High level Python client for Elasticsearch

Overview

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.

Installation

pip install elasticsearch-dsl

Examples

Please see the 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 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-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 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(
    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:

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
connections.create_connection(hosts=['localhost'])

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:

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

$ 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

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

Contribution Guide

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

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.

Comments
  • 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.

    enhancement 
    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?

    thanks

    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.

    https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-request-scroll.html#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.

    Changes:

    • 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
    9611
    >>> len(results.hits.hits)
    10
    

    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.

    Thanks

    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)

    Hi

    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)

    api.lic_servers.append('lic_server_0')

    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
    Q(
        "range",
        some__field_name={
                "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?

    Thanks

    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

    Hello,

    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:
        d.update(recursive_to_dict(self._extra))
    

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

    opened by ipsbrittainm 0
Releases(v7.4.0)
asyncio compatible driver for elasticsearch

asyncio client library for elasticsearch aioes is a asyncio compatible library for working with Elasticsearch The project is abandoned aioes is not su

null 97 Sep 5, 2022
Pure Python MySQL Client

PyMySQL Table of Contents Requirements Installation Documentation Example Resources License This package contains a pure-Python MySQL client library,

PyMySQL 7.2k Jan 9, 2023
Python client for Apache Kafka

Kafka Python client Python client for the Apache Kafka distributed stream processing system. kafka-python is designed to function much like the offici

Dana Powers 5.1k Jan 8, 2023
Redis Python Client

redis-py The Python interface to the Redis key-value store. Python 2 Compatibility Note redis-py 3.5.x will be the last version of redis-py that suppo

Andy McCurdy 11k Dec 29, 2022
A fast PostgreSQL Database Client Library for Python/asyncio.

asyncpg -- A fast PostgreSQL Database Client Library for Python/asyncio asyncpg is a database interface library designed specifically for PostgreSQL a

magicstack 5.8k Dec 31, 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 4, 2022
Asynchronous Python client for InfluxDB

aioinflux Asynchronous Python client for InfluxDB. Built on top of aiohttp and asyncio. Aioinflux is an alternative to the official InfluxDB Python cl

Gustavo Bezerra 159 Dec 27, 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 1, 2023
python-bigquery Apache-2python-bigquery (🥈34 · ⭐ 3.5K · 📈) - Google BigQuery API client library. Apache-2

Python Client for Google BigQuery Querying massive datasets can be time consuming and expensive without the right hardware and infrastructure. Google

Google APIs 550 Jan 1, 2023
Python client for InfluxDB

InfluxDB-Python InfluxDB-Python is a client for interacting with InfluxDB. Development of this library is maintained by: Github ID URL @aviau (https:/

InfluxData 1.6k Dec 24, 2022
Confluent's Kafka Python Client

Confluent's Python Client for Apache KafkaTM confluent-kafka-python provides a high-level Producer, Consumer and AdminClient compatible with all Apach

Confluent Inc. 3.1k Jan 5, 2023
Python cluster client for the official redis cluster. Redis 3.0+.

redis-py-cluster This client provides a client for redis cluster that was added in redis 3.0. This project is a port of redis-rb-cluster by antirez, w

Grokzen 1.1k Jan 5, 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
Pysolr — Python Solr client

pysolr pysolr is a lightweight Python client for Apache Solr. It provides an interface that queries the server and returns results based on the query.

Haystack Search 626 Dec 1, 2022
PyRemoteSQL is a python SQL client that allows you to connect to your remote server with phpMyAdmin installed.

PyRemoteSQL Python MySQL remote client Basically this is a python SQL client that allows you to connect to your remote server with phpMyAdmin installe

ProbablyX 3 Nov 4, 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 2, 2023
Python version of the TerminusDB client - for TerminusDB API and WOQLpy

TerminusDB Client Python Development status ⚙️ Python Package status ?? Python version of the TerminusDB client - for TerminusDB API and WOQLpy Requir

TerminusDB 66 Dec 2, 2022
CouchDB client built on top of aiohttp (asyncio)

aiocouchdb source: https://github.com/aio-libs/aiocouchdb documentation: http://aiocouchdb.readthedocs.org/en/latest/ license: BSD CouchDB client buil

aio-libs 53 Apr 5, 2022
google-cloud-bigtable Apache-2google-cloud-bigtable (🥈31 · ⭐ 3.5K) - Google Cloud Bigtable API client library. Apache-2

Python Client for Google Cloud Bigtable Google Cloud Bigtable is Google's NoSQL Big Data database service. It's the same database that powers many cor

Google APIs 39 Dec 3, 2022