High level Python client for Elasticsearch


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

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.


pip install elasticsearch-dsl


Please see the examples directory to see some complex examples using elasticsearch-dsl.


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

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

# Elasticsearch 6.x

# Elasticsearch 5.x

# Elasticsearch 2.x

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

Search Example

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

from elasticsearch import Elasticsearch
client = Elasticsearch()

response = client.search(
      "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

client = Elasticsearch()

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:

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

# Define a default Elasticsearch client

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

# 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 = Article.get(id=42)

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


Activate Virtual Environment (virtualenvs):

$ virtualenv venv
$ source venv/bin/activate

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

$ pip install -e '.[develop]'

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

$ python setup.py test

Alternatively, it is possible to use the run_tests.py script in test_elasticsearch_dsl, which wraps pytest, to run subsets of the test suite. Some examples can be seen below:

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

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


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

Contribution Guide

Want to hack on Elasticsearch DSL? Awesome! We have Contribution-Guide.


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


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.

  • Querying a nested object

    Querying a nested object

    What is the proper way to query a nested object? Example: s = Search(using=es).index("my_index").query("nested", path="features", query=Q("term", features__name="foo"))

    The code expects keyword parameters, but specifying a nested field like 'features.name' as keyword parameter is not possible and 'features__name' is not converted into 'features.name'.

    If it's not supported, I could add some code that will properly replace double underscores with periods.

    opened by adriaant 27
  • Can't paginate using elasticsearch_dsl

    Can't paginate using elasticsearch_dsl

    When I want to paginate through the search results, not iterate as the scan does from elasticsearch.helpers.

    My current workaround is something like this

    search = Search()
    # construct your search query
    result = search.params(search_type='scan', scroll='1m').execute()
    scroll_id = result.scroll_id
    # Now start using scroll_id to do the pagination,
    # but I have to use Elasticsearch.scroll which returns dictionaries not a Result object
    client = connections.get_connection()
    while data_to_paginate:
      result = Response(client.scroll(scroll_id, scroll='1m'))

    There probably should be a helper function that should abstract at least the following part

    client = connections.get_connection()
    result = Response(client.scroll(scroll_id, scroll='1m'))

    Maybe even getting the scroll_id from the result. Basically the user probably shouldn't be getting a client and manually constructing a Response object.

    @HonzaKral what do you think? If we agree on the interface I could implement that since I am probably going to do that for my project.

    opened by mamikonyana 26
  • sort results to check if the field exits

    sort results to check if the field exits

    hi, when i sort the search results with sort(), some documents don't exit, so it goes error. a way is to use filter() to check if the documents have the filed to sort. but how to use filter to check if the field exits in the documents?


    opened by wdfsinap 24
  • Feature Request: Sliced Scroll

    Feature Request: Sliced Scroll

    Correct me if I am wrong, but I don't see an option in the DSL for a scan with sliced scroll.


    This would be helpful to return queries faster in specific cases.

    Any current plans to support this?

    enhancement discuss 
    opened by bfgoodrich 22
  • Querying for a range of dates.

    Querying for a range of dates.

    Hello Honza, I'm hoping you might be able to help me out with one last issue i'm having. I need to query for all articles that have 404 errors as a response field and I also need to find all of them from withing the lasts 15 inutes. The issues show up inside of Kibana but they are not showing in my queries.

    I've been having a really hard time getting this to work and there aren't any clear examples of querying in a specific range of time in the docs. Here's my script.

    s = Search(using=es, index= "_all") \
            .query("match", response = "404")\
            .filter('range', timestamp={'from': datetime.datetime.now() - datetime.timedelta(minutes=15), 'to' : datetime.datetime.now() }) #, 'lte': datetime(2010, 10, 9)})
            #.filter("range", '@timestamp': {"gte": "now-15m", "lte": "now"}) #, "lt" : "2014-12-31 1:00:00"}) 
            #filter is for a range of possible times. 
            #.filter("range", timestamp={ "gt":"now -5m","lt":"now" })
    response = s.execute()
    opened by davidawad 22
  • Add Async I/O Support

    Add Async I/O Support

    NOTE: This commit message is outdated and will be updated before merging.

    This commit adds support for async I/O that mirrors the support added to elasticsearch-py in elastic/elasticsearch-py#1203.


    • A new client argument was added to elasticsearch_dsl.connections.create_connection to allow users to provide the elasticsearch._async.AsyncElasticsearch as their preferred client class. Passing AsyncElasticsearch will enable asynchronous behavior in elasticsearch_dsl.
    • Async versions of the FacetedSearch, Index, Mapping, Search, and UpdateByQuery classes have been added to elasticsearch_dsl._async. The paths for these classes mirror the paths for their sync versions. These classes defer to their respective sync classes for all methods that don't perform I/O.
    • Async versions of Document.delete, .get, .init, .mget, .save, and .update have been added to the AsyncDocument class:
      • Document.delete -> AsyncDocument.delete_async
      • Document.get -> AsyncDocument.get_async
      • Document.init -> AsyncDocument.init_async
      • Document.mget -> AsyncDocument.mget_async
      • Document.save -> AsyncDocument.save_async
      • Document.update -> AsyncDocument.update_async
      • NOTE: Why did I choose delete_async over async def delete? Because I felt that async calls should be optional, even when using AsyncDocument. Ideally, these functions would exist directly on the Document class, but the async/await syntax was introduced in Python 3.6 and causes problems for lower versions. Putting the async/await features in a separate file and including that file conditionally based on the Python version solves these problems.
    • Where possible, the existing methods have been refactored to re-use their existing implementation instead of creating duplication.

    Closes #1355.

    opened by jamesbrewerdev 20
  • How to get all results back from search?

    How to get all results back from search?

    After executing a search, the Search hits.total is over 9000. However, when I check the length of hits.hits it is only 10:

    >>> client = Elasticsearch(['http://nightly.apinf.io:14002'])
    >>> search = Search(using=client)
    >>> results = search.execute()
    >>> results.hits.total
    >>> len(results.hits.hits)

    How do I get back all 9611 search results?

    opened by brylie 20
  • Integration of official async ES client into DSL library

    Integration of official async ES client into DSL library

    Hi team,

    Great effort on contributing and maintaining a great layer on top of ES access.

    While there are some discussions around the async integration into the official DSL library like #704 and #556 I did not find any conclusion on that. I did my research and also found there isn't anything existing. While there are some prototypes and suggestions like here I did not see an implementation.

    I was presuming, it could be due to two reasons: Either its really not there and no body has raised a PR yet, (or) this could be a trivial implementation so most users took care by overriding the parent classes.

    In any case, I needed the integration of the official async python library into DSL. I was experimenting many ways, and something simple yet required to duplicate was to create async_xyz classes on top of the low level APIs that were accessing the es client functions and eventually not awaiting the coroutines from async ES client.

    That said, here is a very basic working/and tested implementation in my fork https://github.com/elastic/elasticsearch-dsl-py/compare/master...vaidsu:master

    Please consider this as a basic prototype implementation and I just started writing tests. I am not sure, if this is good to go, or not. Then if yes, need to understand how far I need to write tests, I am just planning to make all the sync tests runnable on async calls.

    Please let me know. If you like the thought, but have suggestions, also feel free to share -- I am open to contribute back.


    opened by vaidsu 19
  • Allow index settings in Meta.index

    Allow index settings in Meta.index

    Currently, when defining a new DocType you have to create a separate Index object if you wish to configure any index-level settings. With the deprecation of multiple types in elasticsearch 6.0 it might make more sense to just allow the index settings to configurable on the DocType itself in some fashion.

    This would then allow even for situations where given DocType is present in multiple indices (time-based indices for example) meaning its Meta.index would specify a wildcard (products-* for example) and provide settings which would then allow it to generate and save an IndeTemplate and/or create any particular index via the init classmethod.

    Any ideas and feedback is more than welcome!

    Inspired by @3lnc's comment: https://github.com/elastic/elasticsearch-dsl-py/issues/779#issuecomment-350047587

    enhancement discuss 
    opened by honzakral 19
  • How to create a geo_point

    How to create a geo_point

    I am testing an index with geo_point. The mapping is like the following "city": { "properties": { "city": {"type": "string"}, "state": {"type": "string"}, "location": {"type": "geo_point"} } }

    I cannot find the type to import from elasticsearch_dsl. Is "geo_point" supported? If it is, how can I declare a class with attribute of type "geo_point" and create an object of "geo_point"? Thanks.

    opened by Al77056 17
  • problem to save a doctype and the doctype has a field like as String(index='not_analyzed', multi=True)

    problem to save a doctype and the doctype has a field like as String(index='not_analyzed', multi=True)


    Nowadays I have a problemm, I would like to use the DocType class and one of its parameters save as a list of strings, so I defined this:

    class application(DocType):

    short_name = String(index='not_analyzed')
    lic_servers = String(index='not_analyzed', multi=True)
    updated_at = Date()
    class Meta:
        id = ''
    def save(self, ** kwargs):
        self.meta.id = self.short_name
        self.updated_at = datetime.now()
        return super(application,self).save(** kwargs)

    It was to save in elastic searc a document in this form:

    api = application.get(id=my_ID,index=my_index,ignore=404)

    if api == None: api = application(short_name = m)


    res = api.save()

    But I have the problemm that when I have more than one lic_server in this way for example:

    api.lic_servers =>['lic_server1' , 'lic_server2', 'lic_server3', ...... 'lic_serverN']

    I have the problem to save because:

    res = api.save()

    And res = FALSE.

    Could somebody tell me something about this?

    Thanks in advance.

    opened by juandasgandaras 17
  • Query constructor issue with labels containing

    Query constructor issue with labels containing "__"

    If the column name has any __, then the Query constructor is converting into .

    from elasticsearch import Elasticsearch
    from elasticsearch_dsl import Q, Search
                "gte": "2022-10-01",
                "lte": "2022-11-30"

    Constructed resulting query is as follows. As you can see, its converting __ in field name to .

        "range": {
            "some.field_name": {
                "gte": "2022-10-01",
                "lte": "2022-11-30"

    when changed to a hand crafted json, then it works

        "range": {
            "some__field_name": {
                "gte": "2022-10-01",
                "lte": "2022-11-30"

    Let me know if there is a missing step or a known issue and if some work around exists.

    opened by sudheer82 1
  • Get all fields from Documents and their type to validate insert new values

    Get all fields from Documents and their type to validate insert new values

    I want to insert every time value to field in Document Object i crated. To know if the value is valid i want to use Fields and their type with _deserialize method.

    Example: validate Number with correct type without knowing Number is a Float type

    class EsDoc(Document): ----Number = Float()

    doc = EsDoc setattr(doc, 'Number', 't') # don't raise error

    if i want to validate i must know that number is Float to use _deserialize method:

    Float._deserialize(doc, doc.Number) # raise the error i want

    mybe i miss something, there is a way to validate field type without knowing his type? or get his type in some way and then validate by this type?


    opened by AmitMalka94 0
  • Resolve _expand__to_dot default at runtime

    Resolve _expand__to_dot default at runtime

    In the current situation, the default value of _expand__to_dot is bound to True when the module is imported. Changing the EXPAND__TO_DOT has no impact on the default behavior.

    This change would allow the user to set EXPAND__TO_DOT to False as a global default.

    Closes #1633

    opened by SamVermeulen42 0
  • Expand__to_dot variable cannot be used to control the behavior

    Expand__to_dot variable cannot be used to control the behavior


    This pull request: https://github.com/elastic/elasticsearch-dsl-py/pull/809 moved the default for _expand__to_dot to a variable. At load time, the default for _expand__to_dot will already be set to True. Overwriting EXPAND__TO_DOT after the import has not impact.

    The variable would be usable if the default is resolved in the function definition.

    opened by samv-yazzoom 0
  • Inconsistent counts between search() and execute() when using min_score

    Inconsistent counts between search() and execute() when using min_score

    The min_score is a top-level argument in the body, which must currently be injected via:

    s = Search().query().extra(min_score=4.0)

    However, this produces different counts between the count() and the execute() functions because the count() function ignores this extra data.

    Search.to_dict() function:

    if not count:

    Related issue: https://github.com/elastic/elasticsearch-dsl-py/issues/462

    opened by ipsbrittainm 0
SAP HANA Connector in pure Python

SAP HANA Database Client for Python A pure Python client for the SAP HANA Database based on the SAP HANA Database SQL Command Network Protocol. pyhdb

SAP 299 Nov 20, 2022
Generate database table diagram from SQL data definition.

sql2diagram Generate database table diagram from SQL data definition. e.g. "CREATE TABLE ..." See Example below How does it works? Analyze the SQL to

django-cas-ng 1 Feb 08, 2022
Google Cloud Client Library for Python

Google Cloud Python Client Python idiomatic clients for Google Cloud Platform services. Stability levels The development status classifier on PyPI ind

Google APIs 4.1k Jan 01, 2023
Python MYSQL CheatSheet.

Python MYSQL CheatSheet Python mysql cheatsheet. Install Required Windows(WAMP) Download and Install from HERE Linux(LAMP) install packages. sudo apt

Mohammad Dori 4 Jul 15, 2022
New generation PostgreSQL database adapter for the Python programming language

Psycopg 3 -- PostgreSQL database adapter for Python Psycopg 3 is a modern implementation of a PostgreSQL adapter for Python. Installation Quick versio

The Psycopg Team 880 Jan 08, 2023
MinIO Client SDK for Python

MinIO Python SDK for Amazon S3 Compatible Cloud Storage MinIO Python SDK is Simple Storage Service (aka S3) client to perform bucket and object operat

High Performance, Kubernetes Native Object Storage 582 Dec 28, 2022
A wrapper around asyncpg for use with sqlalchemy

asyncpgsa A python library wrapper around asyncpg for use with sqlalchemy Backwards incompatibility notice Since this library is still in pre 1.0 worl

Canopy 404 Dec 03, 2022
Redis Python Client - The Python interface to the Redis key-value store.

redis-py The Python interface to the Redis key-value store. Installation | Contributing | Getting Started | Connecting To Redis Installation redis-py

Redis 11k Jan 08, 2023
A database migrations tool for SQLAlchemy.

Alembic is a database migrations tool written by the author of SQLAlchemy. A migrations tool offers the following functionality: Can emit ALTER statem

SQLAlchemy 1.7k Jan 01, 2023
Create a database, insert data and easily select it with Sqlite

sqliteBasics create a database, insert data and easily select it with Sqlite Watch on YouTube a step by step tutorial explaining this code: https://yo

Mariya 27 Dec 27, 2022
Py2neo is a client library and toolkit for working with Neo4j from within Python

Py2neo Py2neo is a client library and toolkit for working with Neo4j from within Python applications. The library supports both Bolt and HTTP and prov

py2neo.org 1.2k Jan 02, 2023
Simplest SQL mapper in Python, probably

SQL MAPPER Basically what it does is: it executes some SQL thru a database connector you fed it, maps it to some model and gives to u. Also it can cre

2 Nov 07, 2022
High level Python client for Elasticsearch

Elasticsearch DSL Elasticsearch DSL is a high-level library whose aim is to help with writing and running queries against Elasticsearch. It is built o

elastic 3.6k Jan 03, 2023
A Pythonic, object-oriented interface for working with MongoDB.

PyMODM MongoDB has paused the development of PyMODM. If there are any users who want to take over and maintain this project, or if you just have quest

mongodb 345 Dec 25, 2022
DBMS Mini-project: Recruitment Management System

# Hire-ME DBMS Mini-project: Recruitment Management System. 💫 ✨ Features Python + MYSQL using mysql.connector library Recruiter and Client Panel Beau

Karan Gandhi 35 Dec 23, 2022
Redis client for Python asyncio (PEP 3156)

Redis client for Python asyncio. Redis client for the PEP 3156 Python event loop. This Redis library is a completely asynchronous, non-blocking client

Jonathan Slenders 554 Dec 04, 2022
Py2neo is a comprehensive toolkit for working with Neo4j from within Python applications or from the command line.

Py2neo Py2neo is a client library and toolkit for working with Neo4j from within Python applications and from the command line. The library supports b

Nigel Small 1.2k Jan 02, 2023
PubMed Mapper: A Python library that map PubMed XML to Python object

pubmed-mapper: A Python Library that map PubMed XML to Python object 中文文档 1. Philosophy view UML Programmatically access PubMed article is a common ta

灵魂工具人 33 Dec 08, 2022
Sample scripts to show extracting details directly from the AIQUM database

Sample scripts to show extracting details directly from the AIQUM database

1 Nov 19, 2021
Asynchronous interface for peewee ORM powered by asyncio

peewee-async Asynchronous interface for peewee ORM powered by asyncio. Important notes Since version 0.6.0a only peewee 3.5+ is supported If you still

05Bit 666 Dec 30, 2022