elasticsearch-haystack 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of elasticsearch-haystack might be problematic. Click here for more details.
- elasticsearch_haystack/__about__.py +4 -0
- elasticsearch_haystack/__init__.py +6 -0
- elasticsearch_haystack/bm25_retriever.py +59 -0
- elasticsearch_haystack/document_store.py +308 -0
- elasticsearch_haystack/filters.py +151 -0
- elasticsearch_haystack-0.0.1.dist-info/METADATA +56 -0
- elasticsearch_haystack-0.0.1.dist-info/RECORD +9 -0
- elasticsearch_haystack-0.0.1.dist-info/WHEEL +4 -0
- elasticsearch_haystack-0.0.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present Silvano Cerza <silvanocerza@gmail.com>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
from typing import Any, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
from haystack.preview import component, default_from_dict, default_to_dict
|
|
7
|
+
from haystack.preview.dataclasses import Document
|
|
8
|
+
|
|
9
|
+
from elasticsearch_haystack.document_store import ElasticsearchDocumentStore
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@component
|
|
13
|
+
class ElasticsearchBM25Retriever:
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
*,
|
|
17
|
+
document_store: ElasticsearchDocumentStore,
|
|
18
|
+
filters: Optional[Dict[str, Any]] = None,
|
|
19
|
+
fuzziness: str = "AUTO",
|
|
20
|
+
top_k: int = 10,
|
|
21
|
+
scale_score: bool = True,
|
|
22
|
+
):
|
|
23
|
+
if not isinstance(document_store, ElasticsearchDocumentStore):
|
|
24
|
+
msg = "document_store must be an instance of ElasticsearchDocumentStore"
|
|
25
|
+
raise ValueError(msg)
|
|
26
|
+
|
|
27
|
+
self._document_store = document_store
|
|
28
|
+
self._filters = filters or {}
|
|
29
|
+
self._fuzziness = fuzziness
|
|
30
|
+
self._top_k = top_k
|
|
31
|
+
self._scale_score = scale_score
|
|
32
|
+
|
|
33
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
34
|
+
return default_to_dict(
|
|
35
|
+
self,
|
|
36
|
+
filters=self._filters,
|
|
37
|
+
fuzziness=self._fuzziness,
|
|
38
|
+
top_k=self._top_k,
|
|
39
|
+
scale_score=self._scale_score,
|
|
40
|
+
document_store=self._document_store.to_dict(),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ElasticsearchBM25Retriever":
|
|
45
|
+
data["init_parameters"]["document_store"] = ElasticsearchDocumentStore.from_dict(
|
|
46
|
+
data["init_parameters"]["document_store"]
|
|
47
|
+
)
|
|
48
|
+
return default_from_dict(cls, data)
|
|
49
|
+
|
|
50
|
+
@component.output_types(documents=List[Document])
|
|
51
|
+
def run(self, query: str):
|
|
52
|
+
docs = self._document_store._bm25_retrieval(
|
|
53
|
+
query=query,
|
|
54
|
+
filters=self._filters,
|
|
55
|
+
fuzziness=self._fuzziness,
|
|
56
|
+
top_k=self._top_k,
|
|
57
|
+
scale_score=self._scale_score,
|
|
58
|
+
)
|
|
59
|
+
return {"documents": docs}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present Silvano Cerza <silvanocerza@gmail.com>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Any, Dict, List, Mapping, Optional, Union
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
# There are no import stubs for elastic_transport and elasticsearch so mypy fails
|
|
10
|
+
from elastic_transport import NodeConfig # type: ignore[import-not-found]
|
|
11
|
+
from elasticsearch import Elasticsearch, helpers # type: ignore[import-not-found]
|
|
12
|
+
from haystack.preview import default_from_dict, default_to_dict
|
|
13
|
+
from haystack.preview.dataclasses import Document
|
|
14
|
+
from haystack.preview.document_stores.decorator import document_store
|
|
15
|
+
from haystack.preview.document_stores.errors import DuplicateDocumentError
|
|
16
|
+
from haystack.preview.document_stores.protocols import DuplicatePolicy
|
|
17
|
+
|
|
18
|
+
from elasticsearch_haystack.filters import _normalize_filters
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
Hosts = Union[str, List[Union[str, Mapping[str, Union[str, int]], NodeConfig]]]
|
|
23
|
+
|
|
24
|
+
# document scores are essentially unbounded and will be scaled to values between 0 and 1 if scale_score is set to
|
|
25
|
+
# True (default). Scaling uses the expit function (inverse of the logit function) after applying a scaling factor
|
|
26
|
+
# (e.g., BM25_SCALING_FACTOR for the bm25_retrieval method).
|
|
27
|
+
# Larger scaling factor decreases scaled scores. For example, an input of 10 is scaled to 0.99 with
|
|
28
|
+
# BM25_SCALING_FACTOR=2 but to 0.78 with BM25_SCALING_FACTOR=8 (default). The defaults were chosen empirically.
|
|
29
|
+
# Increase the default if most unscaled scores are larger than expected (>30) and otherwise would incorrectly
|
|
30
|
+
# all be mapped to scores ~1.
|
|
31
|
+
BM25_SCALING_FACTOR = 8
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@document_store
|
|
35
|
+
class ElasticsearchDocumentStore:
|
|
36
|
+
def __init__(self, *, hosts: Optional[Hosts] = None, index: str = "default", **kwargs):
|
|
37
|
+
"""
|
|
38
|
+
Creates a new ElasticsearchDocumentStore instance.
|
|
39
|
+
|
|
40
|
+
For more information on connection parameters, see the official Elasticsearch documentation:
|
|
41
|
+
https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html
|
|
42
|
+
|
|
43
|
+
For the full list of supported kwargs, see the official Elasticsearch reference:
|
|
44
|
+
https://elasticsearch-py.readthedocs.io/en/stable/api.html#module-elasticsearch
|
|
45
|
+
|
|
46
|
+
:param hosts: List of hosts running the Elasticsearch client. Defaults to None
|
|
47
|
+
:param index: Name of index in Elasticsearch, if it doesn't exist it will be created. Defaults to "default"
|
|
48
|
+
:param **kwargs: Optional arguments that ``Elasticsearch`` takes.
|
|
49
|
+
"""
|
|
50
|
+
self._hosts = hosts
|
|
51
|
+
self._client = Elasticsearch(hosts, **kwargs)
|
|
52
|
+
self._index = index
|
|
53
|
+
self._kwargs = kwargs
|
|
54
|
+
|
|
55
|
+
# Check client connection, this will raise if not connected
|
|
56
|
+
self._client.info()
|
|
57
|
+
|
|
58
|
+
# Create the index if it doesn't exist
|
|
59
|
+
if not self._client.indices.exists(index=index):
|
|
60
|
+
self._client.indices.create(index=index)
|
|
61
|
+
|
|
62
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
63
|
+
# This is not the best solution to serialise this class but is the fastest to implement.
|
|
64
|
+
# Not all kwargs types can be serialised to text so this can fail. We must serialise each
|
|
65
|
+
# type explicitly to handle this properly.
|
|
66
|
+
return default_to_dict(
|
|
67
|
+
self,
|
|
68
|
+
hosts=self._hosts,
|
|
69
|
+
index=self._index,
|
|
70
|
+
**self._kwargs,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ElasticsearchDocumentStore":
|
|
75
|
+
return default_from_dict(cls, data)
|
|
76
|
+
|
|
77
|
+
def count_documents(self) -> int:
|
|
78
|
+
"""
|
|
79
|
+
Returns how many documents are present in the document store.
|
|
80
|
+
"""
|
|
81
|
+
return self._client.count(index=self._index)["count"]
|
|
82
|
+
|
|
83
|
+
def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]:
|
|
84
|
+
"""
|
|
85
|
+
Returns the documents that match the filters provided.
|
|
86
|
+
|
|
87
|
+
Filters are defined as nested dictionaries. The keys of the dictionaries can be a logical operator (`"$and"`,
|
|
88
|
+
`"$or"`, `"$not"`), a comparison operator (`"$eq"`, `$ne`, `"$in"`, `$nin`, `"$gt"`, `"$gte"`, `"$lt"`,
|
|
89
|
+
`"$lte"`) or a metadata field name.
|
|
90
|
+
|
|
91
|
+
Logical operator keys take a dictionary of metadata field names and/or logical operators as value. Metadata
|
|
92
|
+
field names take a dictionary of comparison operators as value. Comparison operator keys take a single value or
|
|
93
|
+
(in case of `"$in"`) a list of values as value. If no logical operator is provided, `"$and"` is used as default
|
|
94
|
+
operation. If no comparison operator is provided, `"$eq"` (or `"$in"` if the comparison value is a list) is used
|
|
95
|
+
as default operation.
|
|
96
|
+
|
|
97
|
+
Example:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
filters = {
|
|
101
|
+
"$and": {
|
|
102
|
+
"type": {"$eq": "article"},
|
|
103
|
+
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
|
|
104
|
+
"rating": {"$gte": 3},
|
|
105
|
+
"$or": {
|
|
106
|
+
"genre": {"$in": ["economy", "politics"]},
|
|
107
|
+
"publisher": {"$eq": "nytimes"}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
# or simpler using default operators
|
|
112
|
+
filters = {
|
|
113
|
+
"type": "article",
|
|
114
|
+
"date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
|
|
115
|
+
"rating": {"$gte": 3},
|
|
116
|
+
"$or": {
|
|
117
|
+
"genre": ["economy", "politics"],
|
|
118
|
+
"publisher": "nytimes"
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
To use the same logical operator multiple times on the same level, logical operators can take a list of
|
|
124
|
+
dictionaries as value.
|
|
125
|
+
|
|
126
|
+
Example:
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
filters = {
|
|
130
|
+
"$or": [
|
|
131
|
+
{
|
|
132
|
+
"$and": {
|
|
133
|
+
"Type": "News Paper",
|
|
134
|
+
"Date": {
|
|
135
|
+
"$lt": "2019-01-01"
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
"$and": {
|
|
141
|
+
"Type": "Blog Post",
|
|
142
|
+
"Date": {
|
|
143
|
+
"$gte": "2019-01-01"
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
]
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
:param filters: the filters to apply to the document list.
|
|
152
|
+
:return: a list of Documents that match the given filters.
|
|
153
|
+
"""
|
|
154
|
+
query = {"bool": {"filter": _normalize_filters(filters)}} if filters else None
|
|
155
|
+
|
|
156
|
+
documents: List[Document] = []
|
|
157
|
+
from_ = 0
|
|
158
|
+
# Handle pagination
|
|
159
|
+
while True:
|
|
160
|
+
res = self._client.search(
|
|
161
|
+
index=self._index,
|
|
162
|
+
query=query,
|
|
163
|
+
from_=from_,
|
|
164
|
+
)
|
|
165
|
+
documents.extend(self._deserialize_document(hit) for hit in res["hits"]["hits"])
|
|
166
|
+
from_ = len(documents)
|
|
167
|
+
if from_ >= res["hits"]["total"]["value"]:
|
|
168
|
+
break
|
|
169
|
+
return documents
|
|
170
|
+
|
|
171
|
+
def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.FAIL) -> None:
|
|
172
|
+
"""
|
|
173
|
+
Writes (or overwrites) documents into the store.
|
|
174
|
+
|
|
175
|
+
:param documents: a list of documents.
|
|
176
|
+
:param policy: documents with the same ID count as duplicates. When duplicates are met,
|
|
177
|
+
the store can:
|
|
178
|
+
- skip: keep the existing document and ignore the new one.
|
|
179
|
+
- overwrite: remove the old document and write the new one.
|
|
180
|
+
- fail: an error is raised
|
|
181
|
+
:raises DuplicateDocumentError: Exception trigger on duplicate document if `policy=DuplicatePolicy.FAIL`
|
|
182
|
+
:return: None
|
|
183
|
+
"""
|
|
184
|
+
if len(documents) > 0:
|
|
185
|
+
if not isinstance(documents[0], Document):
|
|
186
|
+
msg = "param 'documents' must contain a list of objects of type Document"
|
|
187
|
+
raise ValueError(msg)
|
|
188
|
+
|
|
189
|
+
action = "index" if policy == DuplicatePolicy.OVERWRITE else "create"
|
|
190
|
+
_, errors = helpers.bulk(
|
|
191
|
+
client=self._client,
|
|
192
|
+
actions=(
|
|
193
|
+
{
|
|
194
|
+
"_op_type": action,
|
|
195
|
+
"_id": doc.id,
|
|
196
|
+
"_source": doc.to_dict(),
|
|
197
|
+
}
|
|
198
|
+
for doc in documents
|
|
199
|
+
),
|
|
200
|
+
refresh="wait_for",
|
|
201
|
+
index=self._index,
|
|
202
|
+
raise_on_error=False,
|
|
203
|
+
)
|
|
204
|
+
if errors and policy == DuplicatePolicy.FAIL:
|
|
205
|
+
# TODO: Handle errors in a better way, we're assuming that all errors
|
|
206
|
+
# are related to duplicate documents but that could be very well be wrong.
|
|
207
|
+
|
|
208
|
+
# mypy complains that `errors`` could be either `int` or a `list` of `dict`s.
|
|
209
|
+
# Since the type depends on the parameters passed to `helpers.bulk()`` we know
|
|
210
|
+
# for sure that it will be a `list`.
|
|
211
|
+
ids = ", ".join(e["create"]["_id"] for e in errors) # type: ignore[union-attr]
|
|
212
|
+
msg = f"IDs '{ids}' already exist in the document store."
|
|
213
|
+
raise DuplicateDocumentError(msg)
|
|
214
|
+
|
|
215
|
+
def _deserialize_document(self, hit: Dict[str, Any]) -> Document:
|
|
216
|
+
"""
|
|
217
|
+
Creates a Document from the search hit provided.
|
|
218
|
+
This is mostly useful in self.filter_documents().
|
|
219
|
+
"""
|
|
220
|
+
data = hit["_source"]
|
|
221
|
+
|
|
222
|
+
if "highlight" in hit:
|
|
223
|
+
data["metadata"]["highlighted"] = hit["highlight"]
|
|
224
|
+
data["score"] = hit["_score"]
|
|
225
|
+
|
|
226
|
+
return Document.from_dict(data)
|
|
227
|
+
|
|
228
|
+
def delete_documents(self, document_ids: List[str]) -> None:
|
|
229
|
+
"""
|
|
230
|
+
Deletes all documents with a matching document_ids from the document store.
|
|
231
|
+
|
|
232
|
+
:param object_ids: the object_ids to delete
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
#
|
|
236
|
+
helpers.bulk(
|
|
237
|
+
client=self._client,
|
|
238
|
+
actions=({"_op_type": "delete", "_id": id_} for id_ in document_ids),
|
|
239
|
+
refresh="wait_for",
|
|
240
|
+
index=self._index,
|
|
241
|
+
raise_on_error=False,
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
def _bm25_retrieval(
|
|
245
|
+
self,
|
|
246
|
+
query: str,
|
|
247
|
+
*,
|
|
248
|
+
filters: Optional[Dict[str, Any]] = None,
|
|
249
|
+
fuzziness: str = "AUTO",
|
|
250
|
+
top_k: int = 10,
|
|
251
|
+
scale_score: bool = True,
|
|
252
|
+
) -> List[Document]:
|
|
253
|
+
"""
|
|
254
|
+
Elasticsearch by defaults uses BM25 search algorithm.
|
|
255
|
+
Even though this method is called `bm25_retrieval` it searches for `query`
|
|
256
|
+
using the search algorithm `_client` was configured with.
|
|
257
|
+
|
|
258
|
+
This method is not mean to be part of the public interface of
|
|
259
|
+
`ElasticsearchDocumentStore` nor called directly.
|
|
260
|
+
`ElasticsearchBM25Retriever` uses this method directly and is the public interface for it.
|
|
261
|
+
|
|
262
|
+
`query` must be a non empty string, otherwise a `ValueError` will be raised.
|
|
263
|
+
|
|
264
|
+
:param query: String to search in saved Documents' text.
|
|
265
|
+
:param filters: Filters applied to the retrieved Documents, for more info
|
|
266
|
+
see `ElasticsearchDocumentStore.filter_documents`, defaults to None
|
|
267
|
+
:param fuzziness: Fuzziness parameter passed to Elasticsearch, defaults to "AUTO".
|
|
268
|
+
see the official documentation for valid values:
|
|
269
|
+
https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness
|
|
270
|
+
:param top_k: Maximum number of Documents to return, defaults to 10
|
|
271
|
+
:param scale_score: If `True` scales the Document`s scores between 0 and 1, defaults to True
|
|
272
|
+
:raises ValueError: If `query` is an empty string
|
|
273
|
+
:return: List of Document that match `query`
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
if not query:
|
|
277
|
+
msg = "query must be a non empty string"
|
|
278
|
+
raise ValueError(msg)
|
|
279
|
+
|
|
280
|
+
body: Dict[str, Any] = {
|
|
281
|
+
"size": top_k,
|
|
282
|
+
"query": {
|
|
283
|
+
"bool": {
|
|
284
|
+
"must": [
|
|
285
|
+
{
|
|
286
|
+
"multi_match": {
|
|
287
|
+
"query": query,
|
|
288
|
+
"fuzziness": fuzziness,
|
|
289
|
+
"type": "most_fields",
|
|
290
|
+
"operator": "AND",
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
]
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if filters:
|
|
299
|
+
body["query"]["bool"]["filter"] = _normalize_filters(filters)
|
|
300
|
+
|
|
301
|
+
res = self._client.search(index=self._index, **body)
|
|
302
|
+
|
|
303
|
+
docs = []
|
|
304
|
+
for hit in res["hits"]["hits"]:
|
|
305
|
+
if scale_score:
|
|
306
|
+
hit["_score"] = float(1 / (1 + np.exp(-np.asarray(hit["_score"] / BM25_SCALING_FACTOR))))
|
|
307
|
+
docs.append(self._deserialize_document(hit))
|
|
308
|
+
return docs
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Union
|
|
2
|
+
|
|
3
|
+
from haystack.preview.errors import FilterError
|
|
4
|
+
from pandas import DataFrame
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _normalize_filters(filters: Union[List[Dict], Dict], logical_condition="") -> Dict[str, Any]:
|
|
8
|
+
"""
|
|
9
|
+
Converts Haystack filters in ElasticSearch compatible filters.
|
|
10
|
+
"""
|
|
11
|
+
if not isinstance(filters, dict) and not isinstance(filters, list):
|
|
12
|
+
msg = "Filters must be either a dictionary or a list"
|
|
13
|
+
raise FilterError(msg)
|
|
14
|
+
conditions = []
|
|
15
|
+
if isinstance(filters, dict):
|
|
16
|
+
filters = [filters]
|
|
17
|
+
for filter_ in filters:
|
|
18
|
+
for operator, value in filter_.items():
|
|
19
|
+
if operator in ["$not", "$and", "$or"]:
|
|
20
|
+
# Logical operators
|
|
21
|
+
conditions.append(_normalize_filters(value, operator))
|
|
22
|
+
else:
|
|
23
|
+
# Comparison operators
|
|
24
|
+
conditions.extend(_parse_comparison(operator, value))
|
|
25
|
+
|
|
26
|
+
if len(conditions) > 1:
|
|
27
|
+
conditions = _normalize_ranges(conditions)
|
|
28
|
+
else:
|
|
29
|
+
# mypy is complaining we're assigning a dict to a list of dicts.
|
|
30
|
+
# We're ok with this as we're returning right after this.
|
|
31
|
+
conditions = conditions[0] # type: ignore[assignment]
|
|
32
|
+
|
|
33
|
+
if logical_condition == "$not":
|
|
34
|
+
return {"bool": {"must_not": conditions}}
|
|
35
|
+
elif logical_condition == "$or":
|
|
36
|
+
return {"bool": {"should": conditions}}
|
|
37
|
+
|
|
38
|
+
# If no logical condition is specified we default to "$and"
|
|
39
|
+
return {"bool": {"must": conditions}}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _parse_comparison(field: str, comparison: Union[Dict, List, str, float]) -> List:
|
|
43
|
+
result: List[Dict[str, Any]] = []
|
|
44
|
+
if isinstance(comparison, dict):
|
|
45
|
+
for comparator, val in comparison.items():
|
|
46
|
+
if isinstance(val, DataFrame):
|
|
47
|
+
# Ruff is complaining we're overriding the loop variable `var`
|
|
48
|
+
# but we actually want to override it. So we ignore the error.
|
|
49
|
+
val = val.to_json() # noqa: PLW2901
|
|
50
|
+
if comparator == "$eq":
|
|
51
|
+
if isinstance(val, list):
|
|
52
|
+
result.append(
|
|
53
|
+
{
|
|
54
|
+
"terms_set": {
|
|
55
|
+
field: {
|
|
56
|
+
"terms": val,
|
|
57
|
+
"minimum_should_match_script": {
|
|
58
|
+
"source": f"Math.max(params.num_terms, doc['{field}'].size())"
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
)
|
|
64
|
+
result.append({"term": {field: val}})
|
|
65
|
+
elif comparator == "$ne":
|
|
66
|
+
if isinstance(val, list):
|
|
67
|
+
result.append({"bool": {"must_not": {"terms": {field: val}}}})
|
|
68
|
+
else:
|
|
69
|
+
result.append(
|
|
70
|
+
{"bool": {"must_not": {"match": {field: {"query": val, "minimum_should_match": "100%"}}}}}
|
|
71
|
+
)
|
|
72
|
+
elif comparator == "$in":
|
|
73
|
+
if not isinstance(val, list):
|
|
74
|
+
msg = f"{field}'s value must be a list when using '{comparator}' comparator"
|
|
75
|
+
raise FilterError(msg)
|
|
76
|
+
result.append({"terms": {field: val}})
|
|
77
|
+
elif comparator == "$nin":
|
|
78
|
+
if not isinstance(val, list):
|
|
79
|
+
msg = f"{field}'s value must be a list when using '{comparator}' comparator"
|
|
80
|
+
raise FilterError(msg)
|
|
81
|
+
result.append({"bool": {"must_not": {"terms": {field: val}}}})
|
|
82
|
+
elif comparator in ["$gt", "$gte", "$lt", "$lte"]:
|
|
83
|
+
if not isinstance(val, str) and not isinstance(val, int) and not isinstance(val, float):
|
|
84
|
+
msg = f"{field}'s value must be 'str', 'int', 'float' types when using '{comparator}' comparator"
|
|
85
|
+
raise FilterError(msg)
|
|
86
|
+
result.append({"range": {field: {comparator[1:]: val}}})
|
|
87
|
+
elif comparator in ["$not", "$or"]:
|
|
88
|
+
if isinstance(val, list):
|
|
89
|
+
# This handles corner cases like this:
|
|
90
|
+
# `{"name": {"$or": [{"$eq": "name_0"}, {"$eq": "name_1"}]}}`
|
|
91
|
+
# If we don't handle it like this we'd lose the "name" field and the
|
|
92
|
+
# generated query would be wrong and return unexpected results.
|
|
93
|
+
comparisons = [_parse_comparison(field, v)[0] for v in val]
|
|
94
|
+
if comparator == "$not":
|
|
95
|
+
result.append({"bool": {"must_not": comparisons}})
|
|
96
|
+
elif comparator == "$or":
|
|
97
|
+
result.append({"bool": {"should": comparisons}})
|
|
98
|
+
else:
|
|
99
|
+
result.append(_normalize_filters(val, comparator))
|
|
100
|
+
elif comparator == "$and" and isinstance(val, list):
|
|
101
|
+
# We're assuming there are no duplicate items in the list
|
|
102
|
+
flat_filters = {k: v for d in val for k, v in d.items()}
|
|
103
|
+
result.extend(_parse_comparison(field, flat_filters))
|
|
104
|
+
elif comparator == "$and":
|
|
105
|
+
result.append(_normalize_filters({field: val}, comparator))
|
|
106
|
+
else:
|
|
107
|
+
msg = f"Unknown comparator '{comparator}'"
|
|
108
|
+
raise FilterError(msg)
|
|
109
|
+
elif isinstance(comparison, list):
|
|
110
|
+
result.append({"terms": {field: comparison}})
|
|
111
|
+
elif isinstance(comparison, DataFrame):
|
|
112
|
+
result.append({"match": {field: {"query": comparison.to_json(), "minimum_should_match": "100%"}}})
|
|
113
|
+
elif isinstance(comparison, str):
|
|
114
|
+
# We can't use "term" for text fields as ElasticSearch changes the value of text.
|
|
115
|
+
# More info here:
|
|
116
|
+
# https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html#query-dsl-term-query
|
|
117
|
+
result.append({"match": {field: {"query": comparison, "minimum_should_match": "100%"}}})
|
|
118
|
+
else:
|
|
119
|
+
result.append({"term": {field: comparison}})
|
|
120
|
+
return result
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _normalize_ranges(conditions: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
124
|
+
"""
|
|
125
|
+
Merges range conditions acting on a same field.
|
|
126
|
+
|
|
127
|
+
Example usage:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
conditions = [
|
|
131
|
+
{"range": {"date": {"lt": "2021-01-01"}}},
|
|
132
|
+
{"range": {"date": {"gte": "2015-01-01"}}},
|
|
133
|
+
]
|
|
134
|
+
conditions = _normalize_ranges(conditions)
|
|
135
|
+
assert conditions == [
|
|
136
|
+
{"range": {"date": {"lt": "2021-01-01", "gte": "2015-01-01"}}},
|
|
137
|
+
]
|
|
138
|
+
```
|
|
139
|
+
"""
|
|
140
|
+
range_conditions = [next(iter(c["range"].items())) for c in conditions if "range" in c]
|
|
141
|
+
if range_conditions:
|
|
142
|
+
conditions = [c for c in conditions if "range" not in c]
|
|
143
|
+
range_conditions_dict: Dict[str, Any] = {}
|
|
144
|
+
for field_name, comparison in range_conditions:
|
|
145
|
+
if field_name not in range_conditions_dict:
|
|
146
|
+
range_conditions_dict[field_name] = {}
|
|
147
|
+
range_conditions_dict[field_name].update(comparison)
|
|
148
|
+
|
|
149
|
+
for field_name, comparisons in range_conditions_dict.items():
|
|
150
|
+
conditions.append({"range": {field_name: comparisons}})
|
|
151
|
+
return conditions
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: elasticsearch-haystack
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Haystack 2.x Document Store for ElasticSearch
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/document_stores/elasticsearch#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/document_stores/elasticsearch
|
|
8
|
+
Author-email: Silvano Cerza <silvanocerza@gmail.com>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Requires-Dist: elasticsearch<9,>=8
|
|
21
|
+
Requires-Dist: haystack-ai
|
|
22
|
+
Requires-Dist: typing-extensions
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
[](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/document_stores_elasticsearch.yml)
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/elasticsearch-haystack)
|
|
28
|
+
[](https://pypi.org/project/elasticsearch-haystack)
|
|
29
|
+
|
|
30
|
+
# Elasticsearch Document Store
|
|
31
|
+
|
|
32
|
+
Document Store for Haystack 2.x, supports ElasticSearch 8.
|
|
33
|
+
|
|
34
|
+
## Installation
|
|
35
|
+
|
|
36
|
+
```console
|
|
37
|
+
pip install elasticsearch-haystack
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Testing
|
|
41
|
+
|
|
42
|
+
To run tests first start a Docker container running ElasticSearch. We provide a utility `docker-compose.yml` for that:
|
|
43
|
+
|
|
44
|
+
```console
|
|
45
|
+
docker-compose up
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Then run tests:
|
|
49
|
+
|
|
50
|
+
```console
|
|
51
|
+
hatch run test
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## License
|
|
55
|
+
|
|
56
|
+
`elasticsearch-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
elasticsearch_haystack/__about__.py,sha256=IDuWJELihTuNWFXTXOWzkNA5kuxeynOeS0gu2154R6k,140
|
|
2
|
+
elasticsearch_haystack/__init__.py,sha256=rIdDqIKAEAEgQaVw2UCvMynweiCgVGzapZYAWOtdWqM,237
|
|
3
|
+
elasticsearch_haystack/bm25_retriever.py,sha256=pSj2geUWDAHYfcLlexthKWR6F5YGA35e45l9t8Cw3Bw,1997
|
|
4
|
+
elasticsearch_haystack/document_store.py,sha256=YjdwbHDWXgdhyduMvqPKh814ml4gGOXs7R6tUwbMDyE,12470
|
|
5
|
+
elasticsearch_haystack/filters.py,sha256=9kPEVBj2GpXj17vOBUWNCZyb6vC1T_BgDit1SCCFkzw,7069
|
|
6
|
+
elasticsearch_haystack-0.0.1.dist-info/METADATA,sha256=R0aBD9kpCPJCHDzFPkCgnur3Bh-cTunHwf6am24eOM0,2176
|
|
7
|
+
elasticsearch_haystack-0.0.1.dist-info/WHEEL,sha256=9QBuHhg6FNW7lppboF2vKVbCGTVzsFykgRQjjlajrhA,87
|
|
8
|
+
elasticsearch_haystack-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
9
|
+
elasticsearch_haystack-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|