elasticsearch-haystack 0.3.0__py3-none-any.whl → 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of elasticsearch-haystack might be problematic. Click here for more details.
- {elasticsearch_haystack-0.3.0.dist-info → elasticsearch_haystack-0.5.0.dist-info}/METADATA +3 -2
- {elasticsearch_haystack-0.3.0.dist-info → elasticsearch_haystack-0.5.0.dist-info}/RECORD +7 -7
- {elasticsearch_haystack-0.3.0.dist-info → elasticsearch_haystack-0.5.0.dist-info}/WHEEL +1 -1
- haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py +30 -13
- haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py +51 -10
- haystack_integrations/document_stores/elasticsearch/document_store.py +127 -57
- {elasticsearch_haystack-0.3.0.dist-info → elasticsearch_haystack-0.5.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
2
|
Name: elasticsearch-haystack
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.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
|
|
@@ -9,6 +9,7 @@ Author-email: Silvano Cerza <silvanocerza@gmail.com>
|
|
|
9
9
|
License-Expression: Apache-2.0
|
|
10
10
|
License-File: LICENSE
|
|
11
11
|
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
13
|
Classifier: Programming Language :: Python
|
|
13
14
|
Classifier: Programming Language :: Python :: 3.8
|
|
14
15
|
Classifier: Programming Language :: Python :: 3.9
|
|
@@ -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=
|
|
3
|
-
haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=
|
|
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=
|
|
5
|
+
haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=XMbrn-dsRw0HS8mPMreGCO3cRQnwwU_UA3OzWb3pi_4,18304
|
|
6
6
|
haystack_integrations/document_stores/elasticsearch/filters.py,sha256=L1tN7YCIDuNdhGrBQdPoqXFk37x__2-K038xZ6PRdNQ,9923
|
|
7
|
-
elasticsearch_haystack-0.
|
|
8
|
-
elasticsearch_haystack-0.
|
|
9
|
-
elasticsearch_haystack-0.
|
|
10
|
-
elasticsearch_haystack-0.
|
|
7
|
+
elasticsearch_haystack-0.5.0.dist-info/METADATA,sha256=bKt2Am26Ey5iq0ZQw7JOeBSu_Em7-e9iDdl1eHqCt08,2168
|
|
8
|
+
elasticsearch_haystack-0.5.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
|
|
9
|
+
elasticsearch_haystack-0.5.0.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
|
|
10
|
+
elasticsearch_haystack-0.5.0.dist-info/RECORD,,
|
|
@@ -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
|
|
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.
|
|
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
|
|
57
|
-
:param fuzziness: Fuzziness parameter passed to Elasticsearch
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
:param top_k: Maximum number of Documents to return
|
|
61
|
-
:param scale_score: If `True` scales the Document`s scores between 0 and 1
|
|
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,6 +91,14 @@ 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
|
)
|
|
@@ -93,10 +109,11 @@ class ElasticsearchBM25Retriever:
|
|
|
93
109
|
"""
|
|
94
110
|
Retrieve documents using the BM25 keyword-based algorithm.
|
|
95
111
|
|
|
96
|
-
:param query: String to search in
|
|
97
|
-
:param filters: Filters applied to the retrieved
|
|
98
|
-
:param top_k: Maximum number of
|
|
99
|
-
:
|
|
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.
|
|
100
117
|
"""
|
|
101
118
|
docs = self._document_store._bm25_retrieval(
|
|
102
119
|
query=query,
|
|
@@ -11,9 +11,35 @@ from haystack_integrations.document_stores.elasticsearch.document_store import E
|
|
|
11
11
|
@component
|
|
12
12
|
class ElasticsearchEmbeddingRetriever:
|
|
13
13
|
"""
|
|
14
|
-
|
|
14
|
+
ElasticsearchEmbeddingRetriever retrieves documents from the ElasticsearchDocumentStore using vector similarity.
|
|
15
15
|
|
|
16
|
-
|
|
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.
|
|
32
|
-
Filters are applied during the approximate
|
|
33
|
-
:param top_k: Maximum number of Documents to return
|
|
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
|
|
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,6 +89,14 @@ 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
|
)
|
|
@@ -68,9 +108,10 @@ class ElasticsearchEmbeddingRetriever:
|
|
|
68
108
|
Retrieve documents using a vector similarity metric.
|
|
69
109
|
|
|
70
110
|
:param query_embedding: Embedding of the query.
|
|
71
|
-
:param filters: Filters applied to the retrieved
|
|
72
|
-
:param top_k: Maximum number of
|
|
73
|
-
:
|
|
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`
|
|
74
115
|
"""
|
|
75
116
|
docs = self._document_store._embedding_retrieval(
|
|
76
117
|
query_embedding=query_embedding,
|
|
@@ -35,16 +35,16 @@ BM25_SCALING_FACTOR = 8
|
|
|
35
35
|
|
|
36
36
|
class ElasticsearchDocumentStore:
|
|
37
37
|
"""
|
|
38
|
-
ElasticsearchDocumentStore is a Document Store for Elasticsearch.
|
|
39
|
-
|
|
38
|
+
ElasticsearchDocumentStore is a Document Store for Elasticsearch. It can be used with Elastic Cloud or your own
|
|
39
|
+
Elasticsearch cluster.
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
Usage example (Elastic Cloud):
|
|
42
42
|
```python
|
|
43
43
|
from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
|
|
44
44
|
document_store = ElasticsearchDocumentStore(cloud_id="YOUR_CLOUD_ID", api_key="YOUR_API_KEY")
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
Usage example (self-hosted Elasticsearch instance):
|
|
48
48
|
```python
|
|
49
49
|
from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
|
|
50
50
|
document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200")
|
|
@@ -53,8 +53,8 @@ class ElasticsearchDocumentStore:
|
|
|
53
53
|
We strongly recommend to enable security so that only authorized users can access your data.
|
|
54
54
|
|
|
55
55
|
For more details on how to connect to Elasticsearch and configure security,
|
|
56
|
-
see the official Elasticsearch
|
|
57
|
-
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)
|
|
58
58
|
|
|
59
59
|
All extra keyword arguments will be passed to the Elasticsearch client.
|
|
60
60
|
"""
|
|
@@ -63,32 +63,34 @@ class ElasticsearchDocumentStore:
|
|
|
63
63
|
self,
|
|
64
64
|
*,
|
|
65
65
|
hosts: Optional[Hosts] = None,
|
|
66
|
+
custom_mapping: Optional[Dict[str, Any]] = None,
|
|
66
67
|
index: str = "default",
|
|
67
68
|
embedding_similarity_function: Literal["cosine", "dot_product", "l2_norm", "max_inner_product"] = "cosine",
|
|
68
69
|
**kwargs,
|
|
69
70
|
):
|
|
70
71
|
"""
|
|
71
72
|
Creates a new ElasticsearchDocumentStore instance.
|
|
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
|
+
It will also try to create that index if it doesn't exist yet. Otherwise, it will use the existing one.
|
|
74
75
|
|
|
75
76
|
One can also set the similarity function used to compare Documents embeddings. This is mostly useful
|
|
76
77
|
when using the `ElasticsearchDocumentStore` in a Pipeline with an `ElasticsearchEmbeddingRetriever`.
|
|
77
78
|
|
|
78
|
-
For more information on connection parameters, see the official Elasticsearch
|
|
79
|
-
https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html
|
|
79
|
+
For more information on connection parameters, see the official Elasticsearch
|
|
80
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/connecting.html)
|
|
80
81
|
|
|
81
|
-
For the full list of supported kwargs, see the official Elasticsearch
|
|
82
|
-
https://elasticsearch-py.readthedocs.io/en/stable/api.html#module-elasticsearch
|
|
82
|
+
For the full list of supported kwargs, see the official Elasticsearch
|
|
83
|
+
[reference](https://elasticsearch-py.readthedocs.io/en/stable/api.html#module-elasticsearch)
|
|
83
84
|
|
|
84
|
-
:param hosts: List of hosts running the Elasticsearch client.
|
|
85
|
-
:param
|
|
85
|
+
:param hosts: List of hosts running the Elasticsearch client.
|
|
86
|
+
:param custom_mapping: Custom mapping for the index. If not provided, a default mapping will be used.
|
|
87
|
+
:param index: Name of index in Elasticsearch.
|
|
86
88
|
:param embedding_similarity_function: The similarity function used to compare Documents embeddings.
|
|
87
|
-
|
|
89
|
+
This parameter only takes effect if the index does not yet exist and is created.
|
|
88
90
|
To choose the most appropriate function, look for information about your embedding model.
|
|
89
|
-
To understand how document scores are computed, see the Elasticsearch
|
|
90
|
-
https://www.elastic.co/guide/en/elasticsearch/reference/current/dense-vector.html#dense-vector-params
|
|
91
|
-
:param **kwargs: Optional arguments that
|
|
91
|
+
To understand how document scores are computed, see the Elasticsearch
|
|
92
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/dense-vector.html#dense-vector-params)
|
|
93
|
+
:param **kwargs: Optional arguments that `Elasticsearch` takes.
|
|
92
94
|
"""
|
|
93
95
|
self._hosts = hosts
|
|
94
96
|
self._client = Elasticsearch(
|
|
@@ -98,29 +100,56 @@ class ElasticsearchDocumentStore:
|
|
|
98
100
|
)
|
|
99
101
|
self._index = index
|
|
100
102
|
self._embedding_similarity_function = embedding_similarity_function
|
|
103
|
+
self._custom_mapping = custom_mapping
|
|
101
104
|
self._kwargs = kwargs
|
|
102
105
|
|
|
103
106
|
# Check client connection, this will raise if not connected
|
|
104
107
|
self._client.info()
|
|
105
108
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
109
|
+
if self._custom_mapping and not isinstance(self._custom_mapping, Dict):
|
|
110
|
+
msg = "custom_mapping must be a dictionary"
|
|
111
|
+
raise ValueError(msg)
|
|
112
|
+
|
|
113
|
+
if self._custom_mapping:
|
|
114
|
+
mappings = self._custom_mapping
|
|
115
|
+
else:
|
|
116
|
+
# Configure mapping for the embedding field if none is provided
|
|
117
|
+
mappings = {
|
|
118
|
+
"properties": {
|
|
119
|
+
"embedding": {"type": "dense_vector", "index": True, "similarity": embedding_similarity_function},
|
|
120
|
+
"content": {"type": "text"},
|
|
121
|
+
},
|
|
122
|
+
"dynamic_templates": [
|
|
123
|
+
{
|
|
124
|
+
"strings": {
|
|
125
|
+
"path_match": "*",
|
|
126
|
+
"match_mapping_type": "string",
|
|
127
|
+
"mapping": {
|
|
128
|
+
"type": "keyword",
|
|
129
|
+
},
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
],
|
|
110
133
|
}
|
|
111
|
-
}
|
|
112
134
|
|
|
113
135
|
# Create the index if it doesn't exist
|
|
114
136
|
if not self._client.indices.exists(index=index):
|
|
115
137
|
self._client.indices.create(index=index, mappings=mappings)
|
|
116
138
|
|
|
117
139
|
def to_dict(self) -> Dict[str, Any]:
|
|
140
|
+
"""
|
|
141
|
+
Serializes the component to a dictionary.
|
|
142
|
+
|
|
143
|
+
:returns:
|
|
144
|
+
Dictionary with serialized data.
|
|
145
|
+
"""
|
|
118
146
|
# This is not the best solution to serialise this class but is the fastest to implement.
|
|
119
147
|
# Not all kwargs types can be serialised to text so this can fail. We must serialise each
|
|
120
148
|
# type explicitly to handle this properly.
|
|
121
149
|
return default_to_dict(
|
|
122
150
|
self,
|
|
123
151
|
hosts=self._hosts,
|
|
152
|
+
custom_mapping=self._custom_mapping,
|
|
124
153
|
index=self._index,
|
|
125
154
|
embedding_similarity_function=self._embedding_similarity_function,
|
|
126
155
|
**self._kwargs,
|
|
@@ -128,11 +157,20 @@ class ElasticsearchDocumentStore:
|
|
|
128
157
|
|
|
129
158
|
@classmethod
|
|
130
159
|
def from_dict(cls, data: Dict[str, Any]) -> "ElasticsearchDocumentStore":
|
|
160
|
+
"""
|
|
161
|
+
Deserializes the component from a dictionary.
|
|
162
|
+
|
|
163
|
+
:param data:
|
|
164
|
+
Dictionary to deserialize from.
|
|
165
|
+
:returns:
|
|
166
|
+
Deserialized component.
|
|
167
|
+
"""
|
|
131
168
|
return default_from_dict(cls, data)
|
|
132
169
|
|
|
133
170
|
def count_documents(self) -> int:
|
|
134
171
|
"""
|
|
135
172
|
Returns how many documents are present in the document store.
|
|
173
|
+
:returns: Number of documents in the document store.
|
|
136
174
|
"""
|
|
137
175
|
return self._client.count(index=self._index)["count"]
|
|
138
176
|
|
|
@@ -165,6 +203,14 @@ class ElasticsearchDocumentStore:
|
|
|
165
203
|
return documents
|
|
166
204
|
|
|
167
205
|
def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]:
|
|
206
|
+
"""
|
|
207
|
+
The main query method for the document store. It retrieves all documents that match the filters.
|
|
208
|
+
|
|
209
|
+
:param filters: A dictionary of filters to apply. For more information on the structure of the filters,
|
|
210
|
+
see the official Elasticsearch
|
|
211
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html)
|
|
212
|
+
:returns: List of `Document`s that match the filters.
|
|
213
|
+
"""
|
|
168
214
|
if filters and "operator" not in filters and "conditions" not in filters:
|
|
169
215
|
filters = convert(filters)
|
|
170
216
|
|
|
@@ -174,9 +220,15 @@ class ElasticsearchDocumentStore:
|
|
|
174
220
|
|
|
175
221
|
def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int:
|
|
176
222
|
"""
|
|
177
|
-
Writes
|
|
178
|
-
|
|
179
|
-
|
|
223
|
+
Writes `Document`s to Elasticsearch.
|
|
224
|
+
|
|
225
|
+
:param documents: List of Documents to write to the document store.
|
|
226
|
+
:param policy: DuplicatePolicy to apply when a document with the same ID already exists in the document store.
|
|
227
|
+
:raises ValueError: If `documents` is not a list of `Document`s.
|
|
228
|
+
:raises DuplicateDocumentError: If a document with the same ID already exists in the document store and
|
|
229
|
+
`policy` is set to `DuplicatePolicy.FAIL` or `DuplicatePolicy.NONE`.
|
|
230
|
+
:raises DocumentStoreError: If an error occurs while writing the documents to the document store.
|
|
231
|
+
:returns: Number of documents written to the document store.
|
|
180
232
|
"""
|
|
181
233
|
if len(documents) > 0:
|
|
182
234
|
if not isinstance(documents[0], Document):
|
|
@@ -187,16 +239,30 @@ class ElasticsearchDocumentStore:
|
|
|
187
239
|
policy = DuplicatePolicy.FAIL
|
|
188
240
|
|
|
189
241
|
action = "index" if policy == DuplicatePolicy.OVERWRITE else "create"
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
242
|
+
|
|
243
|
+
elasticsearch_actions = []
|
|
244
|
+
for doc in documents:
|
|
245
|
+
doc_dict = doc.to_dict()
|
|
246
|
+
if "sparse_embedding" in doc_dict:
|
|
247
|
+
sparse_embedding = doc_dict.pop("sparse_embedding", None)
|
|
248
|
+
if sparse_embedding:
|
|
249
|
+
logger.warning(
|
|
250
|
+
"Document %s has the `sparse_embedding` field set,"
|
|
251
|
+
"but storing sparse embeddings in Elasticsearch is not currently supported."
|
|
252
|
+
"The `sparse_embedding` field will be ignored.",
|
|
253
|
+
doc.id,
|
|
254
|
+
)
|
|
255
|
+
elasticsearch_actions.append(
|
|
193
256
|
{
|
|
194
257
|
"_op_type": action,
|
|
195
258
|
"_id": doc.id,
|
|
196
|
-
"_source":
|
|
259
|
+
"_source": doc_dict,
|
|
197
260
|
}
|
|
198
|
-
|
|
199
|
-
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
documents_written, errors = helpers.bulk(
|
|
264
|
+
client=self._client,
|
|
265
|
+
actions=elasticsearch_actions,
|
|
200
266
|
refresh="wait_for",
|
|
201
267
|
index=self._index,
|
|
202
268
|
raise_on_error=False,
|
|
@@ -225,10 +291,15 @@ class ElasticsearchDocumentStore:
|
|
|
225
291
|
|
|
226
292
|
return documents_written
|
|
227
293
|
|
|
228
|
-
|
|
294
|
+
@staticmethod
|
|
295
|
+
def _deserialize_document(hit: Dict[str, Any]) -> Document:
|
|
229
296
|
"""
|
|
230
|
-
Creates a Document from the search hit provided.
|
|
297
|
+
Creates a `Document` from the search hit provided.
|
|
298
|
+
|
|
231
299
|
This is mostly useful in self.filter_documents().
|
|
300
|
+
|
|
301
|
+
:param hit: A search hit from Elasticsearch.
|
|
302
|
+
:returns: `Document` created from the search hit.
|
|
232
303
|
"""
|
|
233
304
|
data = hit["_source"]
|
|
234
305
|
|
|
@@ -240,12 +311,11 @@ class ElasticsearchDocumentStore:
|
|
|
240
311
|
|
|
241
312
|
def delete_documents(self, document_ids: List[str]) -> None:
|
|
242
313
|
"""
|
|
243
|
-
Deletes all
|
|
314
|
+
Deletes all `Document`s with a matching `document_ids` from the document store.
|
|
244
315
|
|
|
245
|
-
:param
|
|
316
|
+
:param document_ids: the object IDs to delete
|
|
246
317
|
"""
|
|
247
318
|
|
|
248
|
-
#
|
|
249
319
|
helpers.bulk(
|
|
250
320
|
client=self._client,
|
|
251
321
|
actions=({"_op_type": "delete", "_id": id_} for id_ in document_ids),
|
|
@@ -264,26 +334,25 @@ class ElasticsearchDocumentStore:
|
|
|
264
334
|
scale_score: bool = False,
|
|
265
335
|
) -> List[Document]:
|
|
266
336
|
"""
|
|
267
|
-
Elasticsearch
|
|
337
|
+
Retrieves `Document`s from Elasticsearch using the BM25 search algorithm.
|
|
338
|
+
|
|
268
339
|
Even though this method is called `bm25_retrieval` it searches for `query`
|
|
269
340
|
using the search algorithm `_client` was configured with.
|
|
270
341
|
|
|
271
|
-
This method is not
|
|
342
|
+
This method is not meant to be part of the public interface of
|
|
272
343
|
`ElasticsearchDocumentStore` nor called directly.
|
|
273
344
|
`ElasticsearchBM25Retriever` uses this method directly and is the public interface for it.
|
|
274
345
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
:param
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
:param top_k: Maximum number of Documents to return, defaults to 10
|
|
284
|
-
:param scale_score: If `True` scales the Document`s scores between 0 and 1, defaults to False
|
|
346
|
+
:param query: String to search in saved `Document`s' text.
|
|
347
|
+
:param filters: Filters applied to the retrieved `Document`s, for more info
|
|
348
|
+
see `ElasticsearchDocumentStore.filter_documents`.
|
|
349
|
+
:param fuzziness: Fuzziness parameter passed to Elasticsearch. See the official
|
|
350
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness)
|
|
351
|
+
for valid values.
|
|
352
|
+
:param top_k: Maximum number of `Document`s to return.
|
|
353
|
+
:param scale_score: If `True` scales the `Document``s scores between 0 and 1.
|
|
285
354
|
:raises ValueError: If `query` is an empty string
|
|
286
|
-
:
|
|
355
|
+
:returns: List of `Document` that match `query`
|
|
287
356
|
"""
|
|
288
357
|
|
|
289
358
|
if not query:
|
|
@@ -329,22 +398,23 @@ class ElasticsearchDocumentStore:
|
|
|
329
398
|
) -> List[Document]:
|
|
330
399
|
"""
|
|
331
400
|
Retrieves documents that are most similar to the query embedding using a vector similarity metric.
|
|
401
|
+
|
|
332
402
|
It uses the Elasticsearch's Approximate k-Nearest Neighbors search algorithm.
|
|
333
403
|
|
|
334
|
-
This method is not
|
|
404
|
+
This method is not meant to be part of the public interface of
|
|
335
405
|
`ElasticsearchDocumentStore` nor called directly.
|
|
336
406
|
`ElasticsearchEmbeddingRetriever` uses this method directly and is the public interface for it.
|
|
337
407
|
|
|
338
408
|
:param query_embedding: Embedding of the query.
|
|
339
|
-
:param filters: Filters applied to the retrieved
|
|
409
|
+
:param filters: Filters applied to the retrieved `Document`s.
|
|
340
410
|
Filters are applied during the approximate kNN search to ensure that top_k matching documents are returned.
|
|
341
|
-
:param top_k: Maximum number of
|
|
411
|
+
:param top_k: Maximum number of `Document`s to return.
|
|
342
412
|
:param num_candidates: Number of approximate nearest neighbor candidates on each shard. Defaults to top_k * 10.
|
|
343
413
|
Increasing this value will improve search accuracy at the cost of slower search speeds.
|
|
344
|
-
You can read more about it in the Elasticsearch
|
|
345
|
-
https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy
|
|
346
|
-
:raises ValueError: If `query_embedding` is an empty list
|
|
347
|
-
:
|
|
414
|
+
You can read more about it in the Elasticsearch
|
|
415
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)
|
|
416
|
+
:raises ValueError: If `query_embedding` is an empty list.
|
|
417
|
+
:returns: List of `Document` that are most similar to `query_embedding`.
|
|
348
418
|
"""
|
|
349
419
|
|
|
350
420
|
if not query_embedding:
|
{elasticsearch_haystack-0.3.0.dist-info → elasticsearch_haystack-0.5.0.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|