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)
Find graph motifs using intuitive notation

d o t m o t i f Find graph motifs using intuitive notation DotMotif is a library that identifies subgraphs or motifs in a large graph. It looks like t

APL BRAIN 45 Jan 02, 2023
Official Python low-level client for Elasticsearch

Python Elasticsearch Client Official low-level client for Elasticsearch. Its goal is to provide common ground for all Elasticsearch-related code in Py

elastic 3.8k Jan 01, 2023
Neo4j Bolt driver for Python

Neo4j Bolt Driver for Python This repository contains the official Neo4j driver for Python. Each driver release (from 4.0 upwards) is built specifical

Neo4j 762 Dec 30, 2022
A wrapper for SQLite and MySQL, Most of the queries wrapped into commands for ease.

Before you proceed, make sure you know Some real SQL, before looking at the code, otherwise you probably won't understand anything. Installation pip i

Refined 4 Jul 30, 2022
A Python wheel containing PostgreSQL

postgresql-wheel A Python wheel for Linux containing a complete, self-contained, locally installable PostgreSQL database server. All servers run as th

Michel Pelletier 71 Nov 09, 2022
ClickHouse Python Driver with native interface support

ClickHouse Python Driver ClickHouse Python Driver with native (TCP) interface support. Asynchronous wrapper is available here: https://github.com/myma

Marilyn System 957 Dec 30, 2022
Python Wrapper For sqlite3 and aiosqlite

Python Wrapper For sqlite3 and aiosqlite

6 May 30, 2022
aiomysql is a library for accessing a MySQL database from the asyncio

aiomysql aiomysql is a "driver" for accessing a MySQL database from the asyncio (PEP-3156/tulip) framework. It depends on and reuses most parts of PyM

aio-libs 1.5k Jan 03, 2023
Toolkit for storing files and attachments in web applications

DEPOT - File Storage Made Easy DEPOT is a framework for easily storing and serving files in web applications on Python2.6+ and Python3.2+. DEPOT suppo

Alessandro Molina 139 Dec 25, 2022
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
Prometheus instrumentation library for Python applications

Prometheus Python Client The official Python 2 and 3 client for Prometheus. Three Step Demo One: Install the client: pip install prometheus-client Tw

Prometheus 3.2k Jan 07, 2023
A SQL linter and auto-formatter for Humans

The SQL Linter for Humans SQLFluff is a dialect-flexible and configurable SQL linter. Designed with ELT applications in mind, SQLFluff also works with

SQLFluff 5.5k Jan 08, 2023
Make Your Company Data Driven. Connect to any data source, easily visualize, dashboard and share your data.

Redash is designed to enable anyone, regardless of the level of technical sophistication, to harness the power of data big and small. SQL users levera

Redash 22.4k Dec 30, 2022
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
An extension package of 🤗 Datasets that provides support for executing arbitrary SQL queries on HF datasets

datasets_sql A 🤗 Datasets extension package that provides support for executing arbitrary SQL queries on HF datasets. It uses DuckDB as a SQL engine

Mario Šaško 19 Dec 15, 2022
A Python DB-API and SQLAlchemy dialect to Google Spreasheets

Note: shillelagh is a drop-in replacement for gsheets-db-api, with many additional features. You should use it instead. If you're using SQLAlchemy all

Beto Dealmeida 185 Jan 01, 2023
This repository is for active development of the Azure SDK for Python.

Azure SDK for Python This repository is for active development of the Azure SDK for Python. For consumers of the SDK we recommend visiting our public

Microsoft Azure 3.4k Jan 02, 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
edaSQL is a library to link SQL to Exploratory Data Analysis and further more in the Data Engineering.

edaSQL is a python library to bridge the SQL with Exploratory Data Analysis where you can connect to the Database and insert the queries. The query results can be passed to the EDA tool which can giv

Tamil Selvan 8 Dec 12, 2022
asyncio (PEP 3156) Redis support

aioredis asyncio (PEP 3156) Redis client library. Features hiredis parser Yes Pure-python parser Yes Low-level & High-level APIs Yes Connections Pool

aio-libs 2.2k Jan 04, 2023