elasticsearch-haystack 0.2.0__py3-none-any.whl → 0.4.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
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.3
2
2
  Name: elasticsearch-haystack
3
- Version: 0.2.0
3
+ Version: 0.4.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
@@ -1,10 +1,10 @@
1
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=Taq5pPDIu5lUuCgdbbZoGCMozUIoKqCVzcc085jGpNg,4277
3
- haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=Y2C4Foeiqg2-bOEcc_WEyC62k96DqjnMqBllPcgCrxk,3392
2
+ haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py,sha256=fFx554MTcUHnQZa2SgC0PzIR85YVbqAdMNOiXKkVSu8,4849
3
+ haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=RcIbSMELiKIJsD-8F_u76J33YRt5bLr6lHnoX-hVQ1M,4990
4
4
  haystack_integrations/document_stores/elasticsearch/__init__.py,sha256=YTfu94dtVUBogbJFr1aJrKuaI6-Bw9VuHfPoyU7M8os,207
5
- haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=SDaPCgK1B_O3G7pNa2Z71YktvgpAHDGgC_gHuzy2HTE,15416
5
+ haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=m_NvCRt0xQhVuTdkfxaqql4sB7qVDyYc8f9LaWMoLyA,17688
6
6
  haystack_integrations/document_stores/elasticsearch/filters.py,sha256=L1tN7YCIDuNdhGrBQdPoqXFk37x__2-K038xZ6PRdNQ,9923
7
- elasticsearch_haystack-0.2.0.dist-info/METADATA,sha256=Enr2ufED5ISLsuRqZatL08Zg_Wss1x9A8uyS1eXCUsw,2105
8
- elasticsearch_haystack-0.2.0.dist-info/WHEEL,sha256=mRYSEL3Ih6g5a_CVMIcwiF__0Ae4_gLYh01YFNwiq1k,87
9
- elasticsearch_haystack-0.2.0.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
10
- elasticsearch_haystack-0.2.0.dist-info/RECORD,,
7
+ elasticsearch_haystack-0.4.0.dist-info/METADATA,sha256=sHF3d2RaJjZ8DQ8W7Vm1e8iZN01W8BjlsPIUkrpF8yg,2105
8
+ elasticsearch_haystack-0.4.0.dist-info/WHEEL,sha256=uNdcs2TADwSd5pVaP0Z_kcjcvvTUklh2S7bxZMF8Uj0,87
9
+ elasticsearch_haystack-0.4.0.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
10
+ elasticsearch_haystack-0.4.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.21.0
2
+ Generator: hatchling 1.22.4
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -11,8 +11,9 @@ from haystack_integrations.document_stores.elasticsearch.document_store import E
11
11
  @component
12
12
  class ElasticsearchBM25Retriever:
13
13
  """
14
- ElasticsearchBM25Retriever is a keyword-based retriever that uses BM25 to find the most
15
- similar documents to a user's query.
14
+ ElasticsearchBM25Retriever retrieves documents from the ElasticsearchDocumentStore using BM25 algorithm to find the
15
+ most similar documents to a user's query.
16
+
16
17
  This retriever is only compatible with ElasticsearchDocumentStore.
17
18
 
18
19
  Usage example:
@@ -35,7 +36,7 @@ class ElasticsearchBM25Retriever:
35
36
 
36
37
  result = retriever.run(query="Who lives in Berlin?")
37
38
  for doc in result["documents"]:
38
- print(doc.text)
39
+ print(doc.content)
39
40
  ```
40
41
  """
41
42
 
@@ -53,12 +54,13 @@ class ElasticsearchBM25Retriever:
53
54
 
54
55
  :param document_store: An instance of ElasticsearchDocumentStore.
55
56
  :param filters: Filters applied to the retrieved Documents, for more info
56
- see `ElasticsearchDocumentStore.filter_documents`, defaults to None
57
- :param fuzziness: Fuzziness parameter passed to Elasticsearch, defaults to "AUTO".
58
- see the official documentation for valid values:
59
- https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness
60
- :param top_k: Maximum number of Documents to return, defaults to 10
61
- :param scale_score: If `True` scales the Document`s scores between 0 and 1, defaults to False
57
+ see `ElasticsearchDocumentStore.filter_documents`.
58
+ :param fuzziness: Fuzziness parameter passed to Elasticsearch. See the official
59
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness)
60
+ for more details.
61
+ :param top_k: Maximum number of Documents to return.
62
+ :param scale_score: If `True` scales the Document`s scores between 0 and 1.
63
+ :raises ValueError: If `document_store` is not an instance of `ElasticsearchDocumentStore`.
62
64
  """
63
65
 
64
66
  if not isinstance(document_store, ElasticsearchDocumentStore):
@@ -72,6 +74,12 @@ class ElasticsearchBM25Retriever:
72
74
  self._scale_score = scale_score
73
75
 
74
76
  def to_dict(self) -> Dict[str, Any]:
77
+ """
78
+ Serializes the component to a dictionary.
79
+
80
+ :returns:
81
+ Dictionary with serialized data.
82
+ """
75
83
  return default_to_dict(
76
84
  self,
77
85
  filters=self._filters,
@@ -83,23 +91,33 @@ class ElasticsearchBM25Retriever:
83
91
 
84
92
  @classmethod
85
93
  def from_dict(cls, data: Dict[str, Any]) -> "ElasticsearchBM25Retriever":
94
+ """
95
+ Deserializes the component from a dictionary.
96
+
97
+ :param data:
98
+ Dictionary to deserialize from.
99
+ :returns:
100
+ Deserialized component.
101
+ """
86
102
  data["init_parameters"]["document_store"] = ElasticsearchDocumentStore.from_dict(
87
103
  data["init_parameters"]["document_store"]
88
104
  )
89
105
  return default_from_dict(cls, data)
90
106
 
91
107
  @component.output_types(documents=List[Document])
92
- def run(self, query: str, top_k: Optional[int] = None):
108
+ def run(self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None):
93
109
  """
94
110
  Retrieve documents using the BM25 keyword-based algorithm.
95
111
 
96
- :param query: String to search in Documents' text.
97
- :param top_k: Maximum number of Documents to return.
98
- :return: List of Documents that match the query.
112
+ :param query: String to search in `Document`s' text.
113
+ :param filters: Filters applied to the retrieved `Document`s.
114
+ :param top_k: Maximum number of `Document` to return.
115
+ :returns: A dictionary with the following keys:
116
+ - `documents`: List of `Document`s that match the query.
99
117
  """
100
118
  docs = self._document_store._bm25_retrieval(
101
119
  query=query,
102
- filters=self._filters,
120
+ filters=filters or self._filters,
103
121
  fuzziness=self._fuzziness,
104
122
  top_k=top_k or self._top_k,
105
123
  scale_score=self._scale_score,
@@ -11,9 +11,35 @@ from haystack_integrations.document_stores.elasticsearch.document_store import E
11
11
  @component
12
12
  class ElasticsearchEmbeddingRetriever:
13
13
  """
14
- Uses a vector similarity metric to retrieve documents from the ElasticsearchDocumentStore.
14
+ ElasticsearchEmbeddingRetriever retrieves documents from the ElasticsearchDocumentStore using vector similarity.
15
15
 
16
- Needs to be connected to the ElasticsearchDocumentStore to run.
16
+ Usage example:
17
+ ```python
18
+ from haystack import Document
19
+ from haystack.components.embedders import SentenceTransformersTextEmbedder
20
+ from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore
21
+ from haystack_integrations.components.retrievers.elasticsearch import ElasticsearchEmbeddingRetriever
22
+
23
+ document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200")
24
+ retriever = ElasticsearchEmbeddingRetriever(document_store=document_store)
25
+
26
+ # Add documents to DocumentStore
27
+ documents = [
28
+ Document(text="My name is Carla and I live in Berlin"),
29
+ Document(text="My name is Paul and I live in New York"),
30
+ Document(text="My name is Silvano and I live in Matera"),
31
+ Document(text="My name is Usagi Tsukino and I live in Tokyo"),
32
+ ]
33
+ document_store.write_documents(documents)
34
+
35
+ te = SentenceTransformersTextEmbedder()
36
+ te.warm_up()
37
+ query_embeddings = te.run("Who lives in Berlin?")["embedding"]
38
+
39
+ result = retriever.run(query=query_embeddings)
40
+ for doc in result["documents"]:
41
+ print(doc.content)
42
+ ```
17
43
  """
18
44
 
19
45
  def __init__(
@@ -28,13 +54,13 @@ class ElasticsearchEmbeddingRetriever:
28
54
  Create the ElasticsearchEmbeddingRetriever component.
29
55
 
30
56
  :param document_store: An instance of ElasticsearchDocumentStore.
31
- :param filters: Filters applied to the retrieved Documents. Defaults to None.
32
- Filters are applied during the approximate kNN search to ensure that top_k matching documents are returned.
33
- :param top_k: Maximum number of Documents to return, defaults to 10
57
+ :param filters: Filters applied to the retrieved Documents.
58
+ Filters are applied during the approximate KNN search to ensure that top_k matching documents are returned.
59
+ :param top_k: Maximum number of Documents to return.
34
60
  :param num_candidates: Number of approximate nearest neighbor candidates on each shard. Defaults to top_k * 10.
35
61
  Increasing this value will improve search accuracy at the cost of slower search speeds.
36
- You can read more about it in the Elasticsearch documentation:
37
- https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy
62
+ You can read more about it in the Elasticsearch
63
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)
38
64
  :raises ValueError: If `document_store` is not an instance of ElasticsearchDocumentStore.
39
65
  """
40
66
  if not isinstance(document_store, ElasticsearchDocumentStore):
@@ -47,6 +73,12 @@ class ElasticsearchEmbeddingRetriever:
47
73
  self._num_candidates = num_candidates
48
74
 
49
75
  def to_dict(self) -> Dict[str, Any]:
76
+ """
77
+ Serializes the component to a dictionary.
78
+
79
+ :returns:
80
+ Dictionary with serialized data.
81
+ """
50
82
  return default_to_dict(
51
83
  self,
52
84
  filters=self._filters,
@@ -57,23 +89,33 @@ class ElasticsearchEmbeddingRetriever:
57
89
 
58
90
  @classmethod
59
91
  def from_dict(cls, data: Dict[str, Any]) -> "ElasticsearchEmbeddingRetriever":
92
+ """
93
+ Deserializes the component from a dictionary.
94
+
95
+ :param data:
96
+ Dictionary to deserialize from.
97
+ :returns:
98
+ Deserialized component.
99
+ """
60
100
  data["init_parameters"]["document_store"] = ElasticsearchDocumentStore.from_dict(
61
101
  data["init_parameters"]["document_store"]
62
102
  )
63
103
  return default_from_dict(cls, data)
64
104
 
65
105
  @component.output_types(documents=List[Document])
66
- def run(self, query_embedding: List[float], top_k: Optional[int] = None):
106
+ def run(self, query_embedding: List[float], filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None):
67
107
  """
68
108
  Retrieve documents using a vector similarity metric.
69
109
 
70
110
  :param query_embedding: Embedding of the query.
71
- :param top_k: Maximum number of Documents to return.
72
- :return: List of Documents similar to `query_embedding`.
111
+ :param filters: Filters applied to the retrieved `Document`s.
112
+ :param top_k: Maximum number of `Document`s to return.
113
+ :returns: A dictionary with the following keys:
114
+ - `documents`: List of `Document`s most similar to the given `query_embedding`
73
115
  """
74
116
  docs = self._document_store._embedding_retrieval(
75
117
  query_embedding=query_embedding,
76
- filters=self._filters,
118
+ filters=filters or self._filters,
77
119
  top_k=top_k or self._top_k,
78
120
  num_candidates=self._num_candidates,
79
121
  )
@@ -13,6 +13,7 @@ from haystack.dataclasses import Document
13
13
  from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumentError
14
14
  from haystack.document_stores.types import DuplicatePolicy
15
15
  from haystack.utils.filters import convert
16
+ from haystack.version import __version__ as haystack_version
16
17
 
17
18
  from elasticsearch import Elasticsearch, helpers # type: ignore[import-not-found]
18
19
 
@@ -34,16 +35,16 @@ BM25_SCALING_FACTOR = 8
34
35
 
35
36
  class ElasticsearchDocumentStore:
36
37
  """
37
- ElasticsearchDocumentStore is a Document Store for Elasticsearch.
38
- It can be used with Elastic Cloud or your own Elasticsearch cluster.
38
+ ElasticsearchDocumentStore is a Document Store for Elasticsearch. It can be used with Elastic Cloud or your own
39
+ Elasticsearch cluster.
39
40
 
40
- Simple usage with Elastic Cloud:
41
+ Usage example (Elastic Cloud):
41
42
  ```python
42
43
  from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
43
44
  document_store = ElasticsearchDocumentStore(cloud_id="YOUR_CLOUD_ID", api_key="YOUR_API_KEY")
44
45
  ```
45
46
 
46
- One can also connect to a self-hosted Elasticsearch instance:
47
+ Usage example (self-hosted Elasticsearch instance):
47
48
  ```python
48
49
  from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
49
50
  document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200")
@@ -52,8 +53,8 @@ class ElasticsearchDocumentStore:
52
53
  We strongly recommend to enable security so that only authorized users can access your data.
53
54
 
54
55
  For more details on how to connect to Elasticsearch and configure security,
55
- see the official Elasticsearch documentation:
56
- https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html
56
+ see the official Elasticsearch
57
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html)
57
58
 
58
59
  All extra keyword arguments will be passed to the Elasticsearch client.
59
60
  """
@@ -68,29 +69,33 @@ class ElasticsearchDocumentStore:
68
69
  ):
69
70
  """
70
71
  Creates a new ElasticsearchDocumentStore instance.
71
- When no index is explicitly specified, it will use the default index "default".
72
- It will also try to create that index if it doesn't exist yet. Otherwise it will use the existing one.
72
+
73
+ It will also try to create that index if it doesn't exist yet. Otherwise, it will use the existing one.
73
74
 
74
75
  One can also set the similarity function used to compare Documents embeddings. This is mostly useful
75
76
  when using the `ElasticsearchDocumentStore` in a Pipeline with an `ElasticsearchEmbeddingRetriever`.
76
77
 
77
- For more information on connection parameters, see the official Elasticsearch documentation:
78
- https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html
78
+ For more information on connection parameters, see the official Elasticsearch
79
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html)
79
80
 
80
- For the full list of supported kwargs, see the official Elasticsearch reference:
81
- https://elasticsearch-py.readthedocs.io/en/stable/api.html#module-elasticsearch
81
+ For the full list of supported kwargs, see the official Elasticsearch
82
+ [reference](https://elasticsearch-py.readthedocs.io/en/stable/api.html#module-elasticsearch)
82
83
 
83
- :param hosts: List of hosts running the Elasticsearch client. Defaults to None
84
- :param index: Name of index in Elasticsearch, if it doesn't exist it will be created. Defaults to "default"
84
+ :param hosts: List of hosts running the Elasticsearch client.
85
+ :param index: Name of index in Elasticsearch.
85
86
  :param embedding_similarity_function: The similarity function used to compare Documents embeddings.
86
- Defaults to "cosine". This parameter only takes effect if the index does not yet exist and is created.
87
+ This parameter only takes effect if the index does not yet exist and is created.
87
88
  To choose the most appropriate function, look for information about your embedding model.
88
- To understand how document scores are computed, see the Elasticsearch documentation:
89
- https://www.elastic.co/guide/en/elasticsearch/reference/current/dense-vector.html#dense-vector-params
90
- :param **kwargs: Optional arguments that ``Elasticsearch`` takes.
89
+ To understand how document scores are computed, see the Elasticsearch
90
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/dense-vector.html#dense-vector-params)
91
+ :param **kwargs: Optional arguments that `Elasticsearch` takes.
91
92
  """
92
93
  self._hosts = hosts
93
- self._client = Elasticsearch(hosts, **kwargs)
94
+ self._client = Elasticsearch(
95
+ hosts,
96
+ headers={"user-agent": f"haystack-py-ds/{haystack_version}"},
97
+ **kwargs,
98
+ )
94
99
  self._index = index
95
100
  self._embedding_similarity_function = embedding_similarity_function
96
101
  self._kwargs = kwargs
@@ -101,8 +106,20 @@ class ElasticsearchDocumentStore:
101
106
  # configure mapping for the embedding field
102
107
  mappings = {
103
108
  "properties": {
104
- "embedding": {"type": "dense_vector", "index": True, "similarity": embedding_similarity_function}
105
- }
109
+ "embedding": {"type": "dense_vector", "index": True, "similarity": embedding_similarity_function},
110
+ "content": {"type": "text"},
111
+ },
112
+ "dynamic_templates": [
113
+ {
114
+ "strings": {
115
+ "path_match": "*",
116
+ "match_mapping_type": "string",
117
+ "mapping": {
118
+ "type": "keyword",
119
+ },
120
+ }
121
+ }
122
+ ],
106
123
  }
107
124
 
108
125
  # Create the index if it doesn't exist
@@ -110,6 +127,12 @@ class ElasticsearchDocumentStore:
110
127
  self._client.indices.create(index=index, mappings=mappings)
111
128
 
112
129
  def to_dict(self) -> Dict[str, Any]:
130
+ """
131
+ Serializes the component to a dictionary.
132
+
133
+ :returns:
134
+ Dictionary with serialized data.
135
+ """
113
136
  # This is not the best solution to serialise this class but is the fastest to implement.
114
137
  # Not all kwargs types can be serialised to text so this can fail. We must serialise each
115
138
  # type explicitly to handle this properly.
@@ -123,11 +146,20 @@ class ElasticsearchDocumentStore:
123
146
 
124
147
  @classmethod
125
148
  def from_dict(cls, data: Dict[str, Any]) -> "ElasticsearchDocumentStore":
149
+ """
150
+ Deserializes the component from a dictionary.
151
+
152
+ :param data:
153
+ Dictionary to deserialize from.
154
+ :returns:
155
+ Deserialized component.
156
+ """
126
157
  return default_from_dict(cls, data)
127
158
 
128
159
  def count_documents(self) -> int:
129
160
  """
130
161
  Returns how many documents are present in the document store.
162
+ :returns: Number of documents in the document store.
131
163
  """
132
164
  return self._client.count(index=self._index)["count"]
133
165
 
@@ -160,6 +192,14 @@ class ElasticsearchDocumentStore:
160
192
  return documents
161
193
 
162
194
  def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]:
195
+ """
196
+ The main query method for the document store. It retrieves all documents that match the filters.
197
+
198
+ :param filters: A dictionary of filters to apply. For more information on the structure of the filters,
199
+ see the official Elasticsearch
200
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html)
201
+ :returns: List of `Document`s that match the filters.
202
+ """
163
203
  if filters and "operator" not in filters and "conditions" not in filters:
164
204
  filters = convert(filters)
165
205
 
@@ -169,9 +209,15 @@ class ElasticsearchDocumentStore:
169
209
 
170
210
  def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int:
171
211
  """
172
- Writes Documents to Elasticsearch.
173
- If policy is not specified or set to DuplicatePolicy.NONE, it will raise an exception if a document with the
174
- same ID already exists in the document store.
212
+ Writes `Document`s to Elasticsearch.
213
+
214
+ :param documents: List of Documents to write to the document store.
215
+ :param policy: DuplicatePolicy to apply when a document with the same ID already exists in the document store.
216
+ :raises ValueError: If `documents` is not a list of `Document`s.
217
+ :raises DuplicateDocumentError: If a document with the same ID already exists in the document store and
218
+ `policy` is set to `DuplicatePolicy.FAIL` or `DuplicatePolicy.NONE`.
219
+ :raises DocumentStoreError: If an error occurs while writing the documents to the document store.
220
+ :returns: Number of documents written to the document store.
175
221
  """
176
222
  if len(documents) > 0:
177
223
  if not isinstance(documents[0], Document):
@@ -182,16 +228,30 @@ class ElasticsearchDocumentStore:
182
228
  policy = DuplicatePolicy.FAIL
183
229
 
184
230
  action = "index" if policy == DuplicatePolicy.OVERWRITE else "create"
185
- documents_written, errors = helpers.bulk(
186
- client=self._client,
187
- actions=(
231
+
232
+ elasticsearch_actions = []
233
+ for doc in documents:
234
+ doc_dict = doc.to_dict()
235
+ if "sparse_embedding" in doc_dict:
236
+ sparse_embedding = doc_dict.pop("sparse_embedding", None)
237
+ if sparse_embedding:
238
+ logger.warning(
239
+ "Document %s has the `sparse_embedding` field set,"
240
+ "but storing sparse embeddings in Elasticsearch is not currently supported."
241
+ "The `sparse_embedding` field will be ignored.",
242
+ doc.id,
243
+ )
244
+ elasticsearch_actions.append(
188
245
  {
189
246
  "_op_type": action,
190
247
  "_id": doc.id,
191
- "_source": doc.to_dict(),
248
+ "_source": doc_dict,
192
249
  }
193
- for doc in documents
194
- ),
250
+ )
251
+
252
+ documents_written, errors = helpers.bulk(
253
+ client=self._client,
254
+ actions=elasticsearch_actions,
195
255
  refresh="wait_for",
196
256
  index=self._index,
197
257
  raise_on_error=False,
@@ -220,10 +280,15 @@ class ElasticsearchDocumentStore:
220
280
 
221
281
  return documents_written
222
282
 
223
- def _deserialize_document(self, hit: Dict[str, Any]) -> Document:
283
+ @staticmethod
284
+ def _deserialize_document(hit: Dict[str, Any]) -> Document:
224
285
  """
225
- Creates a Document from the search hit provided.
286
+ Creates a `Document` from the search hit provided.
287
+
226
288
  This is mostly useful in self.filter_documents().
289
+
290
+ :param hit: A search hit from Elasticsearch.
291
+ :returns: `Document` created from the search hit.
227
292
  """
228
293
  data = hit["_source"]
229
294
 
@@ -235,12 +300,11 @@ class ElasticsearchDocumentStore:
235
300
 
236
301
  def delete_documents(self, document_ids: List[str]) -> None:
237
302
  """
238
- Deletes all documents with a matching document_ids from the document store.
303
+ Deletes all `Document`s with a matching `document_ids` from the document store.
239
304
 
240
- :param object_ids: the object_ids to delete
305
+ :param document_ids: the object IDs to delete
241
306
  """
242
307
 
243
- #
244
308
  helpers.bulk(
245
309
  client=self._client,
246
310
  actions=({"_op_type": "delete", "_id": id_} for id_ in document_ids),
@@ -259,26 +323,25 @@ class ElasticsearchDocumentStore:
259
323
  scale_score: bool = False,
260
324
  ) -> List[Document]:
261
325
  """
262
- Elasticsearch by defaults uses BM25 search algorithm.
326
+ Retrieves `Document`s from Elasticsearch using the BM25 search algorithm.
327
+
263
328
  Even though this method is called `bm25_retrieval` it searches for `query`
264
329
  using the search algorithm `_client` was configured with.
265
330
 
266
- This method is not mean to be part of the public interface of
331
+ This method is not meant to be part of the public interface of
267
332
  `ElasticsearchDocumentStore` nor called directly.
268
333
  `ElasticsearchBM25Retriever` uses this method directly and is the public interface for it.
269
334
 
270
- `query` must be a non empty string, otherwise a `ValueError` will be raised.
271
-
272
- :param query: String to search in saved Documents' text.
273
- :param filters: Filters applied to the retrieved Documents, for more info
274
- see `ElasticsearchDocumentStore.filter_documents`, defaults to None
275
- :param fuzziness: Fuzziness parameter passed to Elasticsearch, defaults to "AUTO".
276
- see the official documentation for valid values:
277
- https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness
278
- :param top_k: Maximum number of Documents to return, defaults to 10
279
- :param scale_score: If `True` scales the Document`s scores between 0 and 1, defaults to False
335
+ :param query: String to search in saved `Document`s' text.
336
+ :param filters: Filters applied to the retrieved `Document`s, for more info
337
+ see `ElasticsearchDocumentStore.filter_documents`.
338
+ :param fuzziness: Fuzziness parameter passed to Elasticsearch. See the official
339
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness)
340
+ for valid values.
341
+ :param top_k: Maximum number of `Document`s to return.
342
+ :param scale_score: If `True` scales the `Document``s scores between 0 and 1.
280
343
  :raises ValueError: If `query` is an empty string
281
- :return: List of Document that match `query`
344
+ :returns: List of `Document` that match `query`
282
345
  """
283
346
 
284
347
  if not query:
@@ -324,22 +387,23 @@ class ElasticsearchDocumentStore:
324
387
  ) -> List[Document]:
325
388
  """
326
389
  Retrieves documents that are most similar to the query embedding using a vector similarity metric.
390
+
327
391
  It uses the Elasticsearch's Approximate k-Nearest Neighbors search algorithm.
328
392
 
329
- This method is not mean to be part of the public interface of
393
+ This method is not meant to be part of the public interface of
330
394
  `ElasticsearchDocumentStore` nor called directly.
331
395
  `ElasticsearchEmbeddingRetriever` uses this method directly and is the public interface for it.
332
396
 
333
397
  :param query_embedding: Embedding of the query.
334
- :param filters: Filters applied to the retrieved Documents. Defaults to None.
398
+ :param filters: Filters applied to the retrieved `Document`s.
335
399
  Filters are applied during the approximate kNN search to ensure that top_k matching documents are returned.
336
- :param top_k: Maximum number of Documents to return, defaults to 10
400
+ :param top_k: Maximum number of `Document`s to return.
337
401
  :param num_candidates: Number of approximate nearest neighbor candidates on each shard. Defaults to top_k * 10.
338
402
  Increasing this value will improve search accuracy at the cost of slower search speeds.
339
- You can read more about it in the Elasticsearch documentation:
340
- https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy
341
- :raises ValueError: If `query_embedding` is an empty list
342
- :return: List of Document that are most similar to `query_embedding`
403
+ You can read more about it in the Elasticsearch
404
+ [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)
405
+ :raises ValueError: If `query_embedding` is an empty list.
406
+ :returns: List of `Document` that are most similar to `query_embedding`.
343
407
  """
344
408
 
345
409
  if not query_embedding: