elasticsearch-haystack 3.1.0__py3-none-any.whl → 4.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-3.1.0.dist-info → elasticsearch_haystack-4.1.0.dist-info}/METADATA +9 -25
- {elasticsearch_haystack-3.1.0.dist-info → elasticsearch_haystack-4.1.0.dist-info}/RECORD +5 -5
- haystack_integrations/document_stores/elasticsearch/document_store.py +197 -29
- {elasticsearch_haystack-3.1.0.dist-info → elasticsearch_haystack-4.1.0.dist-info}/WHEEL +0 -0
- {elasticsearch_haystack-3.1.0.dist-info → elasticsearch_haystack-4.1.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: elasticsearch-haystack
|
|
3
|
-
Version:
|
|
3
|
+
Version: 4.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
|
|
@@ -24,35 +24,19 @@ Requires-Dist: elasticsearch<9,>=8
|
|
|
24
24
|
Requires-Dist: haystack-ai>=2.4.0
|
|
25
25
|
Description-Content-Type: text/markdown
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
# elasticsearch-haystack
|
|
28
28
|
|
|
29
29
|
[](https://pypi.org/project/elasticsearch-haystack)
|
|
30
30
|
[](https://pypi.org/project/elasticsearch-haystack)
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
- [Integration page](https://haystack.deepset.ai/integrations/elasticsearch-document-store)
|
|
33
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/elasticsearch/CHANGELOG.md)
|
|
33
34
|
|
|
34
|
-
|
|
35
|
+
---
|
|
35
36
|
|
|
36
|
-
##
|
|
37
|
+
## Contributing
|
|
37
38
|
|
|
38
|
-
|
|
39
|
-
pip install elasticsearch-haystack
|
|
40
|
-
```
|
|
39
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
41
40
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
To run tests first start a Docker container running ElasticSearch. We provide a utility `docker-compose.yml` for that:
|
|
45
|
-
|
|
46
|
-
```console
|
|
47
|
-
docker-compose up
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
Then run tests:
|
|
51
|
-
|
|
52
|
-
```console
|
|
53
|
-
hatch run test:all
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
## License
|
|
57
|
-
|
|
58
|
-
`elasticsearch-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
41
|
+
To run integration tests locally, you need a Docker container running ElasticSearch.
|
|
42
|
+
Use the provided `docker-compose.yml` file to start the container: `docker compose up -d`.
|
|
@@ -4,9 +4,9 @@ haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py,sha2
|
|
|
4
4
|
haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=-6eIHW5cU4k8-jAsUsCb15hJRalpkUhzy_dNxr5HUZo,7404
|
|
5
5
|
haystack_integrations/document_stores/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
6
|
haystack_integrations/document_stores/elasticsearch/__init__.py,sha256=YTfu94dtVUBogbJFr1aJrKuaI6-Bw9VuHfPoyU7M8os,207
|
|
7
|
-
haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=
|
|
7
|
+
haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=erIS-Tk9sdBYdRjTsjY_JmTQRH67Sjgk1BWvFCI4dtw,36023
|
|
8
8
|
haystack_integrations/document_stores/elasticsearch/filters.py,sha256=Umip-PP4uFjuWeB1JWkKhaKClQ0VpiykoDlDu99wIV0,9759
|
|
9
|
-
elasticsearch_haystack-
|
|
10
|
-
elasticsearch_haystack-
|
|
11
|
-
elasticsearch_haystack-
|
|
12
|
-
elasticsearch_haystack-
|
|
9
|
+
elasticsearch_haystack-4.1.0.dist-info/METADATA,sha256=TYYaNrsYzGPCLxuVBxGAXlXoaeFJqgL1VzPGybXAFNA,2105
|
|
10
|
+
elasticsearch_haystack-4.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
11
|
+
elasticsearch_haystack-4.1.0.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
|
|
12
|
+
elasticsearch_haystack-4.1.0.dist-info/RECORD,,
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
2
|
#
|
|
3
3
|
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
# ruff: noqa: FBT002, FBT001 boolean-type-hint-positional-argument and boolean-default-value-positional-argument
|
|
6
|
+
# ruff: noqa: B008 function-call-in-default-argument
|
|
7
|
+
# ruff: noqa: S101 disable checks for uses of the assert keyword
|
|
8
|
+
|
|
9
|
+
|
|
4
10
|
from collections.abc import Mapping
|
|
5
|
-
from typing import Any, Dict, List, Literal, Optional, Union
|
|
11
|
+
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
|
|
6
12
|
|
|
7
13
|
import numpy as np
|
|
8
14
|
from elastic_transport import NodeConfig
|
|
@@ -10,6 +16,7 @@ from haystack import default_from_dict, default_to_dict, logging
|
|
|
10
16
|
from haystack.dataclasses import Document
|
|
11
17
|
from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumentError
|
|
12
18
|
from haystack.document_stores.types import DuplicatePolicy
|
|
19
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
13
20
|
from haystack.version import __version__ as haystack_version
|
|
14
21
|
|
|
15
22
|
from elasticsearch import AsyncElasticsearch, Elasticsearch, helpers
|
|
@@ -38,13 +45,16 @@ class ElasticsearchDocumentStore:
|
|
|
38
45
|
|
|
39
46
|
Usage example (Elastic Cloud):
|
|
40
47
|
```python
|
|
41
|
-
from
|
|
42
|
-
document_store = ElasticsearchDocumentStore(
|
|
48
|
+
from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore
|
|
49
|
+
document_store = ElasticsearchDocumentStore(
|
|
50
|
+
api_key_id=Secret.from_env_var("ELASTIC_API_KEY_ID", strict=False),
|
|
51
|
+
api_key=Secret.from_env_var("ELASTIC_API_KEY", strict=False),
|
|
52
|
+
)
|
|
43
53
|
```
|
|
44
54
|
|
|
45
55
|
Usage example (self-hosted Elasticsearch instance):
|
|
46
56
|
```python
|
|
47
|
-
from
|
|
57
|
+
from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore
|
|
48
58
|
document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200")
|
|
49
59
|
```
|
|
50
60
|
In the above example we connect with security disabled just to show the basic usage.
|
|
@@ -63,6 +73,8 @@ class ElasticsearchDocumentStore:
|
|
|
63
73
|
hosts: Optional[Hosts] = None,
|
|
64
74
|
custom_mapping: Optional[Dict[str, Any]] = None,
|
|
65
75
|
index: str = "default",
|
|
76
|
+
api_key: Secret = Secret.from_env_var("ELASTIC_API_KEY", strict=False),
|
|
77
|
+
api_key_id: Secret = Secret.from_env_var("ELASTIC_API_KEY_ID", strict=False),
|
|
66
78
|
embedding_similarity_function: Literal["cosine", "dot_product", "l2_norm", "max_inner_product"] = "cosine",
|
|
67
79
|
**kwargs: Any,
|
|
68
80
|
):
|
|
@@ -80,9 +92,16 @@ class ElasticsearchDocumentStore:
|
|
|
80
92
|
For the full list of supported kwargs, see the official Elasticsearch
|
|
81
93
|
[reference](https://elasticsearch-py.readthedocs.io/en/stable/api.html#module-elasticsearch)
|
|
82
94
|
|
|
95
|
+
Authentication is provided via Secret objects, which by default are loaded from environment variables.
|
|
96
|
+
You can either provide both `api_key_id` and `api_key`, or just `api_key` containing a base64-encoded string
|
|
97
|
+
of `id:secret`. Secret instances can also be loaded from a token using the `Secret.from_token()` method.
|
|
98
|
+
|
|
83
99
|
:param hosts: List of hosts running the Elasticsearch client.
|
|
84
100
|
:param custom_mapping: Custom mapping for the index. If not provided, a default mapping will be used.
|
|
85
101
|
:param index: Name of index in Elasticsearch.
|
|
102
|
+
:param api_key: A Secret object containing the API key for authenticating or base64-encoded with the
|
|
103
|
+
concatenated secret and id for authenticating with Elasticsearch (separated by “:”).
|
|
104
|
+
:param api_key_id: A Secret object containing the API key ID for authenticating with Elasticsearch.
|
|
86
105
|
:param embedding_similarity_function: The similarity function used to compare Documents embeddings.
|
|
87
106
|
This parameter only takes effect if the index does not yet exist and is created.
|
|
88
107
|
To choose the most appropriate function, look for information about your embedding model.
|
|
@@ -94,6 +113,8 @@ class ElasticsearchDocumentStore:
|
|
|
94
113
|
self._client: Optional[Elasticsearch] = None
|
|
95
114
|
self._async_client: Optional[AsyncElasticsearch] = None
|
|
96
115
|
self._index = index
|
|
116
|
+
self._api_key = api_key
|
|
117
|
+
self._api_key_id = api_key_id
|
|
97
118
|
self._embedding_similarity_function = embedding_similarity_function
|
|
98
119
|
self._custom_mapping = custom_mapping
|
|
99
120
|
self._kwargs = kwargs
|
|
@@ -103,6 +124,29 @@ class ElasticsearchDocumentStore:
|
|
|
103
124
|
msg = "custom_mapping must be a dictionary"
|
|
104
125
|
raise ValueError(msg)
|
|
105
126
|
|
|
127
|
+
if not self._custom_mapping:
|
|
128
|
+
self._default_mappings = {
|
|
129
|
+
"properties": {
|
|
130
|
+
"embedding": {
|
|
131
|
+
"type": "dense_vector",
|
|
132
|
+
"index": True,
|
|
133
|
+
"similarity": self._embedding_similarity_function,
|
|
134
|
+
},
|
|
135
|
+
"content": {"type": "text"},
|
|
136
|
+
},
|
|
137
|
+
"dynamic_templates": [
|
|
138
|
+
{
|
|
139
|
+
"strings": {
|
|
140
|
+
"path_match": "*",
|
|
141
|
+
"match_mapping_type": "string",
|
|
142
|
+
"mapping": {
|
|
143
|
+
"type": "keyword",
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
],
|
|
148
|
+
}
|
|
149
|
+
|
|
106
150
|
def _ensure_initialized(self):
|
|
107
151
|
"""
|
|
108
152
|
Ensures both sync and async clients are initialized and the index exists.
|
|
@@ -111,14 +155,18 @@ class ElasticsearchDocumentStore:
|
|
|
111
155
|
headers = self._kwargs.pop("headers", {})
|
|
112
156
|
headers["user-agent"] = f"haystack-py-ds/{haystack_version}"
|
|
113
157
|
|
|
158
|
+
api_key = self._handle_auth()
|
|
159
|
+
|
|
114
160
|
# Initialize both sync and async clients
|
|
115
161
|
self._client = Elasticsearch(
|
|
116
162
|
self._hosts,
|
|
163
|
+
api_key=api_key,
|
|
117
164
|
headers=headers,
|
|
118
165
|
**self._kwargs,
|
|
119
166
|
)
|
|
120
167
|
self._async_client = AsyncElasticsearch(
|
|
121
168
|
self._hosts,
|
|
169
|
+
api_key=api_key,
|
|
122
170
|
headers=headers,
|
|
123
171
|
**self._kwargs,
|
|
124
172
|
)
|
|
@@ -130,27 +178,7 @@ class ElasticsearchDocumentStore:
|
|
|
130
178
|
mappings = self._custom_mapping
|
|
131
179
|
else:
|
|
132
180
|
# Configure mapping for the embedding field if none is provided
|
|
133
|
-
mappings =
|
|
134
|
-
"properties": {
|
|
135
|
-
"embedding": {
|
|
136
|
-
"type": "dense_vector",
|
|
137
|
-
"index": True,
|
|
138
|
-
"similarity": self._embedding_similarity_function,
|
|
139
|
-
},
|
|
140
|
-
"content": {"type": "text"},
|
|
141
|
-
},
|
|
142
|
-
"dynamic_templates": [
|
|
143
|
-
{
|
|
144
|
-
"strings": {
|
|
145
|
-
"path_match": "*",
|
|
146
|
-
"match_mapping_type": "string",
|
|
147
|
-
"mapping": {
|
|
148
|
-
"type": "keyword",
|
|
149
|
-
},
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
],
|
|
153
|
-
}
|
|
181
|
+
mappings = self._default_mappings
|
|
154
182
|
|
|
155
183
|
# Create the index if it doesn't exist
|
|
156
184
|
if not self._client.indices.exists(index=self._index):
|
|
@@ -158,13 +186,56 @@ class ElasticsearchDocumentStore:
|
|
|
158
186
|
|
|
159
187
|
self._initialized = True
|
|
160
188
|
|
|
189
|
+
def _handle_auth(self) -> Optional[Union[str, Tuple[str, str]]]:
|
|
190
|
+
"""
|
|
191
|
+
Handles authentication for the Elasticsearch client.
|
|
192
|
+
|
|
193
|
+
There are three possible scenarios.
|
|
194
|
+
|
|
195
|
+
1) Authentication with both api_key and api_key_id, either as Secrets or as environment variables. In this case,
|
|
196
|
+
use both for authentication.
|
|
197
|
+
|
|
198
|
+
2) Authentication with only api_key, either as a Secret or as an environment variable. In this case, the api_key
|
|
199
|
+
must be a base64-encoded string that encodes both id and secret <id:secret>.
|
|
200
|
+
|
|
201
|
+
3) There's no authentication, neither api_key nor api_key_id are provided as a Secret nor defined as
|
|
202
|
+
environment variables. In this case, the client will connect without authentication.
|
|
203
|
+
|
|
204
|
+
:returns:
|
|
205
|
+
api_key: Optional[Union[str, Tuple[str, str]]]
|
|
206
|
+
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
api_key: Optional[Union[str, Tuple[str, str]]] # make the type checker happy
|
|
210
|
+
|
|
211
|
+
api_key_resolved = self._api_key.resolve_value()
|
|
212
|
+
api_key_id_resolved = self._api_key_id.resolve_value()
|
|
213
|
+
|
|
214
|
+
# Scenario 1: both are found, use them
|
|
215
|
+
if api_key_id_resolved and api_key_resolved:
|
|
216
|
+
api_key = (api_key_id_resolved, api_key_resolved)
|
|
217
|
+
return api_key
|
|
218
|
+
|
|
219
|
+
# Scenario 2: only api_key is set, must be a base64-encoded string that encodes id and secret (separated by “:”)
|
|
220
|
+
elif api_key_resolved and not api_key_id_resolved:
|
|
221
|
+
return api_key_resolved
|
|
222
|
+
|
|
223
|
+
# Error: only api_key_id is found, raise an error
|
|
224
|
+
elif api_key_id_resolved and not api_key_resolved:
|
|
225
|
+
msg = "api_key_id is provided but api_key is missing."
|
|
226
|
+
raise ValueError(msg)
|
|
227
|
+
|
|
228
|
+
else:
|
|
229
|
+
# Scenario 3: neither found, no authentication
|
|
230
|
+
return None
|
|
231
|
+
|
|
161
232
|
@property
|
|
162
233
|
def client(self) -> Elasticsearch:
|
|
163
234
|
"""
|
|
164
235
|
Returns the synchronous Elasticsearch client, initializing it if necessary.
|
|
165
236
|
"""
|
|
166
237
|
self._ensure_initialized()
|
|
167
|
-
assert self._client is not None
|
|
238
|
+
assert self._client is not None
|
|
168
239
|
return self._client
|
|
169
240
|
|
|
170
241
|
@property
|
|
@@ -173,7 +244,7 @@ class ElasticsearchDocumentStore:
|
|
|
173
244
|
Returns the asynchronous Elasticsearch client, initializing it if necessary.
|
|
174
245
|
"""
|
|
175
246
|
self._ensure_initialized()
|
|
176
|
-
assert self._async_client is not None
|
|
247
|
+
assert self._async_client is not None
|
|
177
248
|
return self._async_client
|
|
178
249
|
|
|
179
250
|
def to_dict(self) -> Dict[str, Any]:
|
|
@@ -191,6 +262,8 @@ class ElasticsearchDocumentStore:
|
|
|
191
262
|
hosts=self._hosts,
|
|
192
263
|
custom_mapping=self._custom_mapping,
|
|
193
264
|
index=self._index,
|
|
265
|
+
api_key=self._api_key.to_dict(),
|
|
266
|
+
api_key_id=self._api_key_id.to_dict(),
|
|
194
267
|
embedding_similarity_function=self._embedding_similarity_function,
|
|
195
268
|
**self._kwargs,
|
|
196
269
|
)
|
|
@@ -205,6 +278,7 @@ class ElasticsearchDocumentStore:
|
|
|
205
278
|
:returns:
|
|
206
279
|
Deserialized component.
|
|
207
280
|
"""
|
|
281
|
+
deserialize_secrets_inplace(data, keys=["api_key", "api_key_id"])
|
|
208
282
|
return default_from_dict(cls, data)
|
|
209
283
|
|
|
210
284
|
def count_documents(self) -> int:
|
|
@@ -384,7 +458,7 @@ class ElasticsearchDocumentStore:
|
|
|
384
458
|
|
|
385
459
|
if errors:
|
|
386
460
|
# with stats_only=False, errors is guaranteed to be a list of dicts
|
|
387
|
-
assert isinstance(errors, list)
|
|
461
|
+
assert isinstance(errors, list)
|
|
388
462
|
duplicate_errors_ids = []
|
|
389
463
|
other_errors = []
|
|
390
464
|
for e in errors:
|
|
@@ -463,7 +537,7 @@ class ElasticsearchDocumentStore:
|
|
|
463
537
|
)
|
|
464
538
|
if failed:
|
|
465
539
|
# with stats_only=False, failed is guaranteed to be a list of dicts
|
|
466
|
-
assert isinstance(failed, list)
|
|
540
|
+
assert isinstance(failed, list)
|
|
467
541
|
if policy == DuplicatePolicy.FAIL:
|
|
468
542
|
for error in failed:
|
|
469
543
|
if "create" in error and error["create"]["status"] == DOC_ALREADY_EXISTS:
|
|
@@ -490,6 +564,14 @@ class ElasticsearchDocumentStore:
|
|
|
490
564
|
raise_on_error=False,
|
|
491
565
|
)
|
|
492
566
|
|
|
567
|
+
def _prepare_delete_all_request(self, *, is_async: bool) -> Dict[str, Any]:
|
|
568
|
+
return {
|
|
569
|
+
"index": self._index,
|
|
570
|
+
"body": {"query": {"match_all": {}}}, # Delete all documents
|
|
571
|
+
"wait_for_completion": False if is_async else True, # block until done (set False for async)
|
|
572
|
+
"refresh": True, # Ensure changes are visible immediately
|
|
573
|
+
}
|
|
574
|
+
|
|
493
575
|
async def delete_documents_async(self, document_ids: List[str]) -> None:
|
|
494
576
|
"""
|
|
495
577
|
Asynchronously deletes all documents with a matching document_ids from the document store.
|
|
@@ -509,6 +591,92 @@ class ElasticsearchDocumentStore:
|
|
|
509
591
|
msg = f"Failed to delete documents from Elasticsearch: {e!s}"
|
|
510
592
|
raise DocumentStoreError(msg) from e
|
|
511
593
|
|
|
594
|
+
def delete_all_documents(self, recreate_index: bool = False) -> None:
|
|
595
|
+
"""
|
|
596
|
+
Deletes all documents in the document store.
|
|
597
|
+
|
|
598
|
+
A fast way to clear all documents from the document store while preserving any index settings and mappings.
|
|
599
|
+
|
|
600
|
+
:param recreate_index: If True, the index will be deleted and recreated with the original mappings and
|
|
601
|
+
settings. If False, all documents will be deleted using the `delete_by_query` API.
|
|
602
|
+
"""
|
|
603
|
+
self._ensure_initialized() # _ensure_initialized ensures _client is not None and an index exists
|
|
604
|
+
|
|
605
|
+
if recreate_index:
|
|
606
|
+
# get the current index mappings and settings
|
|
607
|
+
index_name = self._index
|
|
608
|
+
mappings = self._client.indices.get(index=self._index)[index_name]["mappings"] # type: ignore
|
|
609
|
+
settings = self._client.indices.get(index=self._index)[index_name]["settings"] # type: ignore
|
|
610
|
+
|
|
611
|
+
# remove settings that cannot be set during index creation
|
|
612
|
+
settings["index"].pop("uuid", None)
|
|
613
|
+
settings["index"].pop("creation_date", None)
|
|
614
|
+
settings["index"].pop("provided_name", None)
|
|
615
|
+
settings["index"].pop("version", None)
|
|
616
|
+
|
|
617
|
+
self._client.indices.delete(index=self._index) # type: ignore
|
|
618
|
+
self._client.indices.create(index=self._index, settings=settings, mappings=mappings) # type: ignore
|
|
619
|
+
|
|
620
|
+
# delete index
|
|
621
|
+
self._client.indices.delete(index=self._index) # type: ignore
|
|
622
|
+
|
|
623
|
+
# recreate with mappings
|
|
624
|
+
self._client.indices.create(index=self._index, mappings=mappings) # type: ignore
|
|
625
|
+
|
|
626
|
+
else:
|
|
627
|
+
result = self._client.delete_by_query(**self._prepare_delete_all_request(is_async=False)) # type: ignore
|
|
628
|
+
logger.info(
|
|
629
|
+
"Deleted all the {n_docs} documents from the index '{index}'.",
|
|
630
|
+
index=self._index,
|
|
631
|
+
n_docs=result["deleted"],
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
async def delete_all_documents_async(self, recreate_index: bool = False) -> None:
|
|
635
|
+
"""
|
|
636
|
+
Asynchronously deletes all documents in the document store.
|
|
637
|
+
|
|
638
|
+
A fast way to clear all documents from the document store while preserving any index settings and mappings.
|
|
639
|
+
:param recreate_index: If True, the index will be deleted and recreated with the original mappings and
|
|
640
|
+
settings. If False, all documents will be deleted using the `delete_by_query` API.
|
|
641
|
+
"""
|
|
642
|
+
self._ensure_initialized() # ensures _async_client is not None
|
|
643
|
+
|
|
644
|
+
try:
|
|
645
|
+
if recreate_index:
|
|
646
|
+
# get the current index mappings and settings
|
|
647
|
+
index_name = self._index
|
|
648
|
+
index_info = await self._async_client.indices.get(index=self._index) # type: ignore
|
|
649
|
+
mappings = index_info[index_name]["mappings"]
|
|
650
|
+
settings = index_info[index_name]["settings"]
|
|
651
|
+
|
|
652
|
+
# remove settings that cannot be set during index creation
|
|
653
|
+
settings["index"].pop("uuid", None)
|
|
654
|
+
settings["index"].pop("creation_date", None)
|
|
655
|
+
settings["index"].pop("provided_name", None)
|
|
656
|
+
settings["index"].pop("version", None)
|
|
657
|
+
|
|
658
|
+
# delete index
|
|
659
|
+
await self._async_client.indices.delete(index=self._index) # type: ignore
|
|
660
|
+
|
|
661
|
+
# recreate with settings and mappings
|
|
662
|
+
await self._async_client.indices.create(index=self._index, settings=settings, mappings=mappings) # type: ignore
|
|
663
|
+
|
|
664
|
+
else:
|
|
665
|
+
# use delete_by_query for more efficient deletion without index recreation
|
|
666
|
+
# For async, we need to wait for completion to get the deleted count
|
|
667
|
+
delete_request = self._prepare_delete_all_request(is_async=True)
|
|
668
|
+
delete_request["wait_for_completion"] = True # Override to wait for completion in async
|
|
669
|
+
result = await self._async_client.delete_by_query(**delete_request) # type: ignore
|
|
670
|
+
logger.info(
|
|
671
|
+
"Deleted all the {n_docs} documents from the index '{index}'.",
|
|
672
|
+
index=self._index,
|
|
673
|
+
n_docs=result["deleted"],
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
except Exception as e:
|
|
677
|
+
msg = f"Failed to delete all documents from Elasticsearch: {e!s}"
|
|
678
|
+
raise DocumentStoreError(msg) from e
|
|
679
|
+
|
|
512
680
|
def _bm25_retrieval(
|
|
513
681
|
self,
|
|
514
682
|
query: str,
|
|
File without changes
|
{elasticsearch_haystack-3.1.0.dist-info → elasticsearch_haystack-4.1.0.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|