Skip to main content

Python client for Elasticsearch

Project description

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 import Elasticsearch
from elasticsearch_dsl import DocType, String, Date, Integer, connections

# Define a default Elasticsearch client
connections.add_connection(Elasticsearch())

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().save(** kwargs)

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

 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 Elasticsearch client

  • 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

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

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

elasticsearch-dsl-0.0.3.tar.gz (19.0 kB view details)

Uploaded Source

Built Distribution

elasticsearch_dsl-0.0.3-py2.py3-none-any.whl (27.3 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file elasticsearch-dsl-0.0.3.tar.gz.

File metadata

File hashes

Hashes for elasticsearch-dsl-0.0.3.tar.gz
Algorithm Hash digest
SHA256 be3b405f67b36f26ef04d34a912252be9b3e4346f1b5f5d02bfd23cc7dd941e8
MD5 6cbc9ed7aefb3ef804be4e3b318b2570
BLAKE2b-256 e3b5f48cf9bdd1ef3520d0076b9bd261526088eb7711e99890b984ab1731ad8d

See more details on using hashes here.

Provenance

File details

Details for the file elasticsearch_dsl-0.0.3-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for elasticsearch_dsl-0.0.3-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 2d46fb1e79bd23d5ea463303c6f5b45356e3dcbc87cde6aee578a83b29d82bc0
MD5 f95c13431af0e4c9b1cd7149b6c1b796
BLAKE2b-256 2304fc6ea0cd5ef345f8404b8185f78a5150a85f15212afb1732e26b5c967e8d

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page