-
Notifications
You must be signed in to change notification settings - Fork 801
/
Copy path__init__.py
192 lines (153 loc) · 6.46 KB
/
__init__.py
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
# 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.
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterator,
List,
Optional,
Tuple,
Union,
cast,
)
from ..utils import _R, AttrDict, AttrList, _wrap
from .hit import Hit, HitMeta
if TYPE_CHECKING:
from ..aggs import Agg
from ..faceted_search_base import FacetedSearchBase
from ..search_base import Request, SearchBase
from ..update_by_query_base import UpdateByQueryBase
__all__ = ["Response", "AggResponse", "UpdateByQueryResponse", "Hit", "HitMeta"]
class Response(AttrDict[Any], Generic[_R]):
_search: "SearchBase[_R]"
_faceted_search: "FacetedSearchBase[_R]"
_doc_class: Optional[_R]
_hits: List[_R]
def __init__(
self,
search: "Request[_R]",
response: Dict[str, Any],
doc_class: Optional[_R] = None,
):
super(AttrDict, self).__setattr__("_search", search)
super(AttrDict, self).__setattr__("_doc_class", doc_class)
super().__init__(response)
def __iter__(self) -> Iterator[_R]: # type: ignore[override]
return iter(self.hits)
def __getitem__(self, key: Union[slice, int, str]) -> Any:
if isinstance(key, (slice, int)):
# for slicing etc
return self.hits[key]
return super().__getitem__(key)
def __nonzero__(self) -> bool:
return bool(self.hits)
__bool__ = __nonzero__
def __repr__(self) -> str:
return "<Response: %r>" % (self.hits or self.aggregations)
def __len__(self) -> int:
return len(self.hits)
def __getstate__(self) -> Tuple[Dict[str, Any], "Request[_R]", Optional[_R]]: # type: ignore[override]
return self._d_, self._search, self._doc_class
def __setstate__(
self, state: Tuple[Dict[str, Any], "Request[_R]", Optional[_R]] # type: ignore[override]
) -> None:
super(AttrDict, self).__setattr__("_d_", state[0])
super(AttrDict, self).__setattr__("_search", state[1])
super(AttrDict, self).__setattr__("_doc_class", state[2])
def success(self) -> bool:
return self._shards.total == self._shards.successful and not self.timed_out
@property
def hits(self) -> List[_R]:
if not hasattr(self, "_hits"):
h = cast(AttrDict[Any], self._d_["hits"])
try:
hits = AttrList(list(map(self._search._get_result, h["hits"])))
except AttributeError as e:
# avoid raising AttributeError since it will be hidden by the property
raise TypeError("Could not parse hits.", e)
# avoid assigning _hits into self._d_
super(AttrDict, self).__setattr__("_hits", hits)
for k in h:
setattr(self._hits, k, _wrap(h[k]))
return self._hits
@property
def aggregations(self) -> "AggResponse[_R]":
return self.aggs
@property
def aggs(self) -> "AggResponse[_R]":
if not hasattr(self, "_aggs"):
aggs = AggResponse[_R](
cast("Agg[_R]", self._search.aggs),
self._search,
cast(Dict[str, Any], self._d_.get("aggregations", {})),
)
# avoid assigning _aggs into self._d_
super(AttrDict, self).__setattr__("_aggs", aggs)
return cast("AggResponse[_R]", self._aggs)
def search_after(self) -> "SearchBase[_R]":
"""
Return a ``Search`` instance that retrieves the next page of results.
This method provides an easy way to paginate a long list of results using
the ``search_after`` option. For example::
page_size = 20
s = Search()[:page_size].sort("date")
while True:
# get a page of results
r = await s.execute()
# do something with this page of results
# exit the loop if we reached the end
if len(r.hits) < page_size:
break
# get a search object with the next page of results
s = r.search_after()
Note that the ``search_after`` option requires the search to have an
explicit ``sort`` order.
"""
if len(self.hits) == 0:
raise ValueError("Cannot use search_after when there are no search results")
if not hasattr(self.hits[-1].meta, "sort"): # type: ignore
raise ValueError("Cannot use search_after when results are not sorted")
return self._search.extra(search_after=self.hits[-1].meta.sort) # type: ignore
class AggResponse(AttrDict[Any], Generic[_R]):
_meta: Dict[str, Any]
def __init__(self, aggs: "Agg[_R]", search: "Request[_R]", data: Dict[str, Any]):
super(AttrDict, self).__setattr__("_meta", {"search": search, "aggs": aggs})
super().__init__(data)
def __getitem__(self, attr_name: str) -> Any:
if attr_name in self._meta["aggs"]:
# don't do self._meta['aggs'][attr_name] to avoid copying
agg = self._meta["aggs"].aggs[attr_name]
return agg.result(self._meta["search"], self._d_[attr_name])
return super().__getitem__(attr_name)
def __iter__(self) -> Iterator["Agg"]: # type: ignore[override]
for name in self._meta["aggs"]:
yield self[name]
class UpdateByQueryResponse(AttrDict[Any], Generic[_R]):
_search: "UpdateByQueryBase[_R]"
def __init__(
self,
search: "Request[_R]",
response: Dict[str, Any],
doc_class: Optional[_R] = None,
):
super(AttrDict, self).__setattr__("_search", search)
super(AttrDict, self).__setattr__("_doc_class", doc_class)
super().__init__(response)
def success(self) -> bool:
return not self.timed_out and not self.failures