• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

elasticsearch_dsl/H17-Sep-2020-5,8834,081

elasticsearch_dsl.egg-info/H03-May-2022-347241

AUTHORSH A D02-Jun-2020136 32

CONTRIBUTING.rstH A D02-Jun-20201.9 KiB4332

Changelog.rstH A D17-Sep-202012.5 KiB323257

LICENSEH A D02-Jun-20209.9 KiB177149

MANIFEST.inH A D02-Jun-202094 65

PKG-INFOH A D17-Sep-202012.7 KiB347241

READMEH A D02-Jun-20209 KiB318212

setup.cfgH A D17-Sep-2020134 139

setup.pyH A D17-Sep-20202.9 KiB8358

README

1Elasticsearch DSL
2=================
3
4Elasticsearch DSL is a high-level library whose aim is to help with writing and
5running queries against Elasticsearch. It is built on top of the official
6low-level client (`elasticsearch-py <https://github.com/elastic/elasticsearch-py>`_).
7
8It provides a more convenient and idiomatic way to write and manipulate
9queries. It stays close to the Elasticsearch JSON DSL, mirroring its
10terminology and structure. It exposes the whole range of the DSL from Python
11either directly using defined classes or a queryset-like expressions.
12
13It also provides an optional wrapper for working with documents as Python
14objects: defining mappings, retrieving and saving documents, wrapping the
15document data in user-defined classes.
16
17To use the other Elasticsearch APIs (eg. cluster health) just use the
18underlying client.
19
20Installation
21------------
22
23::
24
25  pip install elasticsearch-dsl
26
27Examples
28--------
29
30Please see the `examples
31<https://github.com/elastic/elasticsearch-dsl-py/tree/master/examples>`_
32directory to see some complex examples using ``elasticsearch-dsl``.
33
34Compatibility
35-------------
36
37The library is compatible with all Elasticsearch versions since ``2.x`` but you
38**have to use a matching major version**:
39
40For **Elasticsearch 7.0** and later, use the major version 7 (``7.x.y``) of the
41library.
42
43For **Elasticsearch 6.0** and later, use the major version 6 (``6.x.y``) of the
44library.
45
46For **Elasticsearch 5.0** and later, use the major version 5 (``5.x.y``) of the
47library.
48
49For **Elasticsearch 2.0** and later, use the major version 2 (``2.x.y``) of the
50library.
51
52
53The recommended way to set your requirements in your `setup.py` or
54`requirements.txt` is::
55
56    # Elasticsearch 7.x
57    elasticsearch-dsl>=7.0.0,<8.0.0
58
59    # Elasticsearch 6.x
60    elasticsearch-dsl>=6.0.0,<7.0.0
61
62    # Elasticsearch 5.x
63    elasticsearch-dsl>=5.0.0,<6.0.0
64
65    # Elasticsearch 2.x
66    elasticsearch-dsl>=2.0.0,<3.0.0
67
68
69The development is happening on ``master``, older branches only get bugfix releases
70
71Search Example
72--------------
73
74Let's have a typical search request written directly as a ``dict``:
75
76.. code:: python
77
78    from elasticsearch import Elasticsearch
79    client = Elasticsearch()
80
81    response = client.search(
82        index="my-index",
83        body={
84          "query": {
85            "bool": {
86              "must": [{"match": {"title": "python"}}],
87              "must_not": [{"match": {"description": "beta"}}],
88              "filter": [{"term": {"category": "search"}}]
89            }
90          },
91          "aggs" : {
92            "per_tag": {
93              "terms": {"field": "tags"},
94              "aggs": {
95                "max_lines": {"max": {"field": "lines"}}
96              }
97            }
98          }
99        }
100    )
101
102    for hit in response['hits']['hits']:
103        print(hit['_score'], hit['_source']['title'])
104
105    for tag in response['aggregations']['per_tag']['buckets']:
106        print(tag['key'], tag['max_lines']['value'])
107
108
109
110The problem with this approach is that it is very verbose, prone to syntax
111mistakes like incorrect nesting, hard to modify (eg. adding another filter) and
112definitely not fun to write.
113
114Let's rewrite the example using the Python DSL:
115
116.. code:: python
117
118    from elasticsearch import Elasticsearch
119    from elasticsearch_dsl import Search
120
121    client = Elasticsearch()
122
123    s = Search(using=client, index="my-index") \
124        .filter("term", category="search") \
125        .query("match", title="python")   \
126        .exclude("match", description="beta")
127
128    s.aggs.bucket('per_tag', 'terms', field='tags') \
129        .metric('max_lines', 'max', field='lines')
130
131    response = s.execute()
132
133    for hit in response:
134        print(hit.meta.score, hit.title)
135
136    for tag in response.aggregations.per_tag.buckets:
137        print(tag.key, tag.max_lines.value)
138
139As you see, the library took care of:
140
141  * creating appropriate ``Query`` objects by name (eq. "match")
142
143  * composing queries into a compound ``bool`` query
144
145  * putting the ``term`` query in a filter context of the ``bool`` query
146
147  * providing a convenient access to response data
148
149  * no curly or square brackets everywhere
150
151
152Persistence Example
153-------------------
154
155Let's have a simple Python class representing an article in a blogging system:
156
157.. code:: python
158
159    from datetime import datetime
160    from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, connections
161
162    # Define a default Elasticsearch client
163    connections.create_connection(hosts=['localhost'])
164
165    class Article(Document):
166        title = Text(analyzer='snowball', fields={'raw': Keyword()})
167        body = Text(analyzer='snowball')
168        tags = Keyword()
169        published_from = Date()
170        lines = Integer()
171
172        class Index:
173            name = 'blog'
174            settings = {
175              "number_of_shards": 2,
176            }
177
178        def save(self, ** kwargs):
179            self.lines = len(self.body.split())
180            return super(Article, self).save(** kwargs)
181
182        def is_published(self):
183            return datetime.now() > self.published_from
184
185    # create the mappings in elasticsearch
186    Article.init()
187
188    # create and save and article
189    article = Article(meta={'id': 42}, title='Hello world!', tags=['test'])
190    article.body = ''' looong text '''
191    article.published_from = datetime.now()
192    article.save()
193
194    article = Article.get(id=42)
195    print(article.is_published())
196
197    # Display cluster health
198    print(connections.get_connection().cluster.health())
199
200
201In this example you can see:
202
203  * providing a default connection
204
205  * defining fields with mapping configuration
206
207  * setting index name
208
209  * defining custom methods
210
211  * overriding the built-in ``.save()`` method to hook into the persistence
212    life cycle
213
214  * retrieving and saving the object into Elasticsearch
215
216  * accessing the underlying client for other APIs
217
218You can see more in the persistence chapter of the documentation.
219
220Migration from ``elasticsearch-py``
221-----------------------------------
222
223You don't have to port your entire application to get the benefits of the
224Python DSL, you can start gradually by creating a ``Search`` object from your
225existing ``dict``, modifying it using the API and serializing it back to a
226``dict``:
227
228.. code:: python
229
230    body = {...} # insert complicated query here
231
232    # Convert to Search object
233    s = Search.from_dict(body)
234
235    # Add some filters, aggregations, queries, ...
236    s.filter("term", tags="python")
237
238    # Convert back to dict to plug back into existing code
239    body = s.to_dict()
240
241Development
242-----------
243
244Activate Virtual Environment (`virtualenvs <http://docs.python-guide.org/en/latest/dev/virtualenvs/>`_):
245
246.. code:: bash
247
248    $ virtualenv venv
249    $ source venv/bin/activate
250
251To install all of the dependencies necessary for development, run:
252
253.. code:: bash
254
255    $ pip install -e '.[develop]'
256
257To run all of the tests for ``elasticsearch-dsl-py``, run:
258
259.. code:: bash
260
261    $ python setup.py test
262
263Alternatively, it is possible to use the ``run_tests.py`` script in
264``test_elasticsearch_dsl``, which wraps `pytest
265<http://doc.pytest.org/en/latest/>`_, to run subsets of the test suite. Some
266examples can be seen below:
267
268.. code:: bash
269
270    # Run all of the tests in `test_elasticsearch_dsl/test_analysis.py`
271    $ ./run_tests.py test_analysis.py
272
273    # Run only the `test_analyzer_serializes_as_name` test.
274    $ ./run_tests.py test_analysis.py::test_analyzer_serializes_as_name
275
276``pytest`` will skip tests from ``test_elasticsearch_dsl/test_integration``
277unless there is an instance of Elasticsearch on which a connection can occur.
278By default, the test connection is attempted at ``localhost:9200``, based on
279the defaults specified in the ``elasticsearch-py`` `Connection
280<https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch
281/connection/base.py#L29>`_ class. **Because running the integration
282tests will cause destructive changes to the Elasticsearch cluster, only run
283them when the associated cluster is empty.** As such, if the
284Elasticsearch instance at ``localhost:9200`` does not meet these requirements,
285it is possible to specify a different test Elasticsearch server through the
286``TEST_ES_SERVER`` environment variable.
287
288.. code:: bash
289
290    $ TEST_ES_SERVER=my-test-server:9201 ./run_tests
291
292Documentation
293-------------
294
295Documentation is available at https://elasticsearch-dsl.readthedocs.io.
296
297Contribution Guide
298------------------
299
300Want to hack on Elasticsearch DSL? Awesome! We have `Contribution-Guide <https://github.com/elastic/elasticsearch-dsl-py/blob/master/CONTRIBUTING.rst>`_.
301
302License
303-------
304
305Copyright 2013 Elasticsearch
306
307Licensed under the Apache License, Version 2.0 (the "License");
308you may not use this file except in compliance with the License.
309You may obtain a copy of the License at
310
311    http://www.apache.org/licenses/LICENSE-2.0
312
313Unless required by applicable law or agreed to in writing, software
314distributed under the License is distributed on an "AS IS" BASIS,
315WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
316See the License for the specific language governing permissions and
317limitations under the License.
318