Package: elasticsearch7-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.Installationpip install elasticsearch-dslExamplesPlease see theexamplesdirectory to see some complex examples usingelasticsearch-dsl.CompatibilityThe library is compatible with all Elasticsearch versions since2.xbut youhave to use a matching major version:ForElasticsearch 7.0and later, use the major version 7 (7.x.y) of the
library.ForElasticsearch 6.0and later, use the major version 6 (6.x.y) of the
library.ForElasticsearch 5.0and later, use the major version 5 (5.x.y) of the
library.ForElasticsearch 2.0and later, use the major version 2 (2.x.y) of the
library.The recommended way to set your requirements in yoursetup.pyorrequirements.txtis:# 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.0The development is happening onmaster, older branches only get bugfix releasesSearch ExampleLet’s have a typical search request written directly as adict:fromelasticsearchimportElasticsearchclient=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"}}}}}})forhitinresponse['hits']['hits']:print(hit['_score'],hit['_source']['title'])fortaginresponse['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:fromelasticsearchimportElasticsearchfromelasticsearch_dslimportSearchclient=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()forhitinresponse:print(hit.meta.score,hit.title)fortaginresponse.aggregations.per_tag.buckets:print(tag.key,tag.max_lines.value)As you see, the library took care of:creating appropriateQueryobjects by name (eq. “match”)composing queries into a compoundboolqueryputting thetermquery in a filter context of theboolqueryproviding a convenient access to response datano curly or square brackets everywherePersistence ExampleLet’s have a simple Python class representing an article in a blogging system:fromdatetimeimportdatetimefromelasticsearch_dslimportDocument,Date,Integer,Keyword,Text,connections# Define a default Elasticsearch clientconnections.create_connection(hosts=['localhost'])classArticle(Document):title=Text(analyzer='snowball',fields={'raw':Keyword()})body=Text(analyzer='snowball')tags=Keyword()published_from=Date()lines=Integer()classIndex:name='blog'settings={"number_of_shards":2,}defsave(self,**kwargs):self.lines=len(self.body.split())returnsuper(Article,self).save(**kwargs)defis_published(self):returndatetime.now()>self.published_from# create the mappings in elasticsearchArticle.init()# create and save and articlearticle=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 healthprint(connections.get_connection().cluster.health())In this example you can see:providing a default connectiondefining fields with mapping configurationsetting index namedefining custom methodsoverriding the built-in.save()method to hook into the persistence
life cycleretrieving and saving the object into Elasticsearchaccessing the underlying client for other APIsYou can see more in the persistence chapter of the documentation.Migration fromelasticsearch-pyYou don’t have to port your entire application to get the benefits of the
Python DSL, you can start gradually by creating aSearchobject from your
existingdict, modifying it using the API and serializing it back to adict:body={...}# insert complicated query here# Convert to Search objects=Search.from_dict(body)# Add some filters, aggregations, queries, ...s.filter("term",tags="python")# Convert back to dict to plug back into existing codebody=s.to_dict()DevelopmentActivate Virtual Environment (virtualenvs):$virtualenvvenv$sourcevenv/bin/activateTo install all of the dependencies necessary for development, run:$pipinstall-e'.[develop]'To run all of the tests forelasticsearch-dsl-py, run:$pythonsetup.pytestAlternatively, it is possible to use therun_tests.pyscript intest_elasticsearch_dsl, which wrapspytest, 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.pytest_analysis.py# Run only the `test_analyzer_serializes_as_name` test.$./run_tests.pytest_analysis.py::test_analyzer_serializes_as_namepytestwill skip tests fromtest_elasticsearch_dsl/test_integrationunless there is an instance of Elasticsearch on which a connection can occur.
By default, the test connection is attempted atlocalhost:9200, based on
the defaults specified in theelasticsearch-pyConnectionclass.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 atlocalhost:9200does not meet these requirements,
it is possible to specify a different test Elasticsearch server through theTEST_ES_SERVERenvironment variable.$TEST_ES_SERVER=my-test-server:9201./run_testsDocumentationDocumentation is available athttps://elasticsearch-dsl.readthedocs.io.Contribution GuideWant to hack on Elasticsearch DSL? Awesome! We haveContribution-Guide.LicenseCopyright 2013 ElasticsearchLicensed 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 athttp://www.apache.org/licenses/LICENSE-2.0Unless 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.