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.
- elasticsearch9/__init__.py +98 -0
- elasticsearch9/_async/__init__.py +16 -0
- elasticsearch9/_async/client/__init__.py +6531 -0
- elasticsearch9/_async/client/_base.py +430 -0
- elasticsearch9/_async/client/async_search.py +637 -0
- elasticsearch9/_async/client/autoscaling.py +252 -0
- elasticsearch9/_async/client/cat.py +2995 -0
- elasticsearch9/_async/client/ccr.py +1043 -0
- elasticsearch9/_async/client/cluster.py +1223 -0
- elasticsearch9/_async/client/connector.py +1978 -0
- elasticsearch9/_async/client/dangling_indices.py +192 -0
- elasticsearch9/_async/client/enrich.py +291 -0
- elasticsearch9/_async/client/eql.py +359 -0
- elasticsearch9/_async/client/esql.py +490 -0
- elasticsearch9/_async/client/features.py +130 -0
- elasticsearch9/_async/client/fleet.py +658 -0
- elasticsearch9/_async/client/graph.py +113 -0
- elasticsearch9/_async/client/ilm.py +668 -0
- elasticsearch9/_async/client/indices.py +5582 -0
- elasticsearch9/_async/client/inference.py +2247 -0
- elasticsearch9/_async/client/ingest.py +766 -0
- elasticsearch9/_async/client/license.py +400 -0
- elasticsearch9/_async/client/logstash.py +176 -0
- elasticsearch9/_async/client/migration.py +160 -0
- elasticsearch9/_async/client/ml.py +5835 -0
- elasticsearch9/_async/client/monitoring.py +100 -0
- elasticsearch9/_async/client/nodes.py +543 -0
- elasticsearch9/_async/client/query_rules.py +485 -0
- elasticsearch9/_async/client/rollup.py +616 -0
- elasticsearch9/_async/client/search_application.py +574 -0
- elasticsearch9/_async/client/searchable_snapshots.py +313 -0
- elasticsearch9/_async/client/security.py +4688 -0
- elasticsearch9/_async/client/shutdown.py +268 -0
- elasticsearch9/_async/client/simulate.py +145 -0
- elasticsearch9/_async/client/slm.py +559 -0
- elasticsearch9/_async/client/snapshot.py +1338 -0
- elasticsearch9/_async/client/sql.py +469 -0
- elasticsearch9/_async/client/ssl.py +76 -0
- elasticsearch9/_async/client/synonyms.py +413 -0
- elasticsearch9/_async/client/tasks.py +295 -0
- elasticsearch9/_async/client/text_structure.py +664 -0
- elasticsearch9/_async/client/transform.py +922 -0
- elasticsearch9/_async/client/utils.py +48 -0
- elasticsearch9/_async/client/watcher.py +894 -0
- elasticsearch9/_async/client/xpack.py +134 -0
- elasticsearch9/_async/helpers.py +596 -0
- elasticsearch9/_otel.py +110 -0
- elasticsearch9/_sync/__init__.py +16 -0
- elasticsearch9/_sync/client/__init__.py +6529 -0
- elasticsearch9/_sync/client/_base.py +430 -0
- elasticsearch9/_sync/client/async_search.py +637 -0
- elasticsearch9/_sync/client/autoscaling.py +252 -0
- elasticsearch9/_sync/client/cat.py +2995 -0
- elasticsearch9/_sync/client/ccr.py +1043 -0
- elasticsearch9/_sync/client/cluster.py +1223 -0
- elasticsearch9/_sync/client/connector.py +1978 -0
- elasticsearch9/_sync/client/dangling_indices.py +192 -0
- elasticsearch9/_sync/client/enrich.py +291 -0
- elasticsearch9/_sync/client/eql.py +359 -0
- elasticsearch9/_sync/client/esql.py +490 -0
- elasticsearch9/_sync/client/features.py +130 -0
- elasticsearch9/_sync/client/fleet.py +658 -0
- elasticsearch9/_sync/client/graph.py +113 -0
- elasticsearch9/_sync/client/ilm.py +668 -0
- elasticsearch9/_sync/client/indices.py +5582 -0
- elasticsearch9/_sync/client/inference.py +2247 -0
- elasticsearch9/_sync/client/ingest.py +766 -0
- elasticsearch9/_sync/client/license.py +400 -0
- elasticsearch9/_sync/client/logstash.py +176 -0
- elasticsearch9/_sync/client/migration.py +160 -0
- elasticsearch9/_sync/client/ml.py +5835 -0
- elasticsearch9/_sync/client/monitoring.py +100 -0
- elasticsearch9/_sync/client/nodes.py +543 -0
- elasticsearch9/_sync/client/query_rules.py +485 -0
- elasticsearch9/_sync/client/rollup.py +616 -0
- elasticsearch9/_sync/client/search_application.py +574 -0
- elasticsearch9/_sync/client/searchable_snapshots.py +313 -0
- elasticsearch9/_sync/client/security.py +4688 -0
- elasticsearch9/_sync/client/shutdown.py +268 -0
- elasticsearch9/_sync/client/simulate.py +145 -0
- elasticsearch9/_sync/client/slm.py +559 -0
- elasticsearch9/_sync/client/snapshot.py +1338 -0
- elasticsearch9/_sync/client/sql.py +469 -0
- elasticsearch9/_sync/client/ssl.py +76 -0
- elasticsearch9/_sync/client/synonyms.py +413 -0
- elasticsearch9/_sync/client/tasks.py +295 -0
- elasticsearch9/_sync/client/text_structure.py +664 -0
- elasticsearch9/_sync/client/transform.py +922 -0
- elasticsearch9/_sync/client/utils.py +475 -0
- elasticsearch9/_sync/client/watcher.py +894 -0
- elasticsearch9/_sync/client/xpack.py +134 -0
- elasticsearch9/_utils.py +34 -0
- elasticsearch9/_version.py +18 -0
- elasticsearch9/client.py +126 -0
- elasticsearch9/compat.py +79 -0
- elasticsearch9/dsl/__init__.py +203 -0
- elasticsearch9/dsl/_async/__init__.py +16 -0
- elasticsearch9/dsl/_async/document.py +522 -0
- elasticsearch9/dsl/_async/faceted_search.py +50 -0
- elasticsearch9/dsl/_async/index.py +639 -0
- elasticsearch9/dsl/_async/mapping.py +49 -0
- elasticsearch9/dsl/_async/search.py +237 -0
- elasticsearch9/dsl/_async/update_by_query.py +47 -0
- elasticsearch9/dsl/_sync/__init__.py +16 -0
- elasticsearch9/dsl/_sync/document.py +514 -0
- elasticsearch9/dsl/_sync/faceted_search.py +50 -0
- elasticsearch9/dsl/_sync/index.py +597 -0
- elasticsearch9/dsl/_sync/mapping.py +49 -0
- elasticsearch9/dsl/_sync/search.py +230 -0
- elasticsearch9/dsl/_sync/update_by_query.py +45 -0
- elasticsearch9/dsl/aggs.py +3734 -0
- elasticsearch9/dsl/analysis.py +341 -0
- elasticsearch9/dsl/async_connections.py +37 -0
- elasticsearch9/dsl/connections.py +142 -0
- elasticsearch9/dsl/document.py +20 -0
- elasticsearch9/dsl/document_base.py +444 -0
- elasticsearch9/dsl/exceptions.py +32 -0
- elasticsearch9/dsl/faceted_search.py +28 -0
- elasticsearch9/dsl/faceted_search_base.py +489 -0
- elasticsearch9/dsl/field.py +4392 -0
- elasticsearch9/dsl/function.py +180 -0
- elasticsearch9/dsl/index.py +23 -0
- elasticsearch9/dsl/index_base.py +178 -0
- elasticsearch9/dsl/mapping.py +19 -0
- elasticsearch9/dsl/mapping_base.py +219 -0
- elasticsearch9/dsl/query.py +2822 -0
- elasticsearch9/dsl/response/__init__.py +388 -0
- elasticsearch9/dsl/response/aggs.py +100 -0
- elasticsearch9/dsl/response/hit.py +53 -0
- elasticsearch9/dsl/search.py +20 -0
- elasticsearch9/dsl/search_base.py +1053 -0
- elasticsearch9/dsl/serializer.py +34 -0
- elasticsearch9/dsl/types.py +6453 -0
- elasticsearch9/dsl/update_by_query.py +19 -0
- elasticsearch9/dsl/update_by_query_base.py +149 -0
- elasticsearch9/dsl/utils.py +687 -0
- elasticsearch9/dsl/wrappers.py +144 -0
- elasticsearch9/exceptions.py +133 -0
- elasticsearch9/helpers/__init__.py +41 -0
- elasticsearch9/helpers/actions.py +875 -0
- elasticsearch9/helpers/errors.py +40 -0
- elasticsearch9/helpers/vectorstore/__init__.py +62 -0
- elasticsearch9/helpers/vectorstore/_async/__init__.py +16 -0
- elasticsearch9/helpers/vectorstore/_async/_utils.py +39 -0
- elasticsearch9/helpers/vectorstore/_async/embedding_service.py +89 -0
- elasticsearch9/helpers/vectorstore/_async/strategies.py +487 -0
- elasticsearch9/helpers/vectorstore/_async/vectorstore.py +421 -0
- elasticsearch9/helpers/vectorstore/_sync/__init__.py +16 -0
- elasticsearch9/helpers/vectorstore/_sync/_utils.py +39 -0
- elasticsearch9/helpers/vectorstore/_sync/embedding_service.py +89 -0
- elasticsearch9/helpers/vectorstore/_sync/strategies.py +487 -0
- elasticsearch9/helpers/vectorstore/_sync/vectorstore.py +421 -0
- elasticsearch9/helpers/vectorstore/_utils.py +116 -0
- elasticsearch9/py.typed +0 -0
- elasticsearch9/serializer.py +250 -0
- elasticsearch9-9.0.0.dist-info/METADATA +175 -0
- elasticsearch9-9.0.0.dist-info/RECORD +160 -0
- elasticsearch9-9.0.0.dist-info/WHEEL +4 -0
- elasticsearch9-9.0.0.dist-info/licenses/LICENSE +176 -0
- 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 AsyncElasticsearch
|
|
23
|
+
from elasticsearch._version import __versionstr__ as lib_version
|
|
24
|
+
from elasticsearch.helpers import BulkIndexError, async_bulk
|
|
25
|
+
from elasticsearch.helpers.vectorstore import (
|
|
26
|
+
AsyncEmbeddingService,
|
|
27
|
+
AsyncRetrievalStrategy,
|
|
28
|
+
)
|
|
29
|
+
from elasticsearch.helpers.vectorstore._utils import maximal_marginal_relevance
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AsyncVectorStore:
|
|
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: AsyncElasticsearch,
|
|
54
|
+
*,
|
|
55
|
+
index: str,
|
|
56
|
+
retrieval_strategy: AsyncRetrievalStrategy,
|
|
57
|
+
embedding_service: Optional[AsyncEmbeddingService] = 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
|
+
async def close(self) -> None:
|
|
102
|
+
return await self.client.close()
|
|
103
|
+
|
|
104
|
+
async 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
|
+
await self._create_index_if_not_exists()
|
|
139
|
+
|
|
140
|
+
if self.embedding_service and not vectors:
|
|
141
|
+
vectors = await 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 = await async_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
|
+
async 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
|
+
await async_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
|
+
await 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
|
+
async 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 = await 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 = await 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
|
+
async def _create_index_if_not_exists(self) -> None:
|
|
296
|
+
exists = await 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 = await 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
|
+
await self.retrieval_strategy.before_index_creation(
|
|
336
|
+
client=self.client,
|
|
337
|
+
text_field=self.text_field,
|
|
338
|
+
vector_field=self.vector_field,
|
|
339
|
+
)
|
|
340
|
+
await self.client.indices.create(
|
|
341
|
+
index=self.index, mappings=mappings, settings=settings
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
async def max_marginal_relevance_search(
|
|
345
|
+
self,
|
|
346
|
+
*,
|
|
347
|
+
query: Optional[str] = None,
|
|
348
|
+
query_embedding: Optional[List[float]] = None,
|
|
349
|
+
embedding_service: Optional[AsyncEmbeddingService] = 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 = await embedding_service.embed_query(query)
|
|
394
|
+
elif self.embedding_service:
|
|
395
|
+
query_vector = await 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 = await 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,16 @@
|
|
|
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.
|
|
@@ -0,0 +1,39 @@
|
|
|
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 elasticsearch import BadRequestError, Elasticsearch, NotFoundError
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def model_must_be_deployed(client: Elasticsearch, model_id: str) -> None:
|
|
22
|
+
"""
|
|
23
|
+
:raises [NotFoundError]: if the model is neither downloaded nor deployed.
|
|
24
|
+
:raises [ConflictError]: if the model is downloaded but not yet deployed.
|
|
25
|
+
"""
|
|
26
|
+
doc = {"text_field": f"test if the model '{model_id}' is deployed"}
|
|
27
|
+
try:
|
|
28
|
+
client.ml.infer_trained_model(model_id=model_id, docs=[doc])
|
|
29
|
+
except BadRequestError:
|
|
30
|
+
# The model is deployed but expects a different input field name.
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def model_is_deployed(client: Elasticsearch, model_id: str) -> bool:
|
|
35
|
+
try:
|
|
36
|
+
model_must_be_deployed(client, model_id)
|
|
37
|
+
return True
|
|
38
|
+
except NotFoundError:
|
|
39
|
+
return False
|
|
@@ -0,0 +1,89 @@
|
|
|
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 abc import ABC, abstractmethod
|
|
19
|
+
from typing import List
|
|
20
|
+
|
|
21
|
+
from elasticsearch import Elasticsearch
|
|
22
|
+
from elasticsearch._version import __versionstr__ as lib_version
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class EmbeddingService(ABC):
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
28
|
+
"""Generate embeddings for a list of documents.
|
|
29
|
+
|
|
30
|
+
:param texts: A list of document strings to generate embeddings for.
|
|
31
|
+
|
|
32
|
+
:return: A list of embeddings, one for each document in the input.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def embed_query(self, query: str) -> List[float]:
|
|
37
|
+
"""Generate an embedding for a single query text.
|
|
38
|
+
|
|
39
|
+
:param text: The query text to generate an embedding for.
|
|
40
|
+
|
|
41
|
+
:return: The embedding for the input query text.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ElasticsearchEmbeddings(EmbeddingService):
|
|
46
|
+
"""Elasticsearch as a service for embedding model inference.
|
|
47
|
+
|
|
48
|
+
You need to have an embedding model downloaded and deployed in Elasticsearch:
|
|
49
|
+
- https://www.elastic.co/guide/en/elasticsearch/reference/current/infer-trained-model.html
|
|
50
|
+
- https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-deploy-models.html
|
|
51
|
+
""" # noqa: E501
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
*,
|
|
56
|
+
client: Elasticsearch,
|
|
57
|
+
model_id: str,
|
|
58
|
+
input_field: str = "text_field",
|
|
59
|
+
user_agent: str = f"elasticsearch-py-es/{lib_version}",
|
|
60
|
+
):
|
|
61
|
+
"""
|
|
62
|
+
:param agent_header: user agent header specific to the 3rd party integration.
|
|
63
|
+
Used for usage tracking in Elastic Cloud.
|
|
64
|
+
:param model_id: The model_id of the model deployed in the Elasticsearch cluster.
|
|
65
|
+
:param input_field: The name of the key for the input text field in the
|
|
66
|
+
document. Defaults to 'text_field'.
|
|
67
|
+
:param client: Elasticsearch client connection. Alternatively specify the
|
|
68
|
+
Elasticsearch connection with the other es_* parameters.
|
|
69
|
+
"""
|
|
70
|
+
# Add integration-specific usage header for tracking usage in Elastic Cloud.
|
|
71
|
+
# client.options preserves existing (non-user-agent) headers.
|
|
72
|
+
client = client.options(headers={"User-Agent": user_agent})
|
|
73
|
+
|
|
74
|
+
self.client = client
|
|
75
|
+
self.model_id = model_id
|
|
76
|
+
self.input_field = input_field
|
|
77
|
+
|
|
78
|
+
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
79
|
+
return self._embedding_func(texts)
|
|
80
|
+
|
|
81
|
+
def embed_query(self, text: str) -> List[float]:
|
|
82
|
+
result = self._embedding_func([text])
|
|
83
|
+
return result[0]
|
|
84
|
+
|
|
85
|
+
def _embedding_func(self, texts: List[str]) -> List[List[float]]:
|
|
86
|
+
response = self.client.ml.infer_trained_model(
|
|
87
|
+
model_id=self.model_id, docs=[{self.input_field: text} for text in texts]
|
|
88
|
+
)
|
|
89
|
+
return [doc["predicted_value"] for doc in response["inference_results"]]
|