Skip to main content

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).

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.

Search Example

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

from elasticsearch import Elasticsearch
client = Elasticsearch()

response = client.search(
    index="my-index",
    body={
      "query": {
        "filtered": {
          "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:

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q

client = Elasticsearch()

s = Search(using=client, index="my-index") \
    .filter("term", category="search") \
    .query("match", title="python")   \
    .query(~Q("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

  • creating a filtered query since .filter() was used

  • 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:

from datetime import datetime
from elasticsearch_dsl import DocType, String, Date, Integer
from elasticsearch_dsl.connections import connections

# Define a default Elasticsearch client
connections.create_connection(hosts=['localhost'])

class Article(DocType):
    title = String(analyzer='snowball', fields={'raw': String(index='not_analyzed')})
    body = String(analyzer='snowball')
    tags = String(index='not_analyzed')
    published_from = Date()
    lines = Integer()

    class Meta:
        index = 'blog'

    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(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:

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()

Documentation

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

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.

Metadata

Release files for elasticsearch-dsl 0.0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for elasticsearch-dsl 0.0.4
File Size Uploaded
elasticsearch-dsl-0.0.4.tar.gz 22.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for elasticsearch-dsl 0.0.4
File Interpreter ABI Platform
elasticsearch_dsl-0.0.4-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 53.9 kB

Release files / elasticsearch-dsl-0.0.4.tar.gz

Download URL elasticsearch-dsl-0.0.4.tar.gz
Size 22.4 kB
Tags Source
SHA-256 checksum
How to use checksums
42854a51e82f8d7e4040a14c4cff67a6879ab015b5254c1f083f9f8941b8e82f
BLAKE2b-256 checksum
How to use checksums
168f1b13e7307ca386b9c9ca00df8e3c190554e41b76d051aca62f65f2e4c925
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / elasticsearch_dsl-0.0.4-py2.py3-none-any.whl

Download URL elasticsearch_dsl-0.0.4-py2.py3-none-any.whl
Size 31.5 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
2b90e57e1527a82ccf27836db00e183125fe30e2843fbfcb983a4216271d0ed2
BLAKE2b-256 checksum
How to use checksums
f47683e932ce972dc8b6b9233c702d42866f5fda1d1f15a33ea27ebcd7204d5d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release history Release notifications | RSS feed

8.18.0

2 release files

8.17.0

2 release files

8.16.0

2 release files

8.15.3

2 release files

8.15.1

2 release files

8.15.0

2 release files

8.14.0

2 release files

8.13.1

2 release files

8.12.0

2 release files

8.11.0

2 release files

8.9.0

2 release files

7.4.1

2 release files

7.4.0

2 release files

7.3.0

2 release files

7.2.1

2 release files

7.2.0

2 release files

7.1.0

2 release files

7.0.0

2 release files

6.4.0

2 release files

6.3.1

2 release files

6.3.0

2 release files

6.2.1

2 release files

6.2.0

2 release files

6.1.0

2 release files

6.0.1

2 release files

6.0.0

2 release files

5.4.0

2 release files

5.3.0

2 release files

5.2.0

2 release files

5.1.0

2 release files

5.0.0

2 release files

2.2.0

2 release files

2.1.0

2 release files

2.0.0

2 release files

0.0.11

2 release files

0.0.10

2 release files

0.0.9

2 release files

0.0.8

2 release files

This release

0.0.4 This release

2 release files

0.0.3

2 release files

0.0.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page