File: test_search.py

package info (click to toggle)
python-elasticsearch 9.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 22,728 kB
  • sloc: python: 104,053; makefile: 151; javascript: 75
file content (304 lines) | stat: -rw-r--r-- 9,065 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#  Licensed to Elasticsearch B.V. under one or more contributor
#  license agreements. See the NOTICE file distributed with
#  this work for additional information regarding copyright
#  ownership. Elasticsearch B.V. licenses this file to you 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.


import pytest
from pytest import raises

from elasticsearch import ApiError, AsyncElasticsearch
from elasticsearch.dsl import (
    AsyncDocument,
    AsyncMultiSearch,
    AsyncSearch,
    Date,
    Keyword,
    Q,
    Text,
)
from elasticsearch.dsl.response import aggs

from ..test_data import FLAT_DATA


class Repository(AsyncDocument):
    created_at = Date()
    description = Text(analyzer="snowball")
    tags = Keyword()

    @classmethod
    def search(cls) -> AsyncSearch["Repository"]:  # type: ignore[override]
        return super().search().filter("term", commit_repo="repo")

    class Index:
        name = "git"


class Commit(AsyncDocument):
    class Index:
        name = "flat-git"


@pytest.mark.asyncio
async def test_filters_aggregation_buckets_are_accessible(
    async_data_client: AsyncElasticsearch,
) -> None:
    has_tests_query = Q("term", files="test_elasticsearch_dsl")
    s = Commit.search()[0:0]
    s.aggs.bucket("top_authors", "terms", field="author.name.raw").bucket(
        "has_tests", "filters", filters={"yes": has_tests_query, "no": ~has_tests_query}
    ).metric("lines", "stats", field="stats.lines")

    response = await s.execute()

    assert isinstance(
        response.aggregations.top_authors.buckets[0].has_tests.buckets.yes, aggs.Bucket
    )
    assert (
        35
        == response.aggregations.top_authors.buckets[0].has_tests.buckets.yes.doc_count
    )
    assert (
        228
        == response.aggregations.top_authors.buckets[0].has_tests.buckets.yes.lines.max
    )


@pytest.mark.asyncio
async def test_top_hits_are_wrapped_in_response(
    async_data_client: AsyncElasticsearch,
) -> None:
    s = Commit.search()[0:0]
    s.aggs.bucket("top_authors", "terms", field="author.name.raw").metric(
        "top_commits", "top_hits", size=5
    )
    response = await s.execute()

    top_commits = response.aggregations.top_authors.buckets[0].top_commits
    assert isinstance(top_commits, aggs.TopHitsData)
    assert 5 == len(top_commits)

    hits = [h for h in top_commits]
    assert 5 == len(hits)
    assert isinstance(hits[0], Commit)


@pytest.mark.asyncio
async def test_inner_hits_are_wrapped_in_response(
    async_data_client: AsyncElasticsearch,
) -> None:
    s = AsyncSearch(index="git")[0:1].query(
        "has_parent", parent_type="repo", inner_hits={}, query=Q("match_all")
    )
    response = await s.execute()

    commit = response.hits[0]
    assert isinstance(commit.meta.inner_hits.repo, response.__class__)
    assert repr(commit.meta.inner_hits.repo[0]).startswith(
        "<Hit(git/elasticsearch-dsl-py): "
    )


@pytest.mark.asyncio
async def test_inner_hits_are_serialized_to_dict(
    async_data_client: AsyncElasticsearch,
) -> None:
    s = AsyncSearch(index="git")[0:1].query(
        "has_parent", parent_type="repo", inner_hits={}, query=Q("match_all")
    )
    response = await s.execute()
    d = response.to_dict(recursive=True)
    assert isinstance(d, dict)
    assert isinstance(d["hits"]["hits"][0]["inner_hits"]["repo"], dict)

    # iterating over the results changes the format of the internal AttrDict
    for hit in response:
        pass

    d = response.to_dict(recursive=True)
    assert isinstance(d, dict)
    assert isinstance(d["hits"]["hits"][0]["inner_hits"]["repo"], dict)


@pytest.mark.asyncio
async def test_scan_respects_doc_types(async_data_client: AsyncElasticsearch) -> None:
    repos = [repo async for repo in Repository.search().scan()]

    assert 1 == len(repos)
    assert isinstance(repos[0], Repository)
    assert repos[0].organization == "elasticsearch"


@pytest.mark.asyncio
async def test_scan_iterates_through_all_docs(
    async_data_client: AsyncElasticsearch,
) -> None:
    s = AsyncSearch(index="flat-git")

    commits = [commit async for commit in s.scan()]

    assert 52 == len(commits)
    assert {d["_id"] for d in FLAT_DATA} == {c.meta.id for c in commits}


@pytest.mark.asyncio
async def test_search_after(async_data_client: AsyncElasticsearch) -> None:
    page_size = 7
    s = AsyncSearch(index="flat-git")[:page_size].sort("authored_date")
    commits = []
    while True:
        r = await s.execute()
        commits += r.hits
        if len(r.hits) < page_size:
            break
        s = s.search_after()

    assert 52 == len(commits)
    assert {d["_id"] for d in FLAT_DATA} == {c.meta.id for c in commits}


@pytest.mark.asyncio
async def test_search_after_no_search(async_data_client: AsyncElasticsearch) -> None:
    s = AsyncSearch(index="flat-git")
    with raises(
        ValueError, match="A search must be executed before using search_after"
    ):
        s.search_after()
    await s.count()
    with raises(
        ValueError, match="A search must be executed before using search_after"
    ):
        s.search_after()


@pytest.mark.asyncio
async def test_search_after_no_sort(async_data_client: AsyncElasticsearch) -> None:
    s = AsyncSearch(index="flat-git")
    r = await s.execute()
    with raises(
        ValueError, match="Cannot use search_after when results are not sorted"
    ):
        r.search_after()


@pytest.mark.asyncio
async def test_search_after_no_results(async_data_client: AsyncElasticsearch) -> None:
    s = AsyncSearch(index="flat-git")[:100].sort("authored_date")
    r = await s.execute()
    assert 52 == len(r.hits)
    s = s.search_after()
    r = await s.execute()
    assert 0 == len(r.hits)
    with raises(
        ValueError, match="Cannot use search_after when there are no search results"
    ):
        r.search_after()


@pytest.mark.asyncio
async def test_point_in_time(async_data_client: AsyncElasticsearch) -> None:
    page_size = 7
    commits = []
    async with AsyncSearch(index="flat-git")[:page_size].point_in_time(
        keep_alive="30s"
    ) as s:
        pit_id = s._extra["pit"]["id"]
        while True:
            r = await s.execute()
            commits += r.hits
            if len(r.hits) < page_size:
                break
            s = s.search_after()
            assert pit_id == s._extra["pit"]["id"]
            assert "30s" == s._extra["pit"]["keep_alive"]

    assert 52 == len(commits)
    assert {d["_id"] for d in FLAT_DATA} == {c.meta.id for c in commits}


@pytest.mark.asyncio
async def test_iterate(async_data_client: AsyncElasticsearch) -> None:
    s = AsyncSearch(index="flat-git")

    commits = [commit async for commit in s.iterate()]

    assert 52 == len(commits)
    assert {d["_id"] for d in FLAT_DATA} == {c.meta.id for c in commits}


@pytest.mark.asyncio
async def test_response_is_cached(async_data_client: AsyncElasticsearch) -> None:
    s = Repository.search()
    repos = [repo async for repo in s]

    assert hasattr(s, "_response")
    assert s._response.hits == repos


@pytest.mark.asyncio
async def test_multi_search(async_data_client: AsyncElasticsearch) -> None:
    s1 = Repository.search()
    s2 = AsyncSearch[Repository](index="flat-git")

    ms = AsyncMultiSearch[Repository]()
    ms = ms.add(s1).add(s2)

    r1, r2 = await ms.execute()

    assert 1 == len(r1)
    assert isinstance(r1[0], Repository)
    assert r1._search is s1

    assert 52 == r2.hits.total.value  # type: ignore[attr-defined]
    assert r2._search is s2


@pytest.mark.asyncio
async def test_multi_missing(async_data_client: AsyncElasticsearch) -> None:
    s1 = Repository.search()
    s2 = AsyncSearch[Repository](index="flat-git")
    s3 = AsyncSearch[Repository](index="does_not_exist")

    ms = AsyncMultiSearch[Repository]()
    ms = ms.add(s1).add(s2).add(s3)

    with raises(ApiError):
        await ms.execute()

    r1, r2, r3 = await ms.execute(raise_on_error=False)

    assert 1 == len(r1)
    assert isinstance(r1[0], Repository)
    assert r1._search is s1

    assert 52 == r2.hits.total.value  # type: ignore[attr-defined]
    assert r2._search is s2

    assert r3 is None


@pytest.mark.asyncio
async def test_raw_subfield_can_be_used_in_aggs(
    async_data_client: AsyncElasticsearch,
) -> None:
    s = AsyncSearch(index="git")[0:0]
    s.aggs.bucket("authors", "terms", field="author.name.raw", size=1)

    r = await s.execute()

    authors = r.aggregations.authors
    assert 1 == len(authors)
    assert {"key": "Honza Král", "doc_count": 52} == authors[0]