elasticsearch-haystack 1.0.1__py3-none-any.whl → 2.1.0__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-1.0.1.dist-info → elasticsearch_haystack-2.1.0.dist-info}/METADATA +3 -4
- elasticsearch_haystack-2.1.0.dist-info/RECORD +10 -0
- {elasticsearch_haystack-1.0.1.dist-info → elasticsearch_haystack-2.1.0.dist-info}/WHEEL +1 -1
- haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py +24 -1
- haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py +30 -4
- haystack_integrations/document_stores/elasticsearch/document_store.py +330 -66
- haystack_integrations/document_stores/elasticsearch/filters.py +6 -9
- elasticsearch_haystack-1.0.1.dist-info/RECORD +0 -10
- {elasticsearch_haystack-1.0.1.dist-info → elasticsearch_haystack-2.1.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: elasticsearch-haystack
|
|
3
|
-
Version: 1.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: Haystack 2.x Document Store for ElasticSearch
|
|
5
5
|
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/elasticsearch#readme
|
|
6
6
|
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
@@ -11,13 +11,12 @@ License-File: LICENSE
|
|
|
11
11
|
Classifier: Development Status :: 4 - Beta
|
|
12
12
|
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
13
|
Classifier: Programming Language :: Python
|
|
14
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
15
14
|
Classifier: Programming Language :: Python :: 3.9
|
|
16
15
|
Classifier: Programming Language :: Python :: 3.10
|
|
17
16
|
Classifier: Programming Language :: Python :: 3.11
|
|
18
17
|
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
18
|
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
|
-
Requires-Python: >=3.
|
|
19
|
+
Requires-Python: >=3.9
|
|
21
20
|
Requires-Dist: elasticsearch<9,>=8
|
|
22
21
|
Requires-Dist: haystack-ai
|
|
23
22
|
Description-Content-Type: text/markdown
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
haystack_integrations/components/retrievers/elasticsearch/__init__.py,sha256=cSJBsYjz_T4kK-M-auAHVUnYIcgUqqwwQe_hsF0_IG4,307
|
|
2
|
+
haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py,sha256=ISHc6elYXoDXDvC62_3bMMCk_Dv67jvZIgQBCZ1ZHdw,7012
|
|
3
|
+
haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=jHDLMeecpf-DhvbRM1AAq2kIJn7xMNTR9vkm-FhHH7k,7332
|
|
4
|
+
haystack_integrations/document_stores/elasticsearch/__init__.py,sha256=YTfu94dtVUBogbJFr1aJrKuaI6-Bw9VuHfPoyU7M8os,207
|
|
5
|
+
haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=xzMcKhWfVBZUxzzpchcsAf8qWjux-PfZ4zqa8kd4Hcg,28825
|
|
6
|
+
haystack_integrations/document_stores/elasticsearch/filters.py,sha256=Umip-PP4uFjuWeB1JWkKhaKClQ0VpiykoDlDu99wIV0,9759
|
|
7
|
+
elasticsearch_haystack-2.1.0.dist-info/METADATA,sha256=nemE4-8L0_hMZTDkLk6ubi2p4kT1ESaX_OLHD_8QQnQ,2118
|
|
8
|
+
elasticsearch_haystack-2.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
9
|
+
elasticsearch_haystack-2.1.0.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
|
|
10
|
+
elasticsearch_haystack-2.1.0.dist-info/RECORD,,
|
|
@@ -120,7 +120,7 @@ class ElasticsearchBM25Retriever:
|
|
|
120
120
|
"""
|
|
121
121
|
Retrieve documents using the BM25 keyword-based algorithm.
|
|
122
122
|
|
|
123
|
-
:param query: String to search in `Document`s
|
|
123
|
+
:param query: String to search in the `Document`s text.
|
|
124
124
|
:param filters: Filters applied to the retrieved Documents. The way runtime filters are applied depends on
|
|
125
125
|
the `filter_policy` chosen at retriever initialization. See init method docstring for more
|
|
126
126
|
details.
|
|
@@ -137,3 +137,26 @@ class ElasticsearchBM25Retriever:
|
|
|
137
137
|
scale_score=self._scale_score,
|
|
138
138
|
)
|
|
139
139
|
return {"documents": docs}
|
|
140
|
+
|
|
141
|
+
@component.output_types(documents=List[Document])
|
|
142
|
+
async def run_async(self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None):
|
|
143
|
+
"""
|
|
144
|
+
Asynchronously retrieve documents using the BM25 keyword-based algorithm.
|
|
145
|
+
|
|
146
|
+
:param query: String to search in the `Document` text.
|
|
147
|
+
:param filters: Filters applied to the retrieved Documents. The way runtime filters are applied depends on
|
|
148
|
+
the `filter_policy` chosen at retriever initialization. See init method docstring for more
|
|
149
|
+
details.
|
|
150
|
+
:param top_k: Maximum number of `Document` to return.
|
|
151
|
+
:returns: A dictionary with the following keys:
|
|
152
|
+
- `documents`: List of `Document`s that match the query.
|
|
153
|
+
"""
|
|
154
|
+
filters = apply_filter_policy(self._filter_policy, self._filters, filters)
|
|
155
|
+
docs = await self._document_store._bm25_retrieval_async(
|
|
156
|
+
query=query,
|
|
157
|
+
filters=filters,
|
|
158
|
+
fuzziness=self._fuzziness,
|
|
159
|
+
top_k=top_k or self._top_k,
|
|
160
|
+
scale_score=self._scale_score,
|
|
161
|
+
)
|
|
162
|
+
return {"documents": docs}
|
|
@@ -119,10 +119,11 @@ class ElasticsearchEmbeddingRetriever:
|
|
|
119
119
|
Retrieve documents using a vector similarity metric.
|
|
120
120
|
|
|
121
121
|
:param query_embedding: Embedding of the query.
|
|
122
|
-
:param filters: Filters applied
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
122
|
+
:param filters: Filters applied when fetching documents from the Document Store.
|
|
123
|
+
Filters are applied during the approximate kNN search to ensure the Retriever returns
|
|
124
|
+
`top_k` matching documents.
|
|
125
|
+
The way runtime filters are applied depends on the `filter_policy` selected when initializing the Retriever.
|
|
126
|
+
:param top_k: Maximum number of documents to return.
|
|
126
127
|
:returns: A dictionary with the following keys:
|
|
127
128
|
- `documents`: List of `Document`s most similar to the given `query_embedding`
|
|
128
129
|
"""
|
|
@@ -134,3 +135,28 @@ class ElasticsearchEmbeddingRetriever:
|
|
|
134
135
|
num_candidates=self._num_candidates,
|
|
135
136
|
)
|
|
136
137
|
return {"documents": docs}
|
|
138
|
+
|
|
139
|
+
@component.output_types(documents=List[Document])
|
|
140
|
+
async def run_async(
|
|
141
|
+
self, query_embedding: List[float], filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None
|
|
142
|
+
):
|
|
143
|
+
"""
|
|
144
|
+
Asynchronously retrieve documents using a vector similarity metric.
|
|
145
|
+
|
|
146
|
+
:param query_embedding: Embedding of the query.
|
|
147
|
+
:param filters: Filters applied when fetching documents from the Document Store.
|
|
148
|
+
Filters are applied during the approximate kNN search to ensure the Retriever returns
|
|
149
|
+
`top_k` matching documents.
|
|
150
|
+
The way runtime filters are applied depends on the `filter_policy` selected when initializing the Retriever.
|
|
151
|
+
:param top_k: Maximum number of documents to return.
|
|
152
|
+
:returns: A dictionary with the following keys:
|
|
153
|
+
- `documents`: List of `Document`s that match the query.
|
|
154
|
+
"""
|
|
155
|
+
filters = apply_filter_policy(self._filter_policy, self._filters, filters)
|
|
156
|
+
docs = await self._document_store._embedding_retrieval_async(
|
|
157
|
+
query_embedding=query_embedding,
|
|
158
|
+
filters=filters,
|
|
159
|
+
top_k=top_k or self._top_k,
|
|
160
|
+
num_candidates=self._num_candidates,
|
|
161
|
+
)
|
|
162
|
+
return {"documents": docs}
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
#
|
|
3
3
|
# SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
import logging
|
|
5
|
-
from
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any, Dict, List, Literal, Optional, Union
|
|
6
7
|
|
|
7
8
|
import numpy as np
|
|
8
9
|
|
|
@@ -14,7 +15,7 @@ from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumen
|
|
|
14
15
|
from haystack.document_stores.types import DuplicatePolicy
|
|
15
16
|
from haystack.version import __version__ as haystack_version
|
|
16
17
|
|
|
17
|
-
from elasticsearch import Elasticsearch, helpers # type: ignore[import-not-found]
|
|
18
|
+
from elasticsearch import AsyncElasticsearch, Elasticsearch, helpers # type: ignore[import-not-found]
|
|
18
19
|
|
|
19
20
|
from .filters import _normalize_filters
|
|
20
21
|
|
|
@@ -30,6 +31,7 @@ Hosts = Union[str, List[Union[str, Mapping[str, Union[str, int]], NodeConfig]]]
|
|
|
30
31
|
# Increase the default if most unscaled scores are larger than expected (>30) and otherwise would incorrectly
|
|
31
32
|
# all be mapped to scores ~1.
|
|
32
33
|
BM25_SCALING_FACTOR = 8
|
|
34
|
+
DOC_ALREADY_EXISTS = 409
|
|
33
35
|
|
|
34
36
|
|
|
35
37
|
class ElasticsearchDocumentStore:
|
|
@@ -93,28 +95,39 @@ class ElasticsearchDocumentStore:
|
|
|
93
95
|
"""
|
|
94
96
|
self._hosts = hosts
|
|
95
97
|
self._client = None
|
|
98
|
+
self._async_client = None
|
|
96
99
|
self._index = index
|
|
97
100
|
self._embedding_similarity_function = embedding_similarity_function
|
|
98
101
|
self._custom_mapping = custom_mapping
|
|
99
102
|
self._kwargs = kwargs
|
|
103
|
+
self._initialized = False
|
|
100
104
|
|
|
101
105
|
if self._custom_mapping and not isinstance(self._custom_mapping, Dict):
|
|
102
106
|
msg = "custom_mapping must be a dictionary"
|
|
103
107
|
raise ValueError(msg)
|
|
104
108
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
109
|
+
def _ensure_initialized(self):
|
|
110
|
+
"""
|
|
111
|
+
Ensures both sync and async clients are initialized and the index exists.
|
|
112
|
+
"""
|
|
113
|
+
if not self._initialized:
|
|
108
114
|
headers = self._kwargs.pop("headers", {})
|
|
109
115
|
headers["user-agent"] = f"haystack-py-ds/{haystack_version}"
|
|
110
116
|
|
|
111
|
-
|
|
117
|
+
# Initialize both sync and async clients
|
|
118
|
+
self._client = Elasticsearch(
|
|
112
119
|
self._hosts,
|
|
113
120
|
headers=headers,
|
|
114
121
|
**self._kwargs,
|
|
115
122
|
)
|
|
123
|
+
self._async_client = AsyncElasticsearch(
|
|
124
|
+
self._hosts,
|
|
125
|
+
headers=headers,
|
|
126
|
+
**self._kwargs,
|
|
127
|
+
)
|
|
128
|
+
|
|
116
129
|
# Check client connection, this will raise if not connected
|
|
117
|
-
|
|
130
|
+
self._client.info()
|
|
118
131
|
|
|
119
132
|
if self._custom_mapping:
|
|
120
133
|
mappings = self._custom_mapping
|
|
@@ -143,13 +156,27 @@ class ElasticsearchDocumentStore:
|
|
|
143
156
|
}
|
|
144
157
|
|
|
145
158
|
# Create the index if it doesn't exist
|
|
146
|
-
if not
|
|
147
|
-
|
|
159
|
+
if not self._client.indices.exists(index=self._index):
|
|
160
|
+
self._client.indices.create(index=self._index, mappings=mappings)
|
|
148
161
|
|
|
149
|
-
self.
|
|
162
|
+
self._initialized = True
|
|
150
163
|
|
|
164
|
+
@property
|
|
165
|
+
def client(self) -> Elasticsearch:
|
|
166
|
+
"""
|
|
167
|
+
Returns the synchronous Elasticsearch client, initializing it if necessary.
|
|
168
|
+
"""
|
|
169
|
+
self._ensure_initialized()
|
|
151
170
|
return self._client
|
|
152
171
|
|
|
172
|
+
@property
|
|
173
|
+
def async_client(self) -> AsyncElasticsearch:
|
|
174
|
+
"""
|
|
175
|
+
Returns the asynchronous Elasticsearch client, initializing it if necessary.
|
|
176
|
+
"""
|
|
177
|
+
self._ensure_initialized()
|
|
178
|
+
return self._async_client
|
|
179
|
+
|
|
153
180
|
def to_dict(self) -> Dict[str, Any]:
|
|
154
181
|
"""
|
|
155
182
|
Serializes the component to a dictionary.
|
|
@@ -184,15 +211,26 @@ class ElasticsearchDocumentStore:
|
|
|
184
211
|
def count_documents(self) -> int:
|
|
185
212
|
"""
|
|
186
213
|
Returns how many documents are present in the document store.
|
|
187
|
-
|
|
214
|
+
|
|
215
|
+
:returns:
|
|
216
|
+
Number of documents in the document store.
|
|
188
217
|
"""
|
|
218
|
+
self._ensure_initialized()
|
|
189
219
|
return self.client.count(index=self._index)["count"]
|
|
190
220
|
|
|
221
|
+
async def count_documents_async(self) -> int:
|
|
222
|
+
"""
|
|
223
|
+
Asynchronously returns how many documents are present in the document store.
|
|
224
|
+
:returns: Number of documents in the document store.
|
|
225
|
+
"""
|
|
226
|
+
self._ensure_initialized()
|
|
227
|
+
result = await self._async_client.count(index=self._index) # type: ignore
|
|
228
|
+
return result["count"]
|
|
229
|
+
|
|
191
230
|
def _search_documents(self, **kwargs) -> List[Document]:
|
|
192
231
|
"""
|
|
193
232
|
Calls the Elasticsearch client's search method and handles pagination.
|
|
194
233
|
"""
|
|
195
|
-
|
|
196
234
|
top_k = kwargs.get("size")
|
|
197
235
|
if top_k is None and "knn" in kwargs and "k" in kwargs["knn"]:
|
|
198
236
|
top_k = kwargs["knn"]["k"]
|
|
@@ -207,13 +245,38 @@ class ElasticsearchDocumentStore:
|
|
|
207
245
|
**kwargs,
|
|
208
246
|
)
|
|
209
247
|
|
|
210
|
-
documents.extend(self._deserialize_document(hit) for hit in res["hits"]["hits"])
|
|
248
|
+
documents.extend(self._deserialize_document(hit) for hit in res["hits"]["hits"]) # type: ignore
|
|
249
|
+
from_ = len(documents)
|
|
250
|
+
|
|
251
|
+
if top_k is not None and from_ >= top_k:
|
|
252
|
+
break
|
|
253
|
+
if from_ >= res["hits"]["total"]["value"]:
|
|
254
|
+
break
|
|
255
|
+
return documents
|
|
256
|
+
|
|
257
|
+
async def _search_documents_async(self, **kwargs) -> List[Document]:
|
|
258
|
+
"""
|
|
259
|
+
Asynchronously calls the Elasticsearch client's search method and handles pagination.
|
|
260
|
+
"""
|
|
261
|
+
top_k = kwargs.get("size")
|
|
262
|
+
if top_k is None and "knn" in kwargs and "k" in kwargs["knn"]:
|
|
263
|
+
top_k = kwargs["knn"]["k"]
|
|
264
|
+
|
|
265
|
+
documents: List[Document] = []
|
|
266
|
+
from_ = 0
|
|
267
|
+
|
|
268
|
+
# handle pagination
|
|
269
|
+
while True:
|
|
270
|
+
res = await self._async_client.search(index=self._index, from_=from_, **kwargs) # type: ignore
|
|
271
|
+
documents.extend(self._deserialize_document(hit) for hit in res["hits"]["hits"]) # type: ignore
|
|
211
272
|
from_ = len(documents)
|
|
212
273
|
|
|
213
274
|
if top_k is not None and from_ >= top_k:
|
|
214
275
|
break
|
|
276
|
+
|
|
215
277
|
if from_ >= res["hits"]["total"]["value"]:
|
|
216
278
|
break
|
|
279
|
+
|
|
217
280
|
return documents
|
|
218
281
|
|
|
219
282
|
def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]:
|
|
@@ -229,10 +292,54 @@ class ElasticsearchDocumentStore:
|
|
|
229
292
|
msg = "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering for details."
|
|
230
293
|
raise ValueError(msg)
|
|
231
294
|
|
|
295
|
+
self._ensure_initialized()
|
|
232
296
|
query = {"bool": {"filter": _normalize_filters(filters)}} if filters else None
|
|
233
297
|
documents = self._search_documents(query=query)
|
|
234
298
|
return documents
|
|
235
299
|
|
|
300
|
+
async def filter_documents_async(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]:
|
|
301
|
+
"""
|
|
302
|
+
Asynchronously retrieves all documents that match the filters.
|
|
303
|
+
|
|
304
|
+
:param filters: A dictionary of filters to apply. For more information on the structure of the filters,
|
|
305
|
+
see the official Elasticsearch
|
|
306
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html)
|
|
307
|
+
:returns: List of `Document`s that match the filters.
|
|
308
|
+
"""
|
|
309
|
+
if filters and "operator" not in filters and "conditions" not in filters:
|
|
310
|
+
msg = "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering for details."
|
|
311
|
+
raise ValueError(msg)
|
|
312
|
+
|
|
313
|
+
self._ensure_initialized()
|
|
314
|
+
query = {"bool": {"filter": _normalize_filters(filters)}} if filters else None
|
|
315
|
+
documents = await self._search_documents_async(query=query)
|
|
316
|
+
return documents
|
|
317
|
+
|
|
318
|
+
@staticmethod
|
|
319
|
+
def _deserialize_document(hit: Dict[str, Any]) -> Document:
|
|
320
|
+
"""
|
|
321
|
+
Creates a `Document` from the search hit provided.
|
|
322
|
+
This is mostly useful in self.filter_documents().
|
|
323
|
+
:param hit: A search hit from Elasticsearch.
|
|
324
|
+
:returns: `Document` created from the search hit.
|
|
325
|
+
"""
|
|
326
|
+
data = hit["_source"]
|
|
327
|
+
|
|
328
|
+
if "highlight" in hit:
|
|
329
|
+
data["metadata"]["highlighted"] = hit["highlight"]
|
|
330
|
+
data["score"] = hit["_score"]
|
|
331
|
+
|
|
332
|
+
if "dataframe" in data:
|
|
333
|
+
dataframe = data.pop("dataframe")
|
|
334
|
+
if dataframe:
|
|
335
|
+
logger.warning(
|
|
336
|
+
"Document %s has the `dataframe` field set,"
|
|
337
|
+
"ElasticsearchDocumentStore no longer supports dataframes and this field will be ignored. "
|
|
338
|
+
"The `dataframe` field will soon be removed from Haystack Document.",
|
|
339
|
+
data["id"],
|
|
340
|
+
)
|
|
341
|
+
return Document.from_dict(data)
|
|
342
|
+
|
|
236
343
|
def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int:
|
|
237
344
|
"""
|
|
238
345
|
Writes `Document`s to Elasticsearch.
|
|
@@ -258,6 +365,15 @@ class ElasticsearchDocumentStore:
|
|
|
258
365
|
elasticsearch_actions = []
|
|
259
366
|
for doc in documents:
|
|
260
367
|
doc_dict = doc.to_dict()
|
|
368
|
+
if "dataframe" in doc_dict:
|
|
369
|
+
dataframe = doc_dict.pop("dataframe")
|
|
370
|
+
if dataframe:
|
|
371
|
+
logger.warning(
|
|
372
|
+
"Document %s has the `dataframe` field set,"
|
|
373
|
+
"ElasticsearchDocumentStore no longer supports dataframes and this field will be ignored. "
|
|
374
|
+
"The `dataframe` field will soon be removed from Haystack Document.",
|
|
375
|
+
doc.id,
|
|
376
|
+
)
|
|
261
377
|
if "sparse_embedding" in doc_dict:
|
|
262
378
|
sparse_embedding = doc_dict.pop("sparse_embedding", None)
|
|
263
379
|
if sparse_embedding:
|
|
@@ -306,31 +422,86 @@ class ElasticsearchDocumentStore:
|
|
|
306
422
|
|
|
307
423
|
return documents_written
|
|
308
424
|
|
|
309
|
-
|
|
310
|
-
|
|
425
|
+
async def write_documents_async(
|
|
426
|
+
self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE
|
|
427
|
+
) -> int:
|
|
311
428
|
"""
|
|
312
|
-
|
|
429
|
+
Asynchronously writes `Document`s to Elasticsearch.
|
|
313
430
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
:
|
|
317
|
-
:
|
|
431
|
+
:param documents: List of Documents to write to the document store.
|
|
432
|
+
:param policy: DuplicatePolicy to apply when a document with the same ID already exists in the document store.
|
|
433
|
+
:raises ValueError: If `documents` is not a list of `Document`s.
|
|
434
|
+
:raises DuplicateDocumentError: If a document with the same ID already exists in the document store and
|
|
435
|
+
`policy` is set to `DuplicatePolicy.FAIL` or `DuplicatePolicy.NONE`.
|
|
436
|
+
:raises DocumentStoreError: If an error occurs while writing the documents to the document store.
|
|
437
|
+
:returns: Number of documents written to the document store.
|
|
318
438
|
"""
|
|
319
|
-
|
|
439
|
+
self._ensure_initialized()
|
|
320
440
|
|
|
321
|
-
if
|
|
322
|
-
|
|
323
|
-
|
|
441
|
+
if len(documents) > 0:
|
|
442
|
+
if not isinstance(documents[0], Document):
|
|
443
|
+
msg = "param 'documents' must contain a list of objects of type Document"
|
|
444
|
+
raise ValueError(msg)
|
|
324
445
|
|
|
325
|
-
|
|
446
|
+
if policy == DuplicatePolicy.NONE:
|
|
447
|
+
policy = DuplicatePolicy.FAIL
|
|
448
|
+
|
|
449
|
+
actions = []
|
|
450
|
+
for doc in documents:
|
|
451
|
+
doc_dict = doc.to_dict()
|
|
452
|
+
if "dataframe" in doc_dict:
|
|
453
|
+
dataframe = doc_dict.pop("dataframe")
|
|
454
|
+
if dataframe:
|
|
455
|
+
logger.warning(
|
|
456
|
+
"Document {id} has the `dataframe` field set,"
|
|
457
|
+
"ElasticsearchDocumentStore no longer supports dataframes and this field will be ignored. "
|
|
458
|
+
"The `dataframe` field will soon be removed from Haystack Document.",
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
if "sparse_embedding" in doc_dict:
|
|
462
|
+
sparse_embedding = doc_dict.pop("sparse_embedding", None)
|
|
463
|
+
if sparse_embedding:
|
|
464
|
+
logger.warning(
|
|
465
|
+
"Document %s has the `sparse_embedding` field set,"
|
|
466
|
+
"but storing sparse embeddings in Elasticsearch is not currently supported."
|
|
467
|
+
"The `sparse_embedding` field will be ignored.",
|
|
468
|
+
doc.id,
|
|
469
|
+
)
|
|
470
|
+
|
|
471
|
+
action = {
|
|
472
|
+
"_op_type": "create" if policy == DuplicatePolicy.FAIL else "index",
|
|
473
|
+
"_id": doc.id,
|
|
474
|
+
"_source": doc_dict,
|
|
475
|
+
}
|
|
476
|
+
actions.append(action)
|
|
477
|
+
|
|
478
|
+
try:
|
|
479
|
+
success, failed = await helpers.async_bulk(
|
|
480
|
+
client=self._async_client,
|
|
481
|
+
actions=actions,
|
|
482
|
+
index=self._index,
|
|
483
|
+
refresh=True,
|
|
484
|
+
raise_on_error=False,
|
|
485
|
+
)
|
|
486
|
+
if failed:
|
|
487
|
+
if policy == DuplicatePolicy.FAIL:
|
|
488
|
+
for error in failed:
|
|
489
|
+
if "create" in error and error["create"]["status"] == DOC_ALREADY_EXISTS:
|
|
490
|
+
msg = f"ID '{error['create']['_id']}' already exists in the document store"
|
|
491
|
+
raise DuplicateDocumentError(msg)
|
|
492
|
+
msg = f"Failed to write documents to Elasticsearch. Errors:\n{failed}"
|
|
493
|
+
raise DocumentStoreError(msg)
|
|
494
|
+
return success
|
|
495
|
+
except Exception as e:
|
|
496
|
+
msg = f"Failed to write documents to Elasticsearch: {e!s}"
|
|
497
|
+
raise DocumentStoreError(msg) from e
|
|
326
498
|
|
|
327
499
|
def delete_documents(self, document_ids: List[str]) -> None:
|
|
328
500
|
"""
|
|
329
|
-
Deletes all
|
|
501
|
+
Deletes all documents with a matching document_ids from the document store.
|
|
330
502
|
|
|
331
|
-
:param document_ids: the
|
|
503
|
+
:param document_ids: the document ids to delete
|
|
332
504
|
"""
|
|
333
|
-
|
|
334
505
|
helpers.bulk(
|
|
335
506
|
client=self.client,
|
|
336
507
|
actions=({"_op_type": "delete", "_id": id_} for id_ in document_ids),
|
|
@@ -339,6 +510,25 @@ class ElasticsearchDocumentStore:
|
|
|
339
510
|
raise_on_error=False,
|
|
340
511
|
)
|
|
341
512
|
|
|
513
|
+
async def delete_documents_async(self, document_ids: List[str]) -> None:
|
|
514
|
+
"""
|
|
515
|
+
Asynchronously deletes all documents with a matching document_ids from the document store.
|
|
516
|
+
|
|
517
|
+
:param document_ids: the document ids to delete
|
|
518
|
+
"""
|
|
519
|
+
self._ensure_initialized()
|
|
520
|
+
|
|
521
|
+
try:
|
|
522
|
+
await helpers.async_bulk(
|
|
523
|
+
client=self._async_client,
|
|
524
|
+
actions=({"_op_type": "delete", "_id": id_} for id_ in document_ids),
|
|
525
|
+
index=self._index,
|
|
526
|
+
refresh=True,
|
|
527
|
+
)
|
|
528
|
+
except Exception as e:
|
|
529
|
+
msg = f"Failed to delete documents from Elasticsearch: {e!s}"
|
|
530
|
+
raise DocumentStoreError(msg) from e
|
|
531
|
+
|
|
342
532
|
def _bm25_retrieval(
|
|
343
533
|
self,
|
|
344
534
|
query: str,
|
|
@@ -349,27 +539,15 @@ class ElasticsearchDocumentStore:
|
|
|
349
539
|
scale_score: bool = False,
|
|
350
540
|
) -> List[Document]:
|
|
351
541
|
"""
|
|
352
|
-
Retrieves
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
:param query: String to search in saved `Document`s' text.
|
|
362
|
-
:param filters: Filters applied to the retrieved `Document`s, for more info
|
|
363
|
-
see `ElasticsearchDocumentStore.filter_documents`.
|
|
364
|
-
:param fuzziness: Fuzziness parameter passed to Elasticsearch. See the official
|
|
365
|
-
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness)
|
|
366
|
-
for valid values.
|
|
367
|
-
:param top_k: Maximum number of `Document`s to return.
|
|
368
|
-
:param scale_score: If `True` scales the `Document``s scores between 0 and 1.
|
|
369
|
-
:raises ValueError: If `query` is an empty string
|
|
370
|
-
:returns: List of `Document` that match `query`
|
|
542
|
+
Retrieves documents using BM25 retrieval.
|
|
543
|
+
|
|
544
|
+
:param query: The query string to search for
|
|
545
|
+
:param filters: Optional filters to narrow down the search space
|
|
546
|
+
:param fuzziness: Fuzziness parameter for the search query
|
|
547
|
+
:param top_k: Maximum number of documents to return
|
|
548
|
+
:param scale_score: Whether to scale the similarity score to the range [0,1]
|
|
549
|
+
:returns: List of Documents that match the query
|
|
371
550
|
"""
|
|
372
|
-
|
|
373
551
|
if not query:
|
|
374
552
|
msg = "query must be a non empty string"
|
|
375
553
|
raise ValueError(msg)
|
|
@@ -403,35 +581,79 @@ class ElasticsearchDocumentStore:
|
|
|
403
581
|
|
|
404
582
|
return documents
|
|
405
583
|
|
|
406
|
-
def
|
|
584
|
+
async def _bm25_retrieval_async(
|
|
407
585
|
self,
|
|
408
|
-
|
|
586
|
+
query: str,
|
|
409
587
|
*,
|
|
410
588
|
filters: Optional[Dict[str, Any]] = None,
|
|
589
|
+
fuzziness: str = "AUTO",
|
|
411
590
|
top_k: int = 10,
|
|
412
|
-
|
|
591
|
+
scale_score: bool = False,
|
|
413
592
|
) -> List[Document]:
|
|
414
593
|
"""
|
|
415
|
-
|
|
594
|
+
Asynchronously retrieves documents using BM25 retrieval.
|
|
595
|
+
|
|
596
|
+
:param query: The query string to search for
|
|
597
|
+
:param filters: Optional filters to narrow down the search space
|
|
598
|
+
:param fuzziness: Fuzziness parameter for the search query
|
|
599
|
+
:param top_k: Maximum number of documents to return
|
|
600
|
+
:param scale_score: Whether to scale the similarity score to the range [0,1]
|
|
601
|
+
:returns: List of Documents that match the query
|
|
602
|
+
"""
|
|
603
|
+
self._ensure_initialized()
|
|
604
|
+
|
|
605
|
+
if not query:
|
|
606
|
+
msg = "query must be a non empty string"
|
|
607
|
+
raise ValueError(msg)
|
|
608
|
+
|
|
609
|
+
# Prepare the search body
|
|
610
|
+
search_body = {
|
|
611
|
+
"size": top_k,
|
|
612
|
+
"query": {
|
|
613
|
+
"bool": {
|
|
614
|
+
"must": [
|
|
615
|
+
{
|
|
616
|
+
"multi_match": {
|
|
617
|
+
"query": query,
|
|
618
|
+
"type": "most_fields",
|
|
619
|
+
"operator": "OR",
|
|
620
|
+
"fuzziness": fuzziness,
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
]
|
|
624
|
+
}
|
|
625
|
+
},
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
if filters:
|
|
629
|
+
search_body["query"]["bool"]["filter"] = _normalize_filters(filters) # type:ignore
|
|
416
630
|
|
|
417
|
-
|
|
631
|
+
documents = await self._search_documents_async(**search_body)
|
|
632
|
+
|
|
633
|
+
if scale_score:
|
|
634
|
+
for doc in documents:
|
|
635
|
+
if doc.score is not None:
|
|
636
|
+
doc.score = float(1 / (1 + np.exp(-(doc.score / float(BM25_SCALING_FACTOR)))))
|
|
418
637
|
|
|
419
|
-
|
|
420
|
-
`ElasticsearchDocumentStore` nor called directly.
|
|
421
|
-
`ElasticsearchEmbeddingRetriever` uses this method directly and is the public interface for it.
|
|
638
|
+
return documents
|
|
422
639
|
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
:
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
:raises ValueError: If `query_embedding` is an empty list.
|
|
432
|
-
:returns: List of `Document` that are most similar to `query_embedding`.
|
|
640
|
+
def _embedding_retrieval(
|
|
641
|
+
self,
|
|
642
|
+
query_embedding: List[float],
|
|
643
|
+
*,
|
|
644
|
+
filters: Optional[Dict[str, Any]] = None,
|
|
645
|
+
top_k: int = 10,
|
|
646
|
+
num_candidates: Optional[int] = None,
|
|
647
|
+
) -> List[Document]:
|
|
433
648
|
"""
|
|
649
|
+
Retrieves documents using dense vector similarity search.
|
|
434
650
|
|
|
651
|
+
:param query_embedding: Embedding vector to search for
|
|
652
|
+
:param filters: Optional filters to narrow down the search space
|
|
653
|
+
:param top_k: Maximum number of documents to return
|
|
654
|
+
:param num_candidates: Number of candidates to consider in the search
|
|
655
|
+
:returns: List of Documents most similar to query_embedding
|
|
656
|
+
"""
|
|
435
657
|
if not query_embedding:
|
|
436
658
|
msg = "query_embedding must be a non-empty list of floats"
|
|
437
659
|
raise ValueError(msg)
|
|
@@ -453,3 +675,45 @@ class ElasticsearchDocumentStore:
|
|
|
453
675
|
|
|
454
676
|
docs = self._search_documents(**body)
|
|
455
677
|
return docs
|
|
678
|
+
|
|
679
|
+
async def _embedding_retrieval_async(
|
|
680
|
+
self,
|
|
681
|
+
query_embedding: List[float],
|
|
682
|
+
*,
|
|
683
|
+
filters: Optional[Dict[str, Any]] = None,
|
|
684
|
+
top_k: int = 10,
|
|
685
|
+
num_candidates: Optional[int] = None,
|
|
686
|
+
) -> List[Document]:
|
|
687
|
+
"""
|
|
688
|
+
Asynchronously retrieves documents using dense vector similarity search.
|
|
689
|
+
|
|
690
|
+
:param query_embedding: Embedding vector to search for
|
|
691
|
+
:param filters: Optional filters to narrow down the search space
|
|
692
|
+
:param top_k: Maximum number of documents to return
|
|
693
|
+
:param num_candidates: Number of candidates to consider in the search
|
|
694
|
+
:returns: List of Documents most similar to query_embedding
|
|
695
|
+
"""
|
|
696
|
+
self._ensure_initialized()
|
|
697
|
+
|
|
698
|
+
if not query_embedding:
|
|
699
|
+
msg = "query_embedding must be a non-empty list of floats"
|
|
700
|
+
raise ValueError(msg)
|
|
701
|
+
|
|
702
|
+
# If num_candidates is not set, use top_k * 10 as default
|
|
703
|
+
if num_candidates is None:
|
|
704
|
+
num_candidates = top_k * 10
|
|
705
|
+
|
|
706
|
+
# Prepare the search body
|
|
707
|
+
search_body = {
|
|
708
|
+
"knn": {
|
|
709
|
+
"field": "embedding",
|
|
710
|
+
"query_vector": query_embedding,
|
|
711
|
+
"k": top_k,
|
|
712
|
+
"num_candidates": num_candidates,
|
|
713
|
+
},
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
if filters:
|
|
717
|
+
search_body["knn"]["filter"] = _normalize_filters(filters)
|
|
718
|
+
|
|
719
|
+
return await self._search_documents_async(**search_body)
|
|
@@ -5,7 +5,6 @@ from datetime import datetime
|
|
|
5
5
|
from typing import Any, Dict, List
|
|
6
6
|
|
|
7
7
|
from haystack.errors import FilterError
|
|
8
|
-
from pandas import DataFrame
|
|
9
8
|
|
|
10
9
|
|
|
11
10
|
def _normalize_filters(filters: Dict[str, Any]) -> Dict[str, Any]:
|
|
@@ -57,7 +56,7 @@ def _equal(field: str, value: Any) -> Dict[str, Any]:
|
|
|
57
56
|
}
|
|
58
57
|
}
|
|
59
58
|
}
|
|
60
|
-
if field
|
|
59
|
+
if field == "text":
|
|
61
60
|
# We want to fully match the text field.
|
|
62
61
|
return {"match": {field: {"query": value, "minimum_should_match": "100%"}}}
|
|
63
62
|
return {"term": {field: value}}
|
|
@@ -69,7 +68,7 @@ def _not_equal(field: str, value: Any) -> Dict[str, Any]:
|
|
|
69
68
|
|
|
70
69
|
if isinstance(value, list):
|
|
71
70
|
return {"bool": {"must_not": {"terms": {field: value}}}}
|
|
72
|
-
if field
|
|
71
|
+
if field == "text":
|
|
73
72
|
# We want to fully match the text field.
|
|
74
73
|
return {"bool": {"must_not": {"match": {field: {"query": value, "minimum_should_match": "100%"}}}}}
|
|
75
74
|
|
|
@@ -92,7 +91,7 @@ def _greater_than(field: str, value: Any) -> Dict[str, Any]:
|
|
|
92
91
|
"Strings are only comparable if they are ISO formatted dates."
|
|
93
92
|
)
|
|
94
93
|
raise FilterError(msg) from exc
|
|
95
|
-
if
|
|
94
|
+
if isinstance(value, list):
|
|
96
95
|
msg = f"Filter value can't be of type {type(value)} using operators '>', '>=', '<', '<='"
|
|
97
96
|
raise FilterError(msg)
|
|
98
97
|
return {"range": {field: {"gt": value}}}
|
|
@@ -114,7 +113,7 @@ def _greater_than_equal(field: str, value: Any) -> Dict[str, Any]:
|
|
|
114
113
|
"Strings are only comparable if they are ISO formatted dates."
|
|
115
114
|
)
|
|
116
115
|
raise FilterError(msg) from exc
|
|
117
|
-
if
|
|
116
|
+
if isinstance(value, list):
|
|
118
117
|
msg = f"Filter value can't be of type {type(value)} using operators '>', '>=', '<', '<='"
|
|
119
118
|
raise FilterError(msg)
|
|
120
119
|
return {"range": {field: {"gte": value}}}
|
|
@@ -136,7 +135,7 @@ def _less_than(field: str, value: Any) -> Dict[str, Any]:
|
|
|
136
135
|
"Strings are only comparable if they are ISO formatted dates."
|
|
137
136
|
)
|
|
138
137
|
raise FilterError(msg) from exc
|
|
139
|
-
if
|
|
138
|
+
if isinstance(value, list):
|
|
140
139
|
msg = f"Filter value can't be of type {type(value)} using operators '>', '>=', '<', '<='"
|
|
141
140
|
raise FilterError(msg)
|
|
142
141
|
return {"range": {field: {"lt": value}}}
|
|
@@ -158,7 +157,7 @@ def _less_than_equal(field: str, value: Any) -> Dict[str, Any]:
|
|
|
158
157
|
"Strings are only comparable if they are ISO formatted dates."
|
|
159
158
|
)
|
|
160
159
|
raise FilterError(msg) from exc
|
|
161
|
-
if
|
|
160
|
+
if isinstance(value, list):
|
|
162
161
|
msg = f"Filter value can't be of type {type(value)} using operators '>', '>=', '<', '<='"
|
|
163
162
|
raise FilterError(msg)
|
|
164
163
|
return {"range": {field: {"lte": value}}}
|
|
@@ -212,8 +211,6 @@ def _parse_comparison_condition(condition: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
212
211
|
raise FilterError(msg)
|
|
213
212
|
operator: str = condition["operator"]
|
|
214
213
|
value: Any = condition["value"]
|
|
215
|
-
if isinstance(value, DataFrame):
|
|
216
|
-
value = value.to_json()
|
|
217
214
|
|
|
218
215
|
return COMPARISON_OPERATORS[operator](field, value)
|
|
219
216
|
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
haystack_integrations/components/retrievers/elasticsearch/__init__.py,sha256=cSJBsYjz_T4kK-M-auAHVUnYIcgUqqwwQe_hsF0_IG4,307
|
|
2
|
-
haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py,sha256=XA6UiNFb59CMM5LSoPmNDe3IzZ7ty7HViSaU2ZT4--w,5851
|
|
3
|
-
haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=ZL9kHi6tCzks1_GXoOIRVLcN4BWnaMqN6t-JcwdTfao,5992
|
|
4
|
-
haystack_integrations/document_stores/elasticsearch/__init__.py,sha256=YTfu94dtVUBogbJFr1aJrKuaI6-Bw9VuHfPoyU7M8os,207
|
|
5
|
-
haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=B2B0F2AHsoP1-BykF_xqfRAYeQPmsiBn0QCIfTqk-pc,18871
|
|
6
|
-
haystack_integrations/document_stores/elasticsearch/filters.py,sha256=L1tN7YCIDuNdhGrBQdPoqXFk37x__2-K038xZ6PRdNQ,9923
|
|
7
|
-
elasticsearch_haystack-1.0.1.dist-info/METADATA,sha256=hTImF5-zddncU9m31MLAS4eDtlShxI_gb5lgQFMlCbI,2168
|
|
8
|
-
elasticsearch_haystack-1.0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
9
|
-
elasticsearch_haystack-1.0.1.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
|
|
10
|
-
elasticsearch_haystack-1.0.1.dist-info/RECORD,,
|
{elasticsearch_haystack-1.0.1.dist-info → elasticsearch_haystack-2.1.0.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|