Convert Figma logo to code with AI

elastic logoelasticsearch-dsl-py

High level Python client for Elasticsearch

3,818
801
3,818
47

Top Related Projects

Official Python client for Elasticsearch

7,374

Deprecated: Use the official Elasticsearch client for Go at https://github.com/elastic/go-elasticsearch

Ruby integrations for Elasticsearch

Official Elasticsearch client library for Node.js

This strongly-typed, client library enables working with Elasticsearch. It is the official client maintained and supported by Elastic.

Official PHP client for Elasticsearch.

Quick Overview

Elasticsearch DSL is a high-level library for writing and running queries against Elasticsearch. It provides a more Pythonic way to work with Elasticsearch, offering an object-oriented approach to building queries and aggregations. The library aims to make complex queries more readable and easier to maintain.

Pros

  • Provides a Pythonic interface for Elasticsearch queries
  • Supports complex queries and aggregations with an intuitive API
  • Offers type hinting for better IDE support and code completion
  • Integrates well with other Elasticsearch Python libraries

Cons

  • Learning curve for developers new to Elasticsearch concepts
  • May add overhead for simple queries compared to raw JSON
  • Documentation could be more comprehensive for advanced use cases
  • Limited support for some newer Elasticsearch features

Code Examples

  1. Creating a simple search query:
from elasticsearch_dsl import Search

s = Search(index="my-index").query("match", title="python")
response = s.execute()

for hit in response:
    print(hit.title)
  1. Building a more complex query with filters:
from elasticsearch_dsl import Search, Q

s = Search(index="products")
q = Q("match", category="electronics") & Q("range", price={"gte": 100, "lte": 200})
s = s.query(q)

response = s.execute()
  1. Creating an aggregation:
from elasticsearch_dsl import Search, A

s = Search(index="sales")
s.aggs.bucket("sales_per_month", "date_histogram", field="date", calendar_interval="month")
s.aggs["sales_per_month"].metric("total_sales", "sum", field="amount")

response = s.execute()

Getting Started

To get started with Elasticsearch DSL:

  1. Install the library:

    pip install elasticsearch-dsl
    
  2. Create a connection to Elasticsearch:

    from elasticsearch_dsl import connections
    
    connections.create_connection(hosts=['localhost'])
    
  3. Define a document:

    from elasticsearch_dsl import Document, Keyword, Text, Integer
    
    class Article(Document):
        title = Text()
        body = Text()
        tags = Keyword()
        published_from = Integer()
    
        class Index:
            name = 'blog'
    
  4. Create the index and add a document:

    Article.init()
    
    article = Article(meta={'id': 42}, title='Hello world!', tags=['test'])
    article.body = 'This is a test'
    article.published_from = 2023
    article.save()
    

Competitor Comparisons

Official Python client for Elasticsearch

Pros of elasticsearch-py

  • Lower-level API providing more direct control over Elasticsearch operations
  • Lighter weight and potentially faster for simple queries
  • Closer to Elasticsearch's native JSON query structure

Cons of elasticsearch-py

  • Requires more verbose code for complex queries
  • Less intuitive for developers new to Elasticsearch
  • Lacks high-level abstractions for common operations

Code Comparison

elasticsearch-py:

from elasticsearch import Elasticsearch

es = Elasticsearch()
result = es.search(index="my-index", body={
    "query": {
        "match": {"title": "python"}
    }
})

elasticsearch-dsl-py:

from elasticsearch_dsl import Search, Q

s = Search(index="my-index").query("match", title="python")
response = s.execute()

The elasticsearch-dsl-py library provides a more Pythonic and readable approach to constructing Elasticsearch queries, while elasticsearch-py offers a lower-level interface that closely mirrors the Elasticsearch REST API. The choice between the two depends on the specific needs of your project and your familiarity with Elasticsearch query structures.

7,374

Deprecated: Use the official Elasticsearch client for Go at https://github.com/elastic/go-elasticsearch

Pros of elastic

  • Written in Go, offering better performance and concurrency support
  • More comprehensive API coverage, including support for newer Elasticsearch features
  • Active development with frequent updates and releases

Cons of elastic

  • Steeper learning curve due to more complex API structure
  • Less abstraction, requiring more boilerplate code for common operations
  • Limited query DSL support compared to elasticsearch-dsl-py

Code Comparison

elasticsearch-dsl-py:

from elasticsearch_dsl import Search

s = Search().filter("term", category="search")
s = s.query("match", title="python elasticsearch")
response = s.execute()

elastic:

query := elastic.NewBoolQuery().
    Filter(elastic.NewTermQuery("category", "search")).
    Must(elastic.NewMatchQuery("title", "python elasticsearch"))
result, err := client.Search().Query(query).Do(ctx)

Both libraries provide ways to construct and execute Elasticsearch queries, but elasticsearch-dsl-py offers a more Pythonic and concise syntax. The elastic library, while more verbose, provides finer-grained control over query construction and execution.

elasticsearch-dsl-py is better suited for Python developers looking for an intuitive, high-level abstraction over Elasticsearch operations. elastic is ideal for Go developers who need performance and comprehensive API coverage, and are comfortable with a more detailed, low-level approach to working with Elasticsearch.

Ruby integrations for Elasticsearch

Pros of elasticsearch-ruby

  • Native Ruby implementation, providing idiomatic Ruby syntax and conventions
  • Comprehensive support for Ruby on Rails integration
  • Extensive documentation and examples tailored for Ruby developers

Cons of elasticsearch-ruby

  • Limited DSL capabilities compared to elasticsearch-dsl-py
  • Smaller community and fewer third-party extensions
  • Less flexible query construction for complex search scenarios

Code Comparison

elasticsearch-ruby:

client = Elasticsearch::Client.new
response = client.search(
  index: 'my_index',
  body: { query: { match: { title: 'search' } } }
)

elasticsearch-dsl-py:

from elasticsearch_dsl import Search
s = Search(index='my_index').query('match', title='search')
response = s.execute()

The elasticsearch-ruby example uses a more traditional hash-based approach for constructing queries, while elasticsearch-dsl-py offers a more expressive and chainable DSL for building complex queries.

elasticsearch-ruby is ideal for Ruby developers who prefer working with native Ruby syntax and want seamless integration with Ruby on Rails projects. However, elasticsearch-dsl-py provides a more powerful and flexible DSL for constructing complex queries, which may be beneficial for projects with advanced search requirements.

Both libraries offer similar core functionality for interacting with Elasticsearch, but their syntax and approach to query construction differ significantly. The choice between them often depends on the developer's preferred language and the specific needs of the project.

Official Elasticsearch client library for Node.js

Pros of elasticsearch-js

  • Written in JavaScript, making it ideal for Node.js and browser-based applications
  • Supports both callback and promise-based APIs, offering flexibility in coding style
  • Includes a more comprehensive set of features for interacting with Elasticsearch

Cons of elasticsearch-js

  • Lacks the high-level DSL abstraction provided by elasticsearch-dsl-py
  • May require more verbose code for complex queries compared to the Python DSL

Code Comparison

elasticsearch-js:

const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })

const result = await client.search({
  index: 'my-index',
  body: { query: { match: { title: 'search' } } }
})

elasticsearch-dsl-py:

from elasticsearch_dsl import Search, Q

s = Search(index="my-index").query("match", title="search")
response = s.execute()

The JavaScript version requires more explicit configuration and query structure, while the Python DSL provides a more concise and readable syntax for constructing queries. The Python version abstracts away some of the lower-level details, making it easier to write complex queries with less code. However, the JavaScript client offers more direct control over the Elasticsearch API and may be preferred in JavaScript-centric environments.

This strongly-typed, client library enables working with Elasticsearch. It is the official client maintained and supported by Elastic.

Pros of elasticsearch-net

  • Comprehensive .NET client with strong typing and LINQ support
  • Supports both synchronous and asynchronous operations
  • Extensive documentation and community support

Cons of elasticsearch-net

  • Limited to .NET ecosystem, not suitable for Python developers
  • Steeper learning curve compared to elasticsearch-dsl-py
  • May require more verbose code for simple operations

Code Comparison

elasticsearch-net (.NET):

var searchResponse = await client.SearchAsync<Document>(s => s
    .Query(q => q
        .Match(m => m
            .Field(f => f.Title)
            .Query("elasticsearch")
        )
    )
);

elasticsearch-dsl-py (Python):

s = Search().query("match", title="elasticsearch")
response = s.execute()

Summary

elasticsearch-net is a robust .NET client for Elasticsearch, offering strong typing and LINQ support. It's well-documented and supports both sync and async operations. However, it's limited to the .NET ecosystem and may have a steeper learning curve compared to elasticsearch-dsl-py.

elasticsearch-dsl-py, on the other hand, provides a more Pythonic approach with a simpler syntax for basic operations. It's ideal for Python developers but lacks the strong typing and comprehensive features of elasticsearch-net.

The code comparison illustrates the difference in verbosity and syntax between the two libraries, with elasticsearch-dsl-py offering a more concise approach for simple queries.

Official PHP client for Elasticsearch.

Pros of elasticsearch-php

  • Native PHP implementation, providing better integration with PHP projects
  • Supports all Elasticsearch APIs and features directly
  • Offers more fine-grained control over request construction

Cons of elasticsearch-php

  • Requires more verbose code for complex queries
  • Lacks high-level abstractions for common operations
  • May be more challenging for beginners to use effectively

Code Comparison

elasticsearch-php:

$params = [
    'index' => 'my_index',
    'body'  => [
        'query' => [
            'match' => [
                'title' => 'Search query'
            ]
        ]
    ]
];
$results = $client->search($params);

elasticsearch-dsl-py:

s = Search(using=client, index="my_index") \
    .query("match", title="Search query")
results = s.execute()

The Python DSL provides a more concise and readable syntax for constructing queries, while the PHP client requires a more detailed array structure. The Python version offers a fluent interface, making it easier to chain multiple operations. However, the PHP version gives developers more direct control over the request structure, which can be beneficial for complex or custom queries.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Elasticsearch DSL

Elasticsearch DSL is a high-level library whose aim is to help with writing and running queries against Elasticsearch. It is built on top of the official low-level client (elasticsearch-py <https://github.com/elastic/elasticsearch-py>_).

It provides a more convenient and idiomatic way to write and manipulate queries. It stays close to the Elasticsearch JSON DSL, mirroring its terminology and structure. It exposes the whole range of the DSL from Python either directly using defined classes or a queryset-like expressions.

It also provides an optional wrapper for working with documents as Python objects: defining mappings, retrieving and saving documents, wrapping the document data in user-defined classes.

To use the other Elasticsearch APIs (eg. cluster health) just use the underlying client.

Installation

::

pip install elasticsearch-dsl

Feedback 🗣️

The engineering team here at Elastic is looking for developers to participate in research and feedback sessions to learn more about how you use our Python client and what improvements we can make to their design and your workflow. If you're interested in sharing your insights into developer experience and language client design, please fill out this short form_. Depending on the number of responses we get, we may either contact you for a 1:1 conversation or a focus group with other developers who use the same client. Thank you in advance - your feedback is crucial to improving the user experience for all Elasticsearch developers!

.. _short form: https://forms.gle/bYZwDQXijfhfwshn9

Examples

Please see the examples <https://github.com/elastic/elasticsearch-dsl-py/tree/master/examples>_ directory to see some complex examples using elasticsearch-dsl.

Compatibility

The library is compatible with all Elasticsearch versions since 2.x but you have to use a matching major version:

For Elasticsearch 8.0 and later, use the major version 8 (8.x.y) of the library.

For Elasticsearch 7.0 and later, use the major version 7 (7.x.y) of the library.

For Elasticsearch 6.0 and later, use the major version 6 (6.x.y) of the library.

For Elasticsearch 5.0 and later, use the major version 5 (5.x.y) of the library.

For Elasticsearch 2.0 and later, use the major version 2 (2.x.y) of the library.

The recommended way to set your requirements in your setup.py or requirements.txt is::

# Elasticsearch 8.x
elasticsearch-dsl>=8.0.0,<9.0.0

# Elasticsearch 7.x
elasticsearch-dsl>=7.0.0,<8.0.0

# Elasticsearch 6.x
elasticsearch-dsl>=6.0.0,<7.0.0

# Elasticsearch 5.x
elasticsearch-dsl>=5.0.0,<6.0.0

# Elasticsearch 2.x
elasticsearch-dsl>=2.0.0,<3.0.0

The development is happening on main, older branches only get bugfix releases

Search Example

Let's have a typical search request written directly as a dict:

.. code:: python

from elasticsearch import Elasticsearch
client = Elasticsearch("https://localhost:9200")

response = client.search(
    index="my-index",
    body={
      "query": {
        "bool": {
          "must": [{"match": {"title": "python"}}],
          "must_not": [{"match": {"description": "beta"}}],
          "filter": [{"term": {"category": "search"}}]
        }
      },
      "aggs" : {
        "per_tag": {
          "terms": {"field": "tags"},
          "aggs": {
            "max_lines": {"max": {"field": "lines"}}
          }
        }
      }
    }
)

for hit in response['hits']['hits']:
    print(hit['_score'], hit['_source']['title'])

for tag in response['aggregations']['per_tag']['buckets']:
    print(tag['key'], tag['max_lines']['value'])

The problem with this approach is that it is very verbose, prone to syntax mistakes like incorrect nesting, hard to modify (eg. adding another filter) and definitely not fun to write.

Let's rewrite the example using the Python DSL:

.. code:: python

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

client = Elasticsearch("https://localhost:9200")

s = Search(using=client, index="my-index") \
    .filter("term", category="search") \
    .query("match", title="python")   \
    .exclude("match", description="beta")

s.aggs.bucket('per_tag', 'terms', field='tags') \
    .metric('max_lines', 'max', field='lines')

response = s.execute()

for hit in response:
    print(hit.meta.score, hit.title)

for tag in response.aggregations.per_tag.buckets:
    print(tag.key, tag.max_lines.value)

As you see, the library took care of:

  • creating appropriate Query objects by name (eq. "match")
  • composing queries into a compound bool query
  • putting the term query in a filter context of the bool query
  • providing a convenient access to response data
  • no curly or square brackets everywhere

Persistence Example

Let's have a simple Python class representing an article in a blogging system:

.. code:: python

from datetime import datetime
from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, connections

# Define a default Elasticsearch client
connections.create_connection(hosts="https://localhost:9200")

class Article(Document):
    title = Text(analyzer='snowball', fields={'raw': Keyword()})
    body = Text(analyzer='snowball')
    tags = Keyword()
    published_from = Date()
    lines = Integer()

    class Index:
        name = 'blog'
        settings = {
          "number_of_shards": 2,
        }

    def save(self, ** kwargs):
        self.lines = len(self.body.split())
        return super(Article, self).save(** kwargs)

    def is_published(self):
        return datetime.now() > self.published_from

# create the mappings in elasticsearch
Article.init()

# create and save and article
article = Article(meta={'id': 42}, title='Hello world!', tags=['test'])
article.body = ''' looong text '''
article.published_from = datetime.now()
article.save()

article = Article.get(id=42)
print(article.is_published())

# Display cluster health
print(connections.get_connection().cluster.health())

In this example you can see:

  • providing a default connection
  • defining fields with mapping configuration
  • setting index name
  • defining custom methods
  • overriding the built-in .save() method to hook into the persistence life cycle
  • retrieving and saving the object into Elasticsearch
  • accessing the underlying client for other APIs

You can see more in the persistence chapter of the documentation.

Migration from elasticsearch-py

You don't have to port your entire application to get the benefits of the Python DSL, you can start gradually by creating a Search object from your existing dict, modifying it using the API and serializing it back to a dict:

.. code:: python

body = {...} # insert complicated query here

# Convert to Search object
s = Search.from_dict(body)

# Add some filters, aggregations, queries, ...
s.filter("term", tags="python")

# Convert back to dict to plug back into existing code
body = s.to_dict()

Development

Activate Virtual Environment (virtualenvs <http://docs.python-guide.org/en/latest/dev/virtualenvs/>_):

.. code:: bash

$ virtualenv venv
$ source venv/bin/activate

To install all of the dependencies necessary for development, run:

.. code:: bash

$ pip install -e '.[develop]'

To run all of the tests for elasticsearch-dsl-py, run:

.. code:: bash

$ python setup.py test

Alternatively, it is possible to use the run_tests.py script in test_elasticsearch_dsl, which wraps pytest <http://doc.pytest.org/en/latest/>_, to run subsets of the test suite. Some examples can be seen below:

.. code:: bash

# Run all of the tests in `test_elasticsearch_dsl/test_analysis.py`
$ ./run_tests.py test_analysis.py

# Run only the `test_analyzer_serializes_as_name` test.
$ ./run_tests.py test_analysis.py::test_analyzer_serializes_as_name

pytest will skip tests from test_elasticsearch_dsl/test_integration unless there is an instance of Elasticsearch on which a connection can occur. By default, the test connection is attempted at localhost:9200, based on the defaults specified in the elasticsearch-py Connection <https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch /connection/base.py#L29>_ class. Because running the integration tests will cause destructive changes to the Elasticsearch cluster, only run them when the associated cluster is empty. As such, if the Elasticsearch instance at localhost:9200 does not meet these requirements, it is possible to specify a different test Elasticsearch server through the TEST_ES_SERVER environment variable.

.. code:: bash

$ TEST_ES_SERVER=my-test-server:9201 ./run_tests

Documentation

Documentation is available at https://elasticsearch-dsl.readthedocs.io.

Contribution Guide

Want to hack on Elasticsearch DSL? Awesome! We have Contribution-Guide <https://github.com/elastic/elasticsearch-dsl-py/blob/master/CONTRIBUTING.rst>_.

License

Copyright 2013 Elasticsearch

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.