elasticsearch-haystack 3.0.1__py3-none-any.whl → 4.0.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.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: elasticsearch-haystack
3
- Version: 3.0.1
3
+ Version: 4.0.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
- [![test](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/elasticsearch.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/elasticsearch.yml)
27
+ # elasticsearch-haystack
28
28
 
29
29
  [![PyPI - Version](https://img.shields.io/pypi/v/elasticsearch-haystack.svg)](https://pypi.org/project/elasticsearch-haystack)
30
30
  [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/elasticsearch-haystack.svg)](https://pypi.org/project/elasticsearch-haystack)
31
31
 
32
- # Elasticsearch Document Store
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
- Document Store for Haystack 2.x, supports ElasticSearch 8.
35
+ ---
35
36
 
36
- ## Installation
37
+ ## Contributing
37
38
 
38
- ```console
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
- ## Testing
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
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`.
@@ -0,0 +1,12 @@
1
+ haystack_integrations/components/retrievers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/retrievers/elasticsearch/__init__.py,sha256=cSJBsYjz_T4kK-M-auAHVUnYIcgUqqwwQe_hsF0_IG4,307
3
+ haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py,sha256=HsR42EolOBEIuLNwQ_8FeSmrHMJ6WscYulcoXSHoaYQ,7098
4
+ haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=-6eIHW5cU4k8-jAsUsCb15hJRalpkUhzy_dNxr5HUZo,7404
5
+ haystack_integrations/document_stores/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ haystack_integrations/document_stores/elasticsearch/__init__.py,sha256=YTfu94dtVUBogbJFr1aJrKuaI6-Bw9VuHfPoyU7M8os,207
7
+ haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=1KnQdBsD-QdvncxFZ1oaNTA9-vRJ7xXCDaKr5JcTVnE,31062
8
+ haystack_integrations/document_stores/elasticsearch/filters.py,sha256=Umip-PP4uFjuWeB1JWkKhaKClQ0VpiykoDlDu99wIV0,9759
9
+ elasticsearch_haystack-4.0.0.dist-info/METADATA,sha256=Ukr9NBPT0Vwi8WhAA5agHeOQfB3_0_6RcGQDx_yJB2w,2105
10
+ elasticsearch_haystack-4.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
11
+ elasticsearch_haystack-4.0.0.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
12
+ elasticsearch_haystack-4.0.0.dist-info/RECORD,,
@@ -116,7 +116,9 @@ class ElasticsearchBM25Retriever:
116
116
  return default_from_dict(cls, data)
117
117
 
118
118
  @component.output_types(documents=List[Document])
119
- def run(self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None):
119
+ def run(
120
+ self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None
121
+ ) -> Dict[str, List[Document]]:
120
122
  """
121
123
  Retrieve documents using the BM25 keyword-based algorithm.
122
124
 
@@ -139,7 +141,9 @@ class ElasticsearchBM25Retriever:
139
141
  return {"documents": docs}
140
142
 
141
143
  @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):
144
+ async def run_async(
145
+ self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None
146
+ ) -> Dict[str, List[Document]]:
143
147
  """
144
148
  Asynchronously retrieve documents using the BM25 keyword-based algorithm.
145
149
 
@@ -114,7 +114,9 @@ class ElasticsearchEmbeddingRetriever:
114
114
  return default_from_dict(cls, data)
115
115
 
116
116
  @component.output_types(documents=List[Document])
117
- def run(self, query_embedding: List[float], filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None):
117
+ def run(
118
+ self, query_embedding: List[float], filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None
119
+ ) -> Dict[str, List[Document]]:
118
120
  """
119
121
  Retrieve documents using a vector similarity metric.
120
122
 
@@ -139,7 +141,7 @@ class ElasticsearchEmbeddingRetriever:
139
141
  @component.output_types(documents=List[Document])
140
142
  async def run_async(
141
143
  self, query_embedding: List[float], filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None
142
- ):
144
+ ) -> Dict[str, List[Document]]:
143
145
  """
144
146
  Asynchronously retrieve documents using a vector similarity metric.
145
147
 
File without changes
@@ -1,20 +1,20 @@
1
1
  # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
+
4
5
  from collections.abc import Mapping
5
- from typing import Any, Dict, List, Literal, Optional, Union
6
+ from typing import Any, Dict, List, Literal, Optional, Tuple, Union
6
7
 
7
8
  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]
9
+ from elastic_transport import NodeConfig
11
10
  from haystack import default_from_dict, default_to_dict, logging
12
11
  from haystack.dataclasses import Document
13
12
  from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumentError
14
13
  from haystack.document_stores.types import DuplicatePolicy
14
+ from haystack.utils import Secret, deserialize_secrets_inplace
15
15
  from haystack.version import __version__ as haystack_version
16
16
 
17
- from elasticsearch import AsyncElasticsearch, Elasticsearch, helpers # type: ignore[import-not-found]
17
+ from elasticsearch import AsyncElasticsearch, Elasticsearch, helpers
18
18
 
19
19
  from .filters import _normalize_filters
20
20
 
@@ -40,13 +40,16 @@ class ElasticsearchDocumentStore:
40
40
 
41
41
  Usage example (Elastic Cloud):
42
42
  ```python
43
- from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
44
- document_store = ElasticsearchDocumentStore(cloud_id="YOUR_CLOUD_ID", api_key="YOUR_API_KEY")
43
+ from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore
44
+ document_store = ElasticsearchDocumentStore(
45
+ api_key_id=Secret.from_env_var("ELASTIC_API_KEY_ID", strict=False),
46
+ api_key=Secret.from_env_var("ELASTIC_API_KEY", strict=False),
47
+ )
45
48
  ```
46
49
 
47
50
  Usage example (self-hosted Elasticsearch instance):
48
51
  ```python
49
- from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
52
+ from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore
50
53
  document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200")
51
54
  ```
52
55
  In the above example we connect with security disabled just to show the basic usage.
@@ -65,8 +68,10 @@ class ElasticsearchDocumentStore:
65
68
  hosts: Optional[Hosts] = None,
66
69
  custom_mapping: Optional[Dict[str, Any]] = None,
67
70
  index: str = "default",
71
+ api_key: Secret = Secret.from_env_var("ELASTIC_API_KEY", strict=False), # noqa: B008
72
+ api_key_id: Secret = Secret.from_env_var("ELASTIC_API_KEY_ID", strict=False), # noqa: B008
68
73
  embedding_similarity_function: Literal["cosine", "dot_product", "l2_norm", "max_inner_product"] = "cosine",
69
- **kwargs,
74
+ **kwargs: Any,
70
75
  ):
71
76
  """
72
77
  Creates a new ElasticsearchDocumentStore instance.
@@ -82,9 +87,16 @@ class ElasticsearchDocumentStore:
82
87
  For the full list of supported kwargs, see the official Elasticsearch
83
88
  [reference](https://elasticsearch-py.readthedocs.io/en/stable/api.html#module-elasticsearch)
84
89
 
90
+ Authentication is provided via Secret objects, which by default are loaded from environment variables.
91
+ You can either provide both `api_key_id` and `api_key`, or just `api_key` containing a base64-encoded string
92
+ of `id:secret`. Secret instances can also be loaded from a token using the `Secret.from_token()` method.
93
+
85
94
  :param hosts: List of hosts running the Elasticsearch client.
86
95
  :param custom_mapping: Custom mapping for the index. If not provided, a default mapping will be used.
87
96
  :param index: Name of index in Elasticsearch.
97
+ :param api_key: A Secret object containing the API key for authenticating or base64-encoded with the
98
+ concatenated secret and id for authenticating with Elasticsearch (separated by “:”).
99
+ :param api_key_id: A Secret object containing the API key ID for authenticating with Elasticsearch.
88
100
  :param embedding_similarity_function: The similarity function used to compare Documents embeddings.
89
101
  This parameter only takes effect if the index does not yet exist and is created.
90
102
  To choose the most appropriate function, look for information about your embedding model.
@@ -93,9 +105,11 @@ class ElasticsearchDocumentStore:
93
105
  :param **kwargs: Optional arguments that `Elasticsearch` takes.
94
106
  """
95
107
  self._hosts = hosts
96
- self._client = None
97
- self._async_client = None
108
+ self._client: Optional[Elasticsearch] = None
109
+ self._async_client: Optional[AsyncElasticsearch] = None
98
110
  self._index = index
111
+ self._api_key = api_key
112
+ self._api_key_id = api_key_id
99
113
  self._embedding_similarity_function = embedding_similarity_function
100
114
  self._custom_mapping = custom_mapping
101
115
  self._kwargs = kwargs
@@ -113,14 +127,18 @@ class ElasticsearchDocumentStore:
113
127
  headers = self._kwargs.pop("headers", {})
114
128
  headers["user-agent"] = f"haystack-py-ds/{haystack_version}"
115
129
 
130
+ api_key = self._handle_auth()
131
+
116
132
  # Initialize both sync and async clients
117
133
  self._client = Elasticsearch(
118
134
  self._hosts,
135
+ api_key=api_key,
119
136
  headers=headers,
120
137
  **self._kwargs,
121
138
  )
122
139
  self._async_client = AsyncElasticsearch(
123
140
  self._hosts,
141
+ api_key=api_key,
124
142
  headers=headers,
125
143
  **self._kwargs,
126
144
  )
@@ -160,12 +178,56 @@ class ElasticsearchDocumentStore:
160
178
 
161
179
  self._initialized = True
162
180
 
181
+ def _handle_auth(self) -> Optional[Union[str, Tuple[str, str]]]:
182
+ """
183
+ Handles authentication for the Elasticsearch client.
184
+
185
+ There are three possible scenarios.
186
+
187
+ 1) Authentication with both api_key and api_key_id, either as Secrets or as environment variables. In this case,
188
+ use both for authentication.
189
+
190
+ 2) Authentication with only api_key, either as a Secret or as an environment variable. In this case, the api_key
191
+ must be a base64-encoded string that encodes both id and secret <id:secret>.
192
+
193
+ 3) There's no authentication, neither api_key nor api_key_id are provided as a Secret nor defined as
194
+ environment variables. In this case, the client will connect without authentication.
195
+
196
+ :returns:
197
+ api_key: Optional[Union[str, Tuple[str, str]]]
198
+
199
+ """
200
+
201
+ api_key: Optional[Union[str, Tuple[str, str]]] # make the type checker happy
202
+
203
+ api_key_resolved = self._api_key.resolve_value()
204
+ api_key_id_resolved = self._api_key_id.resolve_value()
205
+
206
+ # Scenario 1: both are found, use them
207
+ if api_key_id_resolved and api_key_resolved:
208
+ api_key = (api_key_id_resolved, api_key_resolved)
209
+ return api_key
210
+
211
+ # Scenario 2: only api_key is set, must be a base64-encoded string that encodes id and secret (separated by “:”)
212
+ elif api_key_resolved and not api_key_id_resolved:
213
+ return api_key_resolved
214
+
215
+ # Error: only api_key_id is found, raise an error
216
+ elif api_key_id_resolved and not api_key_resolved:
217
+ msg = "api_key_id is provided but api_key is missing."
218
+ raise ValueError(msg)
219
+
220
+ else:
221
+ # Scenario 3: neither found, no authentication
222
+ return None
223
+
163
224
  @property
164
225
  def client(self) -> Elasticsearch:
165
226
  """
166
227
  Returns the synchronous Elasticsearch client, initializing it if necessary.
167
228
  """
168
229
  self._ensure_initialized()
230
+ assert self._client is not None # noqa: S101
169
231
  return self._client
170
232
 
171
233
  @property
@@ -174,6 +236,7 @@ class ElasticsearchDocumentStore:
174
236
  Returns the asynchronous Elasticsearch client, initializing it if necessary.
175
237
  """
176
238
  self._ensure_initialized()
239
+ assert self._async_client is not None # noqa: S101
177
240
  return self._async_client
178
241
 
179
242
  def to_dict(self) -> Dict[str, Any]:
@@ -191,6 +254,8 @@ class ElasticsearchDocumentStore:
191
254
  hosts=self._hosts,
192
255
  custom_mapping=self._custom_mapping,
193
256
  index=self._index,
257
+ api_key=self._api_key.to_dict(),
258
+ api_key_id=self._api_key_id.to_dict(),
194
259
  embedding_similarity_function=self._embedding_similarity_function,
195
260
  **self._kwargs,
196
261
  )
@@ -205,6 +270,7 @@ class ElasticsearchDocumentStore:
205
270
  :returns:
206
271
  Deserialized component.
207
272
  """
273
+ deserialize_secrets_inplace(data, keys=["api_key", "api_key_id"])
208
274
  return default_from_dict(cls, data)
209
275
 
210
276
  def count_documents(self) -> int:
@@ -226,7 +292,7 @@ class ElasticsearchDocumentStore:
226
292
  result = await self._async_client.count(index=self._index) # type: ignore
227
293
  return result["count"]
228
294
 
229
- def _search_documents(self, **kwargs) -> List[Document]:
295
+ def _search_documents(self, **kwargs: Any) -> List[Document]:
230
296
  """
231
297
  Calls the Elasticsearch client's search method and handles pagination.
232
298
  """
@@ -253,7 +319,7 @@ class ElasticsearchDocumentStore:
253
319
  break
254
320
  return documents
255
321
 
256
- async def _search_documents_async(self, **kwargs) -> List[Document]:
322
+ async def _search_documents_async(self, **kwargs: Any) -> List[Document]:
257
323
  """
258
324
  Asynchronously calls the Elasticsearch client's search method and handles pagination.
259
325
  """
@@ -379,9 +445,12 @@ class ElasticsearchDocumentStore:
379
445
  refresh="wait_for",
380
446
  index=self._index,
381
447
  raise_on_error=False,
448
+ stats_only=False,
382
449
  )
383
450
 
384
451
  if errors:
452
+ # with stats_only=False, errors is guaranteed to be a list of dicts
453
+ assert isinstance(errors, list) # noqa: S101
385
454
  duplicate_errors_ids = []
386
455
  other_errors = []
387
456
  for e in errors:
@@ -451,13 +520,16 @@ class ElasticsearchDocumentStore:
451
520
 
452
521
  try:
453
522
  success, failed = await helpers.async_bulk(
454
- client=self._async_client,
523
+ client=self.async_client,
455
524
  actions=actions,
456
525
  index=self._index,
457
526
  refresh=True,
458
527
  raise_on_error=False,
528
+ stats_only=False,
459
529
  )
460
530
  if failed:
531
+ # with stats_only=False, failed is guaranteed to be a list of dicts
532
+ assert isinstance(failed, list) # noqa: S101
461
533
  if policy == DuplicatePolicy.FAIL:
462
534
  for error in failed:
463
535
  if "create" in error and error["create"]["status"] == DOC_ALREADY_EXISTS:
@@ -494,7 +566,7 @@ class ElasticsearchDocumentStore:
494
566
 
495
567
  try:
496
568
  await helpers.async_bulk(
497
- client=self._async_client,
569
+ client=self.async_client,
498
570
  actions=({"_op_type": "delete", "_id": id_} for id_ in document_ids),
499
571
  index=self._index,
500
572
  refresh=True,
@@ -551,6 +623,8 @@ class ElasticsearchDocumentStore:
551
623
 
552
624
  if scale_score:
553
625
  for doc in documents:
626
+ if doc.score is None:
627
+ continue
554
628
  doc.score = float(1 / (1 + np.exp(-np.asarray(doc.score / BM25_SCALING_FACTOR))))
555
629
 
556
630
  return documents
File without changes
@@ -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=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=pZ0pPyOCPTCKNYD4q5YbLrslSGTIbVPj60U18-BImX8,27406
6
- haystack_integrations/document_stores/elasticsearch/filters.py,sha256=Umip-PP4uFjuWeB1JWkKhaKClQ0VpiykoDlDu99wIV0,9759
7
- elasticsearch_haystack-3.0.1.dist-info/METADATA,sha256=defq5KselqQwwMLUa3jfrmXjjVxH15cLSn7iKlDKgJk,2257
8
- elasticsearch_haystack-3.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
- elasticsearch_haystack-3.0.1.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
10
- elasticsearch_haystack-3.0.1.dist-info/RECORD,,