elasticsearch-haystack 5.1.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.
- elasticsearch_haystack-5.1.0.dist-info/METADATA +41 -0
- elasticsearch_haystack-5.1.0.dist-info/RECORD +12 -0
- elasticsearch_haystack-5.1.0.dist-info/WHEEL +4 -0
- elasticsearch_haystack-5.1.0.dist-info/licenses/LICENSE +201 -0
- haystack_integrations/components/retrievers/elasticsearch/__init__.py +7 -0
- haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py +166 -0
- haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py +164 -0
- haystack_integrations/components/retrievers/py.typed +0 -0
- haystack_integrations/document_stores/elasticsearch/__init__.py +6 -0
- haystack_integrations/document_stores/elasticsearch/document_store.py +1477 -0
- haystack_integrations/document_stores/elasticsearch/filters.py +246 -0
- haystack_integrations/document_stores/py.typed +0 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: elasticsearch-haystack
|
|
3
|
+
Version: 5.1.0
|
|
4
|
+
Summary: Haystack 2.x Document Store for ElasticSearch
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/elasticsearch#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/elasticsearch
|
|
8
|
+
Author-email: Silvano Cerza <silvanocerza@gmail.com>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: aiohttp>=3.9.0
|
|
22
|
+
Requires-Dist: elasticsearch<9,>=8
|
|
23
|
+
Requires-Dist: haystack-ai>=2.22.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# elasticsearch-haystack
|
|
27
|
+
|
|
28
|
+
[](https://pypi.org/project/elasticsearch-haystack)
|
|
29
|
+
[](https://pypi.org/project/elasticsearch-haystack)
|
|
30
|
+
|
|
31
|
+
- [Integration page](https://haystack.deepset.ai/integrations/elasticsearch-document-store)
|
|
32
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/elasticsearch/CHANGELOG.md)
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Contributing
|
|
37
|
+
|
|
38
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
39
|
+
|
|
40
|
+
To run integration tests locally, you need a Docker container running ElasticSearch.
|
|
41
|
+
Use the provided `docker-compose.yml` file to start the container: `docker compose up -d`.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
haystack_integrations/components/retrievers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
haystack_integrations/components/retrievers/elasticsearch/__init__.py,sha256=cSJBsYjz_T4kK-M-auAHVUnYIcgUqqwwQe_hsF0_IG4,307
|
|
3
|
+
haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py,sha256=ErMEQjzgg3-I2J8zOM_kDV0Y8UWtfqNHm89_vV-fOSo,7048
|
|
4
|
+
haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py,sha256=gz5BnSG0u7QimzKJWDYVvrkURMGXnGv4gldyJFTAk5U,7351
|
|
5
|
+
haystack_integrations/document_stores/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
haystack_integrations/document_stores/elasticsearch/__init__.py,sha256=YTfu94dtVUBogbJFr1aJrKuaI6-Bw9VuHfPoyU7M8os,207
|
|
7
|
+
haystack_integrations/document_stores/elasticsearch/document_store.py,sha256=Wzn5kpcag2p75ySN788Uql9Q00RWj1CRXWmmmnuMLNU,65683
|
|
8
|
+
haystack_integrations/document_stores/elasticsearch/filters.py,sha256=UmQ9zbITweR1QQnVbRKCbH46Dcdrj2rhMO90ll_sHT0,9747
|
|
9
|
+
elasticsearch_haystack-5.1.0.dist-info/METADATA,sha256=VKvwAgwRGEqE3vUWFAskVqf9yMQuBQNeMvvRdyZF_D0,2057
|
|
10
|
+
elasticsearch_haystack-5.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
11
|
+
elasticsearch_haystack-5.1.0.dist-info/licenses/LICENSE,sha256=_M2kulivnaiTHiW-5CRlZrPmH47tt04pBgAgeDvfYi4,11342
|
|
12
|
+
elasticsearch_haystack-5.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2023 deepset GmbH
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
from .bm25_retriever import ElasticsearchBM25Retriever
|
|
5
|
+
from .embedding_retriever import ElasticsearchEmbeddingRetriever
|
|
6
|
+
|
|
7
|
+
__all__ = ["ElasticsearchBM25Retriever", "ElasticsearchEmbeddingRetriever"]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from haystack import component, default_from_dict, default_to_dict
|
|
7
|
+
from haystack.dataclasses import Document
|
|
8
|
+
from haystack.document_stores.types import FilterPolicy
|
|
9
|
+
from haystack.document_stores.types.filter_policy import apply_filter_policy
|
|
10
|
+
|
|
11
|
+
from haystack_integrations.document_stores.elasticsearch.document_store import ElasticsearchDocumentStore
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@component
|
|
15
|
+
class ElasticsearchBM25Retriever:
|
|
16
|
+
"""
|
|
17
|
+
ElasticsearchBM25Retriever retrieves documents from the ElasticsearchDocumentStore using BM25 algorithm to find the
|
|
18
|
+
most similar documents to a user's query.
|
|
19
|
+
|
|
20
|
+
This retriever is only compatible with ElasticsearchDocumentStore.
|
|
21
|
+
|
|
22
|
+
Usage example:
|
|
23
|
+
```python
|
|
24
|
+
from haystack import Document
|
|
25
|
+
from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore
|
|
26
|
+
from haystack_integrations.components.retrievers.elasticsearch import ElasticsearchBM25Retriever
|
|
27
|
+
|
|
28
|
+
document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200")
|
|
29
|
+
retriever = ElasticsearchBM25Retriever(document_store=document_store)
|
|
30
|
+
|
|
31
|
+
# Add documents to DocumentStore
|
|
32
|
+
documents = [
|
|
33
|
+
Document(text="My name is Carla and I live in Berlin"),
|
|
34
|
+
Document(text="My name is Paul and I live in New York"),
|
|
35
|
+
Document(text="My name is Silvano and I live in Matera"),
|
|
36
|
+
Document(text="My name is Usagi Tsukino and I live in Tokyo"),
|
|
37
|
+
]
|
|
38
|
+
document_store.write_documents(documents)
|
|
39
|
+
|
|
40
|
+
result = retriever.run(query="Who lives in Berlin?")
|
|
41
|
+
for doc in result["documents"]:
|
|
42
|
+
print(doc.content)
|
|
43
|
+
```
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
*,
|
|
49
|
+
document_store: ElasticsearchDocumentStore,
|
|
50
|
+
filters: dict[str, Any] | None = None,
|
|
51
|
+
fuzziness: str = "AUTO",
|
|
52
|
+
top_k: int = 10,
|
|
53
|
+
scale_score: bool = False,
|
|
54
|
+
filter_policy: str | FilterPolicy = FilterPolicy.REPLACE,
|
|
55
|
+
):
|
|
56
|
+
"""
|
|
57
|
+
Initialize ElasticsearchBM25Retriever with an instance ElasticsearchDocumentStore.
|
|
58
|
+
|
|
59
|
+
:param document_store: An instance of ElasticsearchDocumentStore.
|
|
60
|
+
:param filters: Filters applied to the retrieved Documents, for more info
|
|
61
|
+
see `ElasticsearchDocumentStore.filter_documents`.
|
|
62
|
+
:param fuzziness: Fuzziness parameter passed to Elasticsearch. See the official
|
|
63
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness)
|
|
64
|
+
for more details.
|
|
65
|
+
:param top_k: Maximum number of Documents to return.
|
|
66
|
+
:param scale_score: If `True` scales the Document`s scores between 0 and 1.
|
|
67
|
+
:param filter_policy: Policy to determine how filters are applied.
|
|
68
|
+
:raises ValueError: If `document_store` is not an instance of `ElasticsearchDocumentStore`.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
if not isinstance(document_store, ElasticsearchDocumentStore):
|
|
72
|
+
msg = "document_store must be an instance of ElasticsearchDocumentStore"
|
|
73
|
+
raise ValueError(msg)
|
|
74
|
+
|
|
75
|
+
self._document_store = document_store
|
|
76
|
+
self._filters = filters or {}
|
|
77
|
+
self._fuzziness = fuzziness
|
|
78
|
+
self._top_k = top_k
|
|
79
|
+
self._scale_score = scale_score
|
|
80
|
+
self._filter_policy = FilterPolicy.from_str(filter_policy) if isinstance(filter_policy, str) else filter_policy
|
|
81
|
+
|
|
82
|
+
def to_dict(self) -> dict[str, Any]:
|
|
83
|
+
"""
|
|
84
|
+
Serializes the component to a dictionary.
|
|
85
|
+
|
|
86
|
+
:returns:
|
|
87
|
+
Dictionary with serialized data.
|
|
88
|
+
"""
|
|
89
|
+
return default_to_dict(
|
|
90
|
+
self,
|
|
91
|
+
filters=self._filters,
|
|
92
|
+
fuzziness=self._fuzziness,
|
|
93
|
+
top_k=self._top_k,
|
|
94
|
+
scale_score=self._scale_score,
|
|
95
|
+
filter_policy=self._filter_policy.value,
|
|
96
|
+
document_store=self._document_store.to_dict(),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
@classmethod
|
|
100
|
+
def from_dict(cls, data: dict[str, Any]) -> "ElasticsearchBM25Retriever":
|
|
101
|
+
"""
|
|
102
|
+
Deserializes the component from a dictionary.
|
|
103
|
+
|
|
104
|
+
:param data:
|
|
105
|
+
Dictionary to deserialize from.
|
|
106
|
+
:returns:
|
|
107
|
+
Deserialized component.
|
|
108
|
+
"""
|
|
109
|
+
data["init_parameters"]["document_store"] = ElasticsearchDocumentStore.from_dict(
|
|
110
|
+
data["init_parameters"]["document_store"]
|
|
111
|
+
)
|
|
112
|
+
# Pipelines serialized with old versions of the component might not
|
|
113
|
+
# have the filter_policy field.
|
|
114
|
+
if filter_policy := data["init_parameters"].get("filter_policy"):
|
|
115
|
+
data["init_parameters"]["filter_policy"] = FilterPolicy.from_str(filter_policy)
|
|
116
|
+
return default_from_dict(cls, data)
|
|
117
|
+
|
|
118
|
+
@component.output_types(documents=list[Document])
|
|
119
|
+
def run(
|
|
120
|
+
self, query: str, filters: dict[str, Any] | None = None, top_k: int | None = None
|
|
121
|
+
) -> dict[str, list[Document]]:
|
|
122
|
+
"""
|
|
123
|
+
Retrieve documents using the BM25 keyword-based algorithm.
|
|
124
|
+
|
|
125
|
+
:param query: String to search in the `Document`s text.
|
|
126
|
+
:param filters: Filters applied to the retrieved Documents. The way runtime filters are applied depends on
|
|
127
|
+
the `filter_policy` chosen at retriever initialization. See init method docstring for more
|
|
128
|
+
details.
|
|
129
|
+
:param top_k: Maximum number of `Document` to return.
|
|
130
|
+
:returns: A dictionary with the following keys:
|
|
131
|
+
- `documents`: List of `Document`s that match the query.
|
|
132
|
+
"""
|
|
133
|
+
filters = apply_filter_policy(self._filter_policy, self._filters, filters)
|
|
134
|
+
docs = self._document_store._bm25_retrieval(
|
|
135
|
+
query=query,
|
|
136
|
+
filters=filters,
|
|
137
|
+
fuzziness=self._fuzziness,
|
|
138
|
+
top_k=top_k or self._top_k,
|
|
139
|
+
scale_score=self._scale_score,
|
|
140
|
+
)
|
|
141
|
+
return {"documents": docs}
|
|
142
|
+
|
|
143
|
+
@component.output_types(documents=list[Document])
|
|
144
|
+
async def run_async(
|
|
145
|
+
self, query: str, filters: dict[str, Any] | None = None, top_k: int | None = None
|
|
146
|
+
) -> dict[str, list[Document]]:
|
|
147
|
+
"""
|
|
148
|
+
Asynchronously retrieve documents using the BM25 keyword-based algorithm.
|
|
149
|
+
|
|
150
|
+
:param query: String to search in the `Document` text.
|
|
151
|
+
:param filters: Filters applied to the retrieved Documents. The way runtime filters are applied depends on
|
|
152
|
+
the `filter_policy` chosen at retriever initialization. See init method docstring for more
|
|
153
|
+
details.
|
|
154
|
+
:param top_k: Maximum number of `Document` to return.
|
|
155
|
+
:returns: A dictionary with the following keys:
|
|
156
|
+
- `documents`: List of `Document`s that match the query.
|
|
157
|
+
"""
|
|
158
|
+
filters = apply_filter_policy(self._filter_policy, self._filters, filters)
|
|
159
|
+
docs = await self._document_store._bm25_retrieval_async(
|
|
160
|
+
query=query,
|
|
161
|
+
filters=filters,
|
|
162
|
+
fuzziness=self._fuzziness,
|
|
163
|
+
top_k=top_k or self._top_k,
|
|
164
|
+
scale_score=self._scale_score,
|
|
165
|
+
)
|
|
166
|
+
return {"documents": docs}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from haystack import component, default_from_dict, default_to_dict
|
|
7
|
+
from haystack.dataclasses import Document
|
|
8
|
+
from haystack.document_stores.types import FilterPolicy
|
|
9
|
+
from haystack.document_stores.types.filter_policy import apply_filter_policy
|
|
10
|
+
|
|
11
|
+
from haystack_integrations.document_stores.elasticsearch.document_store import ElasticsearchDocumentStore
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@component
|
|
15
|
+
class ElasticsearchEmbeddingRetriever:
|
|
16
|
+
"""
|
|
17
|
+
ElasticsearchEmbeddingRetriever retrieves documents from the ElasticsearchDocumentStore using vector similarity.
|
|
18
|
+
|
|
19
|
+
Usage example:
|
|
20
|
+
```python
|
|
21
|
+
from haystack import Document
|
|
22
|
+
from haystack.components.embedders import SentenceTransformersTextEmbedder
|
|
23
|
+
from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore
|
|
24
|
+
from haystack_integrations.components.retrievers.elasticsearch import ElasticsearchEmbeddingRetriever
|
|
25
|
+
|
|
26
|
+
document_store = ElasticsearchDocumentStore(hosts="http://localhost:9200")
|
|
27
|
+
retriever = ElasticsearchEmbeddingRetriever(document_store=document_store)
|
|
28
|
+
|
|
29
|
+
# Add documents to DocumentStore
|
|
30
|
+
documents = [
|
|
31
|
+
Document(text="My name is Carla and I live in Berlin"),
|
|
32
|
+
Document(text="My name is Paul and I live in New York"),
|
|
33
|
+
Document(text="My name is Silvano and I live in Matera"),
|
|
34
|
+
Document(text="My name is Usagi Tsukino and I live in Tokyo"),
|
|
35
|
+
]
|
|
36
|
+
document_store.write_documents(documents)
|
|
37
|
+
|
|
38
|
+
te = SentenceTransformersTextEmbedder()
|
|
39
|
+
te.warm_up()
|
|
40
|
+
query_embeddings = te.run("Who lives in Berlin?")["embedding"]
|
|
41
|
+
|
|
42
|
+
result = retriever.run(query=query_embeddings)
|
|
43
|
+
for doc in result["documents"]:
|
|
44
|
+
print(doc.content)
|
|
45
|
+
```
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
*,
|
|
51
|
+
document_store: ElasticsearchDocumentStore,
|
|
52
|
+
filters: dict[str, Any] | None = None,
|
|
53
|
+
top_k: int = 10,
|
|
54
|
+
num_candidates: int | None = None,
|
|
55
|
+
filter_policy: str | FilterPolicy = FilterPolicy.REPLACE,
|
|
56
|
+
):
|
|
57
|
+
"""
|
|
58
|
+
Create the ElasticsearchEmbeddingRetriever component.
|
|
59
|
+
|
|
60
|
+
:param document_store: An instance of ElasticsearchDocumentStore.
|
|
61
|
+
:param filters: Filters applied to the retrieved Documents.
|
|
62
|
+
Filters are applied during the approximate KNN search to ensure that top_k matching documents are returned.
|
|
63
|
+
:param top_k: Maximum number of Documents to return.
|
|
64
|
+
:param num_candidates: Number of approximate nearest neighbor candidates on each shard. Defaults to top_k * 10.
|
|
65
|
+
Increasing this value will improve search accuracy at the cost of slower search speeds.
|
|
66
|
+
You can read more about it in the Elasticsearch
|
|
67
|
+
[documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)
|
|
68
|
+
:param filter_policy: Policy to determine how filters are applied.
|
|
69
|
+
:raises ValueError: If `document_store` is not an instance of ElasticsearchDocumentStore.
|
|
70
|
+
"""
|
|
71
|
+
if not isinstance(document_store, ElasticsearchDocumentStore):
|
|
72
|
+
msg = "document_store must be an instance of ElasticsearchDocumentStore"
|
|
73
|
+
raise ValueError(msg)
|
|
74
|
+
|
|
75
|
+
self._document_store = document_store
|
|
76
|
+
self._filters = filters or {}
|
|
77
|
+
self._top_k = top_k
|
|
78
|
+
self._num_candidates = num_candidates
|
|
79
|
+
self._filter_policy = FilterPolicy.from_str(filter_policy) if isinstance(filter_policy, str) else filter_policy
|
|
80
|
+
|
|
81
|
+
def to_dict(self) -> dict[str, Any]:
|
|
82
|
+
"""
|
|
83
|
+
Serializes the component to a dictionary.
|
|
84
|
+
|
|
85
|
+
:returns:
|
|
86
|
+
Dictionary with serialized data.
|
|
87
|
+
"""
|
|
88
|
+
return default_to_dict(
|
|
89
|
+
self,
|
|
90
|
+
filters=self._filters,
|
|
91
|
+
top_k=self._top_k,
|
|
92
|
+
num_candidates=self._num_candidates,
|
|
93
|
+
filter_policy=self._filter_policy.value,
|
|
94
|
+
document_store=self._document_store.to_dict(),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def from_dict(cls, data: dict[str, Any]) -> "ElasticsearchEmbeddingRetriever":
|
|
99
|
+
"""
|
|
100
|
+
Deserializes the component from a dictionary.
|
|
101
|
+
|
|
102
|
+
:param data:
|
|
103
|
+
Dictionary to deserialize from.
|
|
104
|
+
:returns:
|
|
105
|
+
Deserialized component.
|
|
106
|
+
"""
|
|
107
|
+
data["init_parameters"]["document_store"] = ElasticsearchDocumentStore.from_dict(
|
|
108
|
+
data["init_parameters"]["document_store"]
|
|
109
|
+
)
|
|
110
|
+
# Pipelines serialized with old versions of the component might not
|
|
111
|
+
# have the filter_policy field.
|
|
112
|
+
if filter_policy := data["init_parameters"].get("filter_policy"):
|
|
113
|
+
data["init_parameters"]["filter_policy"] = FilterPolicy.from_str(filter_policy)
|
|
114
|
+
return default_from_dict(cls, data)
|
|
115
|
+
|
|
116
|
+
@component.output_types(documents=list[Document])
|
|
117
|
+
def run(
|
|
118
|
+
self, query_embedding: list[float], filters: dict[str, Any] | None = None, top_k: int | None = None
|
|
119
|
+
) -> dict[str, list[Document]]:
|
|
120
|
+
"""
|
|
121
|
+
Retrieve documents using a vector similarity metric.
|
|
122
|
+
|
|
123
|
+
:param query_embedding: Embedding of the query.
|
|
124
|
+
:param filters: Filters applied when fetching documents from the Document Store.
|
|
125
|
+
Filters are applied during the approximate kNN search to ensure the Retriever returns
|
|
126
|
+
`top_k` matching documents.
|
|
127
|
+
The way runtime filters are applied depends on the `filter_policy` selected when initializing the Retriever.
|
|
128
|
+
:param top_k: Maximum number of documents to return.
|
|
129
|
+
:returns: A dictionary with the following keys:
|
|
130
|
+
- `documents`: List of `Document`s most similar to the given `query_embedding`
|
|
131
|
+
"""
|
|
132
|
+
filters = apply_filter_policy(self._filter_policy, self._filters, filters)
|
|
133
|
+
docs = self._document_store._embedding_retrieval(
|
|
134
|
+
query_embedding=query_embedding,
|
|
135
|
+
filters=filters,
|
|
136
|
+
top_k=top_k or self._top_k,
|
|
137
|
+
num_candidates=self._num_candidates,
|
|
138
|
+
)
|
|
139
|
+
return {"documents": docs}
|
|
140
|
+
|
|
141
|
+
@component.output_types(documents=list[Document])
|
|
142
|
+
async def run_async(
|
|
143
|
+
self, query_embedding: list[float], filters: dict[str, Any] | None = None, top_k: int | None = None
|
|
144
|
+
) -> dict[str, list[Document]]:
|
|
145
|
+
"""
|
|
146
|
+
Asynchronously retrieve documents using a vector similarity metric.
|
|
147
|
+
|
|
148
|
+
:param query_embedding: Embedding of the query.
|
|
149
|
+
:param filters: Filters applied when fetching documents from the Document Store.
|
|
150
|
+
Filters are applied during the approximate kNN search to ensure the Retriever returns
|
|
151
|
+
`top_k` matching documents.
|
|
152
|
+
The way runtime filters are applied depends on the `filter_policy` selected when initializing the Retriever.
|
|
153
|
+
:param top_k: Maximum number of documents to return.
|
|
154
|
+
:returns: A dictionary with the following keys:
|
|
155
|
+
- `documents`: List of `Document`s that match the query.
|
|
156
|
+
"""
|
|
157
|
+
filters = apply_filter_policy(self._filter_policy, self._filters, filters)
|
|
158
|
+
docs = await self._document_store._embedding_retrieval_async(
|
|
159
|
+
query_embedding=query_embedding,
|
|
160
|
+
filters=filters,
|
|
161
|
+
top_k=top_k or self._top_k,
|
|
162
|
+
num_candidates=self._num_candidates,
|
|
163
|
+
)
|
|
164
|
+
return {"documents": docs}
|
|
File without changes
|