elasticsearch9 9.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.
Files changed (160) hide show
  1. elasticsearch9/__init__.py +98 -0
  2. elasticsearch9/_async/__init__.py +16 -0
  3. elasticsearch9/_async/client/__init__.py +6531 -0
  4. elasticsearch9/_async/client/_base.py +430 -0
  5. elasticsearch9/_async/client/async_search.py +637 -0
  6. elasticsearch9/_async/client/autoscaling.py +252 -0
  7. elasticsearch9/_async/client/cat.py +2995 -0
  8. elasticsearch9/_async/client/ccr.py +1043 -0
  9. elasticsearch9/_async/client/cluster.py +1223 -0
  10. elasticsearch9/_async/client/connector.py +1978 -0
  11. elasticsearch9/_async/client/dangling_indices.py +192 -0
  12. elasticsearch9/_async/client/enrich.py +291 -0
  13. elasticsearch9/_async/client/eql.py +359 -0
  14. elasticsearch9/_async/client/esql.py +490 -0
  15. elasticsearch9/_async/client/features.py +130 -0
  16. elasticsearch9/_async/client/fleet.py +658 -0
  17. elasticsearch9/_async/client/graph.py +113 -0
  18. elasticsearch9/_async/client/ilm.py +668 -0
  19. elasticsearch9/_async/client/indices.py +5582 -0
  20. elasticsearch9/_async/client/inference.py +2247 -0
  21. elasticsearch9/_async/client/ingest.py +766 -0
  22. elasticsearch9/_async/client/license.py +400 -0
  23. elasticsearch9/_async/client/logstash.py +176 -0
  24. elasticsearch9/_async/client/migration.py +160 -0
  25. elasticsearch9/_async/client/ml.py +5835 -0
  26. elasticsearch9/_async/client/monitoring.py +100 -0
  27. elasticsearch9/_async/client/nodes.py +543 -0
  28. elasticsearch9/_async/client/query_rules.py +485 -0
  29. elasticsearch9/_async/client/rollup.py +616 -0
  30. elasticsearch9/_async/client/search_application.py +574 -0
  31. elasticsearch9/_async/client/searchable_snapshots.py +313 -0
  32. elasticsearch9/_async/client/security.py +4688 -0
  33. elasticsearch9/_async/client/shutdown.py +268 -0
  34. elasticsearch9/_async/client/simulate.py +145 -0
  35. elasticsearch9/_async/client/slm.py +559 -0
  36. elasticsearch9/_async/client/snapshot.py +1338 -0
  37. elasticsearch9/_async/client/sql.py +469 -0
  38. elasticsearch9/_async/client/ssl.py +76 -0
  39. elasticsearch9/_async/client/synonyms.py +413 -0
  40. elasticsearch9/_async/client/tasks.py +295 -0
  41. elasticsearch9/_async/client/text_structure.py +664 -0
  42. elasticsearch9/_async/client/transform.py +922 -0
  43. elasticsearch9/_async/client/utils.py +48 -0
  44. elasticsearch9/_async/client/watcher.py +894 -0
  45. elasticsearch9/_async/client/xpack.py +134 -0
  46. elasticsearch9/_async/helpers.py +596 -0
  47. elasticsearch9/_otel.py +110 -0
  48. elasticsearch9/_sync/__init__.py +16 -0
  49. elasticsearch9/_sync/client/__init__.py +6529 -0
  50. elasticsearch9/_sync/client/_base.py +430 -0
  51. elasticsearch9/_sync/client/async_search.py +637 -0
  52. elasticsearch9/_sync/client/autoscaling.py +252 -0
  53. elasticsearch9/_sync/client/cat.py +2995 -0
  54. elasticsearch9/_sync/client/ccr.py +1043 -0
  55. elasticsearch9/_sync/client/cluster.py +1223 -0
  56. elasticsearch9/_sync/client/connector.py +1978 -0
  57. elasticsearch9/_sync/client/dangling_indices.py +192 -0
  58. elasticsearch9/_sync/client/enrich.py +291 -0
  59. elasticsearch9/_sync/client/eql.py +359 -0
  60. elasticsearch9/_sync/client/esql.py +490 -0
  61. elasticsearch9/_sync/client/features.py +130 -0
  62. elasticsearch9/_sync/client/fleet.py +658 -0
  63. elasticsearch9/_sync/client/graph.py +113 -0
  64. elasticsearch9/_sync/client/ilm.py +668 -0
  65. elasticsearch9/_sync/client/indices.py +5582 -0
  66. elasticsearch9/_sync/client/inference.py +2247 -0
  67. elasticsearch9/_sync/client/ingest.py +766 -0
  68. elasticsearch9/_sync/client/license.py +400 -0
  69. elasticsearch9/_sync/client/logstash.py +176 -0
  70. elasticsearch9/_sync/client/migration.py +160 -0
  71. elasticsearch9/_sync/client/ml.py +5835 -0
  72. elasticsearch9/_sync/client/monitoring.py +100 -0
  73. elasticsearch9/_sync/client/nodes.py +543 -0
  74. elasticsearch9/_sync/client/query_rules.py +485 -0
  75. elasticsearch9/_sync/client/rollup.py +616 -0
  76. elasticsearch9/_sync/client/search_application.py +574 -0
  77. elasticsearch9/_sync/client/searchable_snapshots.py +313 -0
  78. elasticsearch9/_sync/client/security.py +4688 -0
  79. elasticsearch9/_sync/client/shutdown.py +268 -0
  80. elasticsearch9/_sync/client/simulate.py +145 -0
  81. elasticsearch9/_sync/client/slm.py +559 -0
  82. elasticsearch9/_sync/client/snapshot.py +1338 -0
  83. elasticsearch9/_sync/client/sql.py +469 -0
  84. elasticsearch9/_sync/client/ssl.py +76 -0
  85. elasticsearch9/_sync/client/synonyms.py +413 -0
  86. elasticsearch9/_sync/client/tasks.py +295 -0
  87. elasticsearch9/_sync/client/text_structure.py +664 -0
  88. elasticsearch9/_sync/client/transform.py +922 -0
  89. elasticsearch9/_sync/client/utils.py +475 -0
  90. elasticsearch9/_sync/client/watcher.py +894 -0
  91. elasticsearch9/_sync/client/xpack.py +134 -0
  92. elasticsearch9/_utils.py +34 -0
  93. elasticsearch9/_version.py +18 -0
  94. elasticsearch9/client.py +126 -0
  95. elasticsearch9/compat.py +79 -0
  96. elasticsearch9/dsl/__init__.py +203 -0
  97. elasticsearch9/dsl/_async/__init__.py +16 -0
  98. elasticsearch9/dsl/_async/document.py +522 -0
  99. elasticsearch9/dsl/_async/faceted_search.py +50 -0
  100. elasticsearch9/dsl/_async/index.py +639 -0
  101. elasticsearch9/dsl/_async/mapping.py +49 -0
  102. elasticsearch9/dsl/_async/search.py +237 -0
  103. elasticsearch9/dsl/_async/update_by_query.py +47 -0
  104. elasticsearch9/dsl/_sync/__init__.py +16 -0
  105. elasticsearch9/dsl/_sync/document.py +514 -0
  106. elasticsearch9/dsl/_sync/faceted_search.py +50 -0
  107. elasticsearch9/dsl/_sync/index.py +597 -0
  108. elasticsearch9/dsl/_sync/mapping.py +49 -0
  109. elasticsearch9/dsl/_sync/search.py +230 -0
  110. elasticsearch9/dsl/_sync/update_by_query.py +45 -0
  111. elasticsearch9/dsl/aggs.py +3734 -0
  112. elasticsearch9/dsl/analysis.py +341 -0
  113. elasticsearch9/dsl/async_connections.py +37 -0
  114. elasticsearch9/dsl/connections.py +142 -0
  115. elasticsearch9/dsl/document.py +20 -0
  116. elasticsearch9/dsl/document_base.py +444 -0
  117. elasticsearch9/dsl/exceptions.py +32 -0
  118. elasticsearch9/dsl/faceted_search.py +28 -0
  119. elasticsearch9/dsl/faceted_search_base.py +489 -0
  120. elasticsearch9/dsl/field.py +4392 -0
  121. elasticsearch9/dsl/function.py +180 -0
  122. elasticsearch9/dsl/index.py +23 -0
  123. elasticsearch9/dsl/index_base.py +178 -0
  124. elasticsearch9/dsl/mapping.py +19 -0
  125. elasticsearch9/dsl/mapping_base.py +219 -0
  126. elasticsearch9/dsl/query.py +2822 -0
  127. elasticsearch9/dsl/response/__init__.py +388 -0
  128. elasticsearch9/dsl/response/aggs.py +100 -0
  129. elasticsearch9/dsl/response/hit.py +53 -0
  130. elasticsearch9/dsl/search.py +20 -0
  131. elasticsearch9/dsl/search_base.py +1053 -0
  132. elasticsearch9/dsl/serializer.py +34 -0
  133. elasticsearch9/dsl/types.py +6453 -0
  134. elasticsearch9/dsl/update_by_query.py +19 -0
  135. elasticsearch9/dsl/update_by_query_base.py +149 -0
  136. elasticsearch9/dsl/utils.py +687 -0
  137. elasticsearch9/dsl/wrappers.py +144 -0
  138. elasticsearch9/exceptions.py +133 -0
  139. elasticsearch9/helpers/__init__.py +41 -0
  140. elasticsearch9/helpers/actions.py +875 -0
  141. elasticsearch9/helpers/errors.py +40 -0
  142. elasticsearch9/helpers/vectorstore/__init__.py +62 -0
  143. elasticsearch9/helpers/vectorstore/_async/__init__.py +16 -0
  144. elasticsearch9/helpers/vectorstore/_async/_utils.py +39 -0
  145. elasticsearch9/helpers/vectorstore/_async/embedding_service.py +89 -0
  146. elasticsearch9/helpers/vectorstore/_async/strategies.py +487 -0
  147. elasticsearch9/helpers/vectorstore/_async/vectorstore.py +421 -0
  148. elasticsearch9/helpers/vectorstore/_sync/__init__.py +16 -0
  149. elasticsearch9/helpers/vectorstore/_sync/_utils.py +39 -0
  150. elasticsearch9/helpers/vectorstore/_sync/embedding_service.py +89 -0
  151. elasticsearch9/helpers/vectorstore/_sync/strategies.py +487 -0
  152. elasticsearch9/helpers/vectorstore/_sync/vectorstore.py +421 -0
  153. elasticsearch9/helpers/vectorstore/_utils.py +116 -0
  154. elasticsearch9/py.typed +0 -0
  155. elasticsearch9/serializer.py +250 -0
  156. elasticsearch9-9.0.0.dist-info/METADATA +175 -0
  157. elasticsearch9-9.0.0.dist-info/RECORD +160 -0
  158. elasticsearch9-9.0.0.dist-info/WHEEL +4 -0
  159. elasticsearch9-9.0.0.dist-info/licenses/LICENSE +176 -0
  160. elasticsearch9-9.0.0.dist-info/licenses/NOTICE +2 -0
@@ -0,0 +1,421 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ import logging
19
+ import uuid
20
+ from typing import Any, Callable, Dict, List, Optional
21
+
22
+ from elasticsearch import Elasticsearch
23
+ from elasticsearch._version import __versionstr__ as lib_version
24
+ from elasticsearch.helpers import BulkIndexError, bulk
25
+ from elasticsearch.helpers.vectorstore import (
26
+ EmbeddingService,
27
+ RetrievalStrategy,
28
+ )
29
+ from elasticsearch.helpers.vectorstore._utils import maximal_marginal_relevance
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class VectorStore:
35
+ """
36
+ VectorStore is a higher-level abstraction of indexing and search.
37
+ Users can pick from available retrieval strategies.
38
+
39
+ Documents have up to 3 fields:
40
+ - text_field: the text to be indexed and searched.
41
+ - metadata: additional information about the document, either schema-free
42
+ or defined by the supplied metadata_mappings.
43
+ - vector_field (usually not filled by the user): the embedding vector of the text.
44
+
45
+ Depending on the strategy, vector embeddings are
46
+ - created by the user beforehand
47
+ - created by this AsyncVectorStore class in Python
48
+ - created in-stack by inference pipelines.
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ client: Elasticsearch,
54
+ *,
55
+ index: str,
56
+ retrieval_strategy: RetrievalStrategy,
57
+ embedding_service: Optional[EmbeddingService] = None,
58
+ num_dimensions: Optional[int] = None,
59
+ text_field: str = "text_field",
60
+ vector_field: str = "vector_field",
61
+ metadata_mappings: Optional[Dict[str, Any]] = None,
62
+ user_agent: str = f"elasticsearch-py-vs/{lib_version}",
63
+ custom_index_settings: Optional[Dict[str, Any]] = None,
64
+ ) -> None:
65
+ """
66
+ :param user_header: user agent header specific to the 3rd party integration.
67
+ Used for usage tracking in Elastic Cloud.
68
+ :param index: The name of the index to query.
69
+ :param retrieval_strategy: how to index and search the data. See the strategies
70
+ module for availble strategies.
71
+ :param text_field: Name of the field with the textual data.
72
+ :param vector_field: For strategies that perform embedding inference in Python,
73
+ the embedding vector goes in this field.
74
+ :param client: Elasticsearch client connection. Alternatively specify the
75
+ Elasticsearch connection with the other es_* parameters.
76
+ :param custom_index_settings: A dictionary of custom settings for the index.
77
+ This can include configurations like the number of shards, number of replicas,
78
+ analysis settings, and other index-specific settings. If not provided, default
79
+ settings will be used. Note that if the same setting is provided by both the user
80
+ and the strategy, will raise an error.
81
+ """
82
+ # Add integration-specific usage header for tracking usage in Elastic Cloud.
83
+ # client.options preserves existing (non-user-agent) headers.
84
+ client = client.options(headers={"User-Agent": user_agent})
85
+
86
+ if hasattr(retrieval_strategy, "text_field"):
87
+ retrieval_strategy.text_field = text_field
88
+ if hasattr(retrieval_strategy, "vector_field"):
89
+ retrieval_strategy.vector_field = vector_field
90
+
91
+ self.client = client
92
+ self.index = index
93
+ self.retrieval_strategy = retrieval_strategy
94
+ self.embedding_service = embedding_service
95
+ self.num_dimensions = num_dimensions
96
+ self.text_field = text_field
97
+ self.vector_field = vector_field
98
+ self.metadata_mappings = metadata_mappings
99
+ self.custom_index_settings = custom_index_settings
100
+
101
+ def close(self) -> None:
102
+ return self.client.close()
103
+
104
+ def add_texts(
105
+ self,
106
+ texts: List[str],
107
+ *,
108
+ metadatas: Optional[List[Dict[str, Any]]] = None,
109
+ vectors: Optional[List[List[float]]] = None,
110
+ ids: Optional[List[str]] = None,
111
+ refresh_indices: bool = True,
112
+ create_index_if_not_exists: bool = True,
113
+ bulk_kwargs: Optional[Dict[str, Any]] = None,
114
+ ) -> List[str]:
115
+ """Add documents to the Elasticsearch index.
116
+
117
+ :param texts: List of text documents.
118
+ :param metadata: Optional list of document metadata. Must be of same length as
119
+ texts.
120
+ :param vectors: Optional list of embedding vectors. Must be of same length as
121
+ texts.
122
+ :param ids: Optional list of ID strings. Must be of same length as texts.
123
+ :param refresh_indices: Whether to refresh the index after deleting documents.
124
+ Defaults to True.
125
+ :param create_index_if_not_exists: Whether to create the index if it does not
126
+ exist. Defaults to True.
127
+ :param bulk_kwargs: Arguments to pass to the bulk function when indexing
128
+ (for example chunk_size).
129
+
130
+ :return: List of IDs of the created documents, either echoing the provided one
131
+ or returning newly created ones.
132
+ """
133
+ bulk_kwargs = bulk_kwargs or {}
134
+ ids = ids or [str(uuid.uuid4()) for _ in texts]
135
+ requests = []
136
+
137
+ if create_index_if_not_exists:
138
+ self._create_index_if_not_exists()
139
+
140
+ if self.embedding_service and not vectors:
141
+ vectors = self.embedding_service.embed_documents(texts)
142
+
143
+ for i, text in enumerate(texts):
144
+ metadata = metadatas[i] if metadatas else {}
145
+
146
+ request: Dict[str, Any] = {
147
+ "_op_type": "index",
148
+ "_index": self.index,
149
+ self.text_field: text,
150
+ "metadata": metadata,
151
+ "_id": ids[i],
152
+ }
153
+
154
+ if vectors:
155
+ request[self.vector_field] = vectors[i]
156
+
157
+ requests.append(request)
158
+
159
+ if len(requests) > 0:
160
+ try:
161
+ success, failed = bulk(
162
+ self.client,
163
+ requests,
164
+ stats_only=True,
165
+ refresh=refresh_indices,
166
+ **bulk_kwargs,
167
+ )
168
+ logger.debug(f"added texts {ids} to index")
169
+ return ids
170
+ except BulkIndexError as e:
171
+ logger.error(f"Error adding texts: {e}")
172
+ firstError = e.errors[0].get("index", {}).get("error", {})
173
+ logger.error(f"First error reason: {firstError.get('reason')}")
174
+ raise e
175
+
176
+ else:
177
+ logger.debug("No texts to add to index")
178
+ return []
179
+
180
+ def delete( # type: ignore[no-untyped-def]
181
+ self,
182
+ *,
183
+ ids: Optional[List[str]] = None,
184
+ query: Optional[Dict[str, Any]] = None,
185
+ refresh_indices: bool = True,
186
+ **delete_kwargs,
187
+ ) -> bool:
188
+ """Delete documents from the Elasticsearch index.
189
+
190
+ :param ids: List of IDs of documents to delete.
191
+ :param refresh_indices: Whether to refresh the index after deleting documents.
192
+ Defaults to True.
193
+
194
+ :return: True if deletion was successful.
195
+ """
196
+ if ids is not None and query is not None:
197
+ raise ValueError("one of ids or query must be specified")
198
+ elif ids is None and query is None:
199
+ raise ValueError("either specify ids or query")
200
+
201
+ try:
202
+ if ids:
203
+ body = [
204
+ {"_op_type": "delete", "_index": self.index, "_id": _id}
205
+ for _id in ids
206
+ ]
207
+ bulk(
208
+ self.client,
209
+ body,
210
+ refresh=refresh_indices,
211
+ ignore_status=404,
212
+ **delete_kwargs,
213
+ )
214
+ logger.debug(f"Deleted {len(body)} texts from index")
215
+
216
+ else:
217
+ self.client.delete_by_query(
218
+ index=self.index,
219
+ query=query,
220
+ refresh=refresh_indices,
221
+ **delete_kwargs,
222
+ )
223
+
224
+ except BulkIndexError as e:
225
+ logger.error(f"Error deleting texts: {e}")
226
+ firstError = e.errors[0].get("index", {}).get("error", {})
227
+ logger.error(f"First error reason: {firstError.get('reason')}")
228
+ raise e
229
+
230
+ return True
231
+
232
+ def search(
233
+ self,
234
+ *,
235
+ query: Optional[str] = None,
236
+ query_vector: Optional[List[float]] = None,
237
+ k: int = 4,
238
+ num_candidates: int = 50,
239
+ fields: Optional[List[str]] = None,
240
+ filter: Optional[List[Dict[str, Any]]] = None,
241
+ custom_query: Optional[
242
+ Callable[[Dict[str, Any], Optional[str]], Dict[str, Any]]
243
+ ] = None,
244
+ ) -> List[Dict[str, Any]]:
245
+ """
246
+ :param query: Input query string.
247
+ :param query_vector: Input embedding vector. If given, input query string is
248
+ ignored.
249
+ :param k: Number of returned results.
250
+ :param num_candidates: Number of candidates to fetch from data nodes in knn.
251
+ :param fields: List of field names to return.
252
+ :param filter: Elasticsearch filters to apply.
253
+ :param custom_query: Function to modify the Elasticsearch query body before it is
254
+ sent to Elasticsearch.
255
+
256
+ :return: List of document hits. Includes _index, _id, _score and _source.
257
+ """
258
+ if fields is None:
259
+ fields = []
260
+ if "metadata" not in fields:
261
+ fields.append("metadata")
262
+ if self.text_field not in fields:
263
+ fields.append(self.text_field)
264
+
265
+ if self.embedding_service and not query_vector:
266
+ if not query:
267
+ raise ValueError("specify a query or a query_vector to search")
268
+ query_vector = self.embedding_service.embed_query(query)
269
+
270
+ query_body = self.retrieval_strategy.es_query(
271
+ query=query,
272
+ query_vector=query_vector,
273
+ text_field=self.text_field,
274
+ vector_field=self.vector_field,
275
+ k=k,
276
+ num_candidates=num_candidates,
277
+ filter=filter or [],
278
+ )
279
+
280
+ if custom_query is not None:
281
+ query_body = custom_query(query_body, query)
282
+ logger.debug(f"Calling custom_query, Query body now: {query_body}")
283
+
284
+ response = self.client.search(
285
+ index=self.index,
286
+ **query_body,
287
+ size=k,
288
+ source=True,
289
+ source_includes=fields,
290
+ )
291
+ hits: List[Dict[str, Any]] = response["hits"]["hits"]
292
+
293
+ return hits
294
+
295
+ def _create_index_if_not_exists(self) -> None:
296
+ exists = self.client.indices.exists(index=self.index)
297
+ if exists.meta.status == 200:
298
+ logger.debug(f"Index {self.index} already exists. Skipping creation.")
299
+ return
300
+
301
+ if self.retrieval_strategy.needs_inference():
302
+ if not self.num_dimensions and not self.embedding_service:
303
+ raise ValueError(
304
+ "retrieval strategy requires embeddings; either embedding_service "
305
+ "or num_dimensions need to be specified"
306
+ )
307
+ if not self.num_dimensions and self.embedding_service:
308
+ vector = self.embedding_service.embed_query("get num dimensions")
309
+ self.num_dimensions = len(vector)
310
+
311
+ mappings, settings = self.retrieval_strategy.es_mappings_settings(
312
+ text_field=self.text_field,
313
+ vector_field=self.vector_field,
314
+ num_dimensions=self.num_dimensions,
315
+ )
316
+
317
+ if self.custom_index_settings:
318
+ conflicting_keys = set(self.custom_index_settings.keys()) & set(
319
+ settings.keys()
320
+ )
321
+ if conflicting_keys:
322
+ raise ValueError(f"Conflicting settings: {conflicting_keys}")
323
+ else:
324
+ settings.update(self.custom_index_settings)
325
+
326
+ if self.metadata_mappings:
327
+ metadata = mappings["properties"].get("metadata", {"properties": {}})
328
+ for key in self.metadata_mappings.keys():
329
+ if key in metadata:
330
+ raise ValueError(f"metadata key {key} already exists in mappings")
331
+
332
+ metadata = dict(**metadata["properties"], **self.metadata_mappings)
333
+ mappings["properties"]["metadata"] = {"properties": metadata}
334
+
335
+ self.retrieval_strategy.before_index_creation(
336
+ client=self.client,
337
+ text_field=self.text_field,
338
+ vector_field=self.vector_field,
339
+ )
340
+ self.client.indices.create(
341
+ index=self.index, mappings=mappings, settings=settings
342
+ )
343
+
344
+ def max_marginal_relevance_search(
345
+ self,
346
+ *,
347
+ query: Optional[str] = None,
348
+ query_embedding: Optional[List[float]] = None,
349
+ embedding_service: Optional[EmbeddingService] = None,
350
+ vector_field: str,
351
+ k: int = 4,
352
+ num_candidates: int = 20,
353
+ lambda_mult: float = 0.5,
354
+ fields: Optional[List[str]] = None,
355
+ custom_query: Optional[
356
+ Callable[[Dict[str, Any], Optional[str]], Dict[str, Any]]
357
+ ] = None,
358
+ ) -> List[Dict[str, Any]]:
359
+ """Return docs selected using the maximal marginal relevance.
360
+
361
+ Maximal marginal relevance optimizes for similarity to query AND diversity
362
+ among selected documents.
363
+
364
+ :param query (str): Text to look up documents similar to.
365
+ :param query_embedding: Input embedding vector. If given, input query string is
366
+ ignored.
367
+ :param k (int): Number of Documents to return. Defaults to 4.
368
+ :param fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.
369
+ :param lambda_mult (float): Number between 0 and 1 that determines the degree
370
+ of diversity among the results with 0 corresponding
371
+ to maximum diversity and 1 to minimum diversity.
372
+ Defaults to 0.5.
373
+ :param fields: Other fields to get from elasticsearch source. These fields
374
+ will be added to the document metadata.
375
+
376
+ :return: A list of Documents selected by maximal marginal relevance.
377
+ """
378
+ remove_vector_query_field_from_metadata = True
379
+ if fields is None:
380
+ fields = [vector_field]
381
+ elif vector_field not in fields:
382
+ fields.append(vector_field)
383
+ else:
384
+ remove_vector_query_field_from_metadata = False
385
+
386
+ # Embed the query
387
+ if query_embedding:
388
+ query_vector = query_embedding
389
+ else:
390
+ if not query:
391
+ raise ValueError("specify either query or query_embedding to search")
392
+ elif embedding_service:
393
+ query_vector = embedding_service.embed_query(query)
394
+ elif self.embedding_service:
395
+ query_vector = self.embedding_service.embed_query(query)
396
+ else:
397
+ raise ValueError("specify embedding_service to search with query")
398
+
399
+ # Fetch the initial documents
400
+ got_hits = self.search(
401
+ query=None,
402
+ query_vector=query_vector,
403
+ k=num_candidates,
404
+ fields=fields,
405
+ custom_query=custom_query,
406
+ )
407
+
408
+ # Get the embeddings for the fetched documents
409
+ got_embeddings = [hit["_source"][vector_field] for hit in got_hits]
410
+
411
+ # Select documents using maximal marginal relevance
412
+ selected_indices = maximal_marginal_relevance(
413
+ query_vector, got_embeddings, lambda_mult=lambda_mult, k=k
414
+ )
415
+ selected_hits = [got_hits[i] for i in selected_indices]
416
+
417
+ if remove_vector_query_field_from_metadata:
418
+ for hit in selected_hits:
419
+ del hit["_source"][vector_field]
420
+
421
+ return selected_hits
@@ -0,0 +1,116 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ from enum import Enum
19
+ from typing import TYPE_CHECKING, List, Union
20
+
21
+ if TYPE_CHECKING:
22
+ import numpy as np
23
+ import numpy.typing as npt
24
+
25
+ Matrix = Union[
26
+ List[List[float]], List["npt.NDArray[np.float64]"], "npt.NDArray[np.float64]"
27
+ ]
28
+
29
+
30
+ class DistanceMetric(str, Enum):
31
+ """Enumerator of all Elasticsearch dense vector distance metrics."""
32
+
33
+ COSINE = "COSINE"
34
+ DOT_PRODUCT = "DOT_PRODUCT"
35
+ EUCLIDEAN_DISTANCE = "EUCLIDEAN_DISTANCE"
36
+ MAX_INNER_PRODUCT = "MAX_INNER_PRODUCT"
37
+
38
+
39
+ def maximal_marginal_relevance(
40
+ query_embedding: List[float],
41
+ embedding_list: List[List[float]],
42
+ lambda_mult: float = 0.5,
43
+ k: int = 4,
44
+ ) -> List[int]:
45
+ """Calculate maximal marginal relevance."""
46
+
47
+ try:
48
+ import numpy as np
49
+ except ModuleNotFoundError as e:
50
+ _raise_missing_mmr_deps_error(e)
51
+
52
+ query_embedding_arr = np.array(query_embedding)
53
+
54
+ if min(k, len(embedding_list)) <= 0:
55
+ return []
56
+ if query_embedding_arr.ndim == 1:
57
+ query_embedding_arr = np.expand_dims(query_embedding_arr, axis=0)
58
+ similarity_to_query = _cosine_similarity(query_embedding_arr, embedding_list)[0]
59
+ most_similar = int(np.argmax(similarity_to_query))
60
+ idxs = [most_similar]
61
+ selected = np.array([embedding_list[most_similar]])
62
+ while len(idxs) < min(k, len(embedding_list)):
63
+ best_score = -np.inf
64
+ idx_to_add = -1
65
+ similarity_to_selected = _cosine_similarity(embedding_list, selected)
66
+ for i, query_score in enumerate(similarity_to_query):
67
+ if i in idxs:
68
+ continue
69
+ redundant_score = max(similarity_to_selected[i])
70
+ equation_score = (
71
+ lambda_mult * query_score - (1 - lambda_mult) * redundant_score
72
+ )
73
+ if equation_score > best_score:
74
+ best_score = equation_score
75
+ idx_to_add = i
76
+ idxs.append(idx_to_add)
77
+ selected = np.append(selected, [embedding_list[idx_to_add]], axis=0)
78
+ return idxs
79
+
80
+
81
+ def _cosine_similarity(X: Matrix, Y: Matrix) -> "npt.NDArray[np.float64]":
82
+ """Row-wise cosine similarity between two equal-width matrices."""
83
+
84
+ try:
85
+ import numpy as np
86
+ import simsimd as simd
87
+ except ModuleNotFoundError as e:
88
+ _raise_missing_mmr_deps_error(e)
89
+
90
+ if len(X) == 0 or len(Y) == 0:
91
+ return np.array([])
92
+
93
+ X = np.array(X)
94
+ Y = np.array(Y)
95
+ if X.shape[1] != Y.shape[1]:
96
+ raise ValueError(
97
+ f"Number of columns in X and Y must be the same. X has shape {X.shape} "
98
+ f"and Y has shape {Y.shape}."
99
+ )
100
+
101
+ X = np.array(X, dtype=np.float32)
102
+ Y = np.array(Y, dtype=np.float32)
103
+ Z = 1 - np.array(simd.cdist(X, Y, metric="cosine"))
104
+ if isinstance(Z, float):
105
+ return np.array([Z])
106
+ return np.array(Z)
107
+
108
+
109
+ def _raise_missing_mmr_deps_error(parent_error: ModuleNotFoundError) -> None:
110
+ import sys
111
+
112
+ raise ModuleNotFoundError(
113
+ f"Failed to compute maximal marginal relevance because the required "
114
+ f"module '{parent_error.name}' is missing. You can install it by running: "
115
+ f"'{sys.executable} -m pip install elasticsearch[vectorstore_mmr]'"
116
+ ) from parent_error
File without changes