arangodb-haystack 1.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.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: arangodb-haystack
3
+ Version: 1.0.0
4
+ Summary: Haystack integration for arangodb
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/arangodb#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/arangodb
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: arangodb,document-store,haystack,llm,rag,vector-search
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: haystack-ai
24
+ Requires-Dist: python-arango>=8.0.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ # arangodb-haystack
28
+
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/arangodb-haystack.svg)](https://pypi.org/project/arangodb-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/arangodb-haystack.svg)](https://pypi.org/project/arangodb-haystack)
31
+
32
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/arangodb/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 ArangoDB. Use the provided `docker-compose.yml` file to start the container: `docker compose up -d`.
@@ -0,0 +1,11 @@
1
+ haystack_integrations/components/retrievers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/retrievers/arangodb/__init__.py,sha256=mSbwLeMVNwjwqUYGdKUi18dkNhoOqpXIIgwCArMBI1A,261
3
+ haystack_integrations/components/retrievers/arangodb/embedding_retriever.py,sha256=SE7xm1Mjx3NTM_wutEJZnkYTKgv789FsNfcU2xSWLRE,3667
4
+ haystack_integrations/document_stores/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ haystack_integrations/document_stores/arangodb/__init__.py,sha256=jL_VQoXqdP33_1WD5tN9eAykDM4I0vaGkkInTPO7o3k,240
6
+ haystack_integrations/document_stores/arangodb/document_store.py,sha256=qUctFBPP-skCaGZgCJ1IKeAGdztQI5bo18JiA12-xDs,13749
7
+ haystack_integrations/document_stores/arangodb/filters.py,sha256=rGd31XfHMfRNH1mTLw-Wf7VMllMzdLy_uzIzSvztr-Y,3983
8
+ arangodb_haystack-1.0.0.dist-info/METADATA,sha256=RUq0Tkf_KemAL-JtmJPGTUDEteaQ_mqlHEuebWAFSOg,1979
9
+ arangodb_haystack-1.0.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
10
+ arangodb_haystack-1.0.0.dist-info/licenses/LICENSE.txt,sha256=OrAtTu4aPmrTjKDSTzkSPgo_ji6NOMWO2N9JOTFyAzM,11350
11
+ arangodb_haystack-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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-present 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
+
5
+ from haystack_integrations.components.retrievers.arangodb.embedding_retriever import ArangoEmbeddingRetriever
6
+
7
+ __all__ = ["ArangoEmbeddingRetriever"]
@@ -0,0 +1,102 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack import component, default_from_dict, default_to_dict
8
+ from haystack.dataclasses import Document
9
+
10
+ from haystack_integrations.document_stores.arangodb.document_store import ArangoDocumentStore
11
+
12
+
13
+ @component
14
+ class ArangoEmbeddingRetriever:
15
+ """
16
+ Retrieves documents from an `ArangoDocumentStore` using vector similarity on embeddings.
17
+
18
+ The similarity function is configured on the `ArangoDocumentStore` (cosine, dot product, or L2).
19
+
20
+ Example usage:
21
+
22
+ ```python
23
+ from haystack_integrations.document_stores.arangodb import ArangoDocumentStore
24
+ from haystack_integrations.components.retrievers.arangodb import ArangoEmbeddingRetriever
25
+
26
+ store = ArangoDocumentStore(host="http://localhost:8529", database="haystack",
27
+ username="root", collection_name="docs", embedding_dimension=768)
28
+ retriever = ArangoEmbeddingRetriever(document_store=store, top_k=5)
29
+ result = retriever.run(query_embedding=[0.1, 0.2, ...])
30
+ ```
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ *,
36
+ document_store: ArangoDocumentStore,
37
+ top_k: int = 10,
38
+ filters: dict[str, Any] | None = None,
39
+ ) -> None:
40
+ """
41
+ Creates a new ArangoEmbeddingRetriever.
42
+
43
+ :param document_store: The `ArangoDocumentStore` to retrieve documents from.
44
+ :param top_k: Maximum number of documents to return.
45
+ :param filters: Optional Haystack metadata filters applied at retrieval time.
46
+ """
47
+ if not isinstance(document_store, ArangoDocumentStore):
48
+ msg = f"document_store must be an ArangoDocumentStore, got {type(document_store)}"
49
+ raise ValueError(msg)
50
+ self.document_store = document_store
51
+ self.top_k = top_k
52
+ self.filters = filters
53
+
54
+ @component.output_types(documents=list[Document])
55
+ def run(
56
+ self,
57
+ query_embedding: list[float],
58
+ top_k: int | None = None,
59
+ filters: dict[str, Any] | None = None,
60
+ ) -> dict[str, list[Document]]:
61
+ """
62
+ Retrieves documents most similar to `query_embedding`.
63
+
64
+ :param query_embedding: The query vector.
65
+ :param top_k: Overrides the instance-level `top_k` for this call.
66
+ :param filters: Overrides the instance-level `filters` for this call.
67
+ :returns: A dictionary with `documents` — a list of `Document` objects sorted by score.
68
+ """
69
+ top_k = top_k if top_k is not None else self.top_k
70
+ filters = filters if filters is not None else self.filters
71
+ docs = self.document_store._embedding_retrieval(
72
+ query_embedding=query_embedding,
73
+ top_k=top_k,
74
+ filters=filters,
75
+ )
76
+ return {"documents": docs}
77
+
78
+ def to_dict(self) -> dict[str, Any]:
79
+ """
80
+ Serializes the component to a dictionary.
81
+
82
+ :returns: Dictionary with serialized data.
83
+ """
84
+ return default_to_dict(
85
+ self,
86
+ document_store=self.document_store.to_dict(),
87
+ top_k=self.top_k,
88
+ filters=self.filters,
89
+ )
90
+
91
+ @classmethod
92
+ def from_dict(cls, data: dict[str, Any]) -> "ArangoEmbeddingRetriever":
93
+ """
94
+ Deserializes the component from a dictionary.
95
+
96
+ :param data: Dictionary to deserialize from.
97
+ :returns: Deserialized component.
98
+ """
99
+ data["init_parameters"]["document_store"] = ArangoDocumentStore.from_dict(
100
+ data["init_parameters"]["document_store"]
101
+ )
102
+ return default_from_dict(cls, data)
File without changes
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from haystack_integrations.document_stores.arangodb.document_store import ArangoDocumentStore
6
+
7
+ __all__ = ["ArangoDocumentStore"]
@@ -0,0 +1,350 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import dataclasses
6
+ from typing import Any, Literal, cast
7
+
8
+ from arango import ArangoClient
9
+ from arango.collection import StandardCollection
10
+ from arango.cursor import Cursor
11
+ from arango.database import StandardDatabase
12
+ from haystack import default_from_dict, default_to_dict, logging
13
+ from haystack.dataclasses import Document
14
+ from haystack.document_stores.errors import DuplicateDocumentError
15
+ from haystack.document_stores.types import DuplicatePolicy
16
+ from haystack.utils.auth import Secret, deserialize_secrets_inplace
17
+
18
+ from .filters import _convert_filters
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Maps the configured similarity function to the AQL vector function, its sort order,
23
+ # and the metric name used when creating the vector index.
24
+ _SIMILARITY_AQL: dict[str, tuple[str, str, str]] = {
25
+ "cosine": ("APPROX_NEAR_COSINE", "DESC", "cosine"),
26
+ "dot_product": ("APPROX_NEAR_INNER_PRODUCT", "DESC", "innerProduct"),
27
+ "l2": ("APPROX_NEAR_L2", "ASC", "l2"),
28
+ }
29
+
30
+ _VECTOR_INDEX_NAME = "haystack_vector_index"
31
+
32
+
33
+ def _doc_to_arango(doc: Document) -> dict[str, Any]:
34
+ d = doc.to_dict(flatten=False)
35
+ d["_key"] = d.pop("id")
36
+ return d
37
+
38
+
39
+ def _arango_to_doc(record: dict[str, Any]) -> Document:
40
+ record = dict(record)
41
+ record["id"] = record.pop("_key")
42
+ record.pop("_id", None)
43
+ record.pop("_rev", None)
44
+ return Document.from_dict(record)
45
+
46
+
47
+ class ArangoDocumentStore:
48
+ """
49
+ A Haystack DocumentStore backed by [ArangoDB](https://www.arangodb.com/).
50
+
51
+ Documents are stored in an ArangoDB collection and support vector similarity search
52
+ via AQL vector functions (requires ArangoDB 3.12+).
53
+
54
+ Example usage:
55
+
56
+ ```python
57
+ from haystack_integrations.document_stores.arangodb import ArangoDocumentStore
58
+ from haystack.utils import Secret
59
+
60
+ store = ArangoDocumentStore(
61
+ host="http://localhost:8529",
62
+ database="haystack",
63
+ username=Secret.from_env_var("ARANGO_USERNAME", strict=False),
64
+ password=Secret.from_env_var("ARANGO_PASSWORD"),
65
+ collection_name="documents",
66
+ embedding_dimension=768,
67
+ )
68
+ ```
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ *,
74
+ host: str = "http://localhost:8529",
75
+ database: str = "haystack",
76
+ username: Secret = Secret.from_env_var("ARANGO_USERNAME", strict=False),
77
+ password: Secret = Secret.from_env_var("ARANGO_PASSWORD"),
78
+ collection_name: str = "haystack_documents",
79
+ embedding_dimension: int = 768,
80
+ recreate_collection: bool = False,
81
+ similarity_function: Literal["cosine", "dot_product", "l2"] = "cosine",
82
+ ) -> None:
83
+ """
84
+ Creates a new ArangoDocumentStore instance.
85
+
86
+ :param host: ArangoDB server URL, e.g. `http://localhost:8529`.
87
+ :param database: Name of the ArangoDB database to use. Created if it does not exist.
88
+ :param username: ArangoDB username as a `Secret`. Defaults to `ARANGO_USERNAME` env var,
89
+ falling back to `root` if the variable is not set.
90
+ :param password: ArangoDB password as a `Secret`. Defaults to `ARANGO_PASSWORD` env var.
91
+ :param collection_name: Name of the collection to store documents in.
92
+ :param embedding_dimension: Dimensionality of document embeddings.
93
+ :param recreate_collection: If `True`, drop and recreate the collection on startup.
94
+ :param similarity_function: Vector similarity function to use for embedding retrieval.
95
+ One of `"cosine"` (default), `"dot_product"`, or `"l2"`.
96
+ """
97
+ self.host = host
98
+ self.database = database
99
+ self.username = username
100
+ self.password = password
101
+ self.collection_name = collection_name
102
+ self.embedding_dimension = embedding_dimension
103
+ self.recreate_collection = recreate_collection
104
+ self.similarity_function = similarity_function
105
+ self._db: StandardDatabase | None = None
106
+ self._col: StandardCollection | None = None
107
+
108
+ def _ensure_connected(self) -> None:
109
+ if self._db is not None and self._col is not None:
110
+ return
111
+ username = self.username.resolve_value() or "root"
112
+ pwd = self.password.resolve_value() or ""
113
+ client = ArangoClient(hosts=self.host)
114
+ sys_db = client.db("_system", username=username, password=pwd)
115
+ if not sys_db.has_database(self.database):
116
+ sys_db.create_database(self.database)
117
+ db = client.db(self.database, username=username, password=pwd)
118
+ if self.recreate_collection and db.has_collection(self.collection_name):
119
+ db.delete_collection(self.collection_name)
120
+ if not db.has_collection(self.collection_name):
121
+ db.create_collection(self.collection_name)
122
+ self._db = db
123
+ self._col = db.collection(self.collection_name)
124
+
125
+ def _ensure_vector_index(self) -> None:
126
+ """
127
+ Lazily creates the FAISS vector index used by the `APPROX_NEAR_*` functions.
128
+
129
+ The index is created on first retrieval rather than at write time because ArangoDB
130
+ requires the collection to already contain training documents with non-null embeddings,
131
+ and `nLists` must be `<=` the number of such documents. We use `nLists=1`, which
132
+ probes the single Voronoi cell (a full scan) and therefore returns exact, complete results.
133
+
134
+ If a vector index already exists on the `embedding` field, its `metric` and `dimension`
135
+ must match this store's configuration; otherwise a `ValueError` is raised, since an
136
+ incompatible index would make `APPROX_NEAR_*` fail or silently return wrong results.
137
+
138
+ :raises ValueError: If an incompatible vector index already exists on the collection.
139
+ """
140
+ col = cast(StandardCollection, self._col)
141
+ _, _, metric = _SIMILARITY_AQL[self.similarity_function]
142
+ existing = cast("list[dict[str, Any]]", col.indexes())
143
+ for index in existing:
144
+ if index.get("type") != "vector" or index.get("fields") != ["embedding"]:
145
+ continue
146
+ params = index.get("params") or {}
147
+ if params.get("metric") == metric and params.get("dimension") == self.embedding_dimension:
148
+ return
149
+ msg = (
150
+ f"Collection '{self.collection_name}' already has a vector index on 'embedding' "
151
+ f"with metric={params.get('metric')!r} and dimension={params.get('dimension')}, "
152
+ f"which is incompatible with this store's configuration "
153
+ f"(metric={metric!r}, dimension={self.embedding_dimension}). "
154
+ f"Use a different collection or set recreate_collection=True to rebuild it."
155
+ )
156
+ raise ValueError(msg)
157
+ col.add_index(
158
+ {
159
+ "type": "vector",
160
+ "name": _VECTOR_INDEX_NAME,
161
+ "fields": ["embedding"],
162
+ "params": {
163
+ "metric": metric,
164
+ "dimension": self.embedding_dimension,
165
+ "nLists": 1,
166
+ },
167
+ }
168
+ )
169
+
170
+ def count_documents(self) -> int:
171
+ """
172
+ Returns the number of documents in the store.
173
+
174
+ :returns: Document count.
175
+ """
176
+ self._ensure_connected()
177
+ return cast(int, cast(StandardCollection, self._col).count())
178
+
179
+ def filter_documents(self, filters: dict[str, Any] | None = None) -> list[Document]:
180
+ """
181
+ Returns documents matching the provided filters.
182
+
183
+ :param filters: Haystack metadata filters. If `None`, all documents are returned.
184
+ :returns: List of matching `Document` objects.
185
+ """
186
+ self._ensure_connected()
187
+ db = cast(StandardDatabase, self._db)
188
+
189
+ aql = f"FOR doc IN {self.collection_name}"
190
+ bind_vars: dict[str, Any] = {}
191
+
192
+ if filters:
193
+ expr, bind_vars = _convert_filters(filters)
194
+ aql += f" FILTER {expr}"
195
+
196
+ aql += " RETURN doc"
197
+
198
+ cursor = cast(Cursor, db.aql.execute(aql, bind_vars=bind_vars))
199
+ return [_arango_to_doc(r) for r in cursor]
200
+
201
+ def write_documents(self, documents: list[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int:
202
+ """
203
+ Writes documents to the store.
204
+
205
+ :param documents: Documents to write.
206
+ :param policy: How to handle duplicates — `OVERWRITE`, `SKIP`, or `FAIL` (default).
207
+ :raises ValueError: If `documents` contains non-`Document` objects.
208
+ :raises DuplicateDocumentError: If a duplicate is found and policy is `FAIL`.
209
+ :returns: Number of documents written.
210
+ """
211
+ if not documents:
212
+ return 0
213
+ if not isinstance(documents[0], Document):
214
+ msg = "param 'documents' must contain a list of objects of type Document"
215
+ raise ValueError(msg)
216
+
217
+ if policy == DuplicatePolicy.NONE:
218
+ policy = DuplicatePolicy.FAIL
219
+
220
+ self._ensure_connected()
221
+ col = cast(StandardCollection, self._col)
222
+
223
+ arango_docs = [_doc_to_arango(doc) for doc in documents]
224
+ overwrite = policy == DuplicatePolicy.OVERWRITE
225
+ raw = col.insert_many(arango_docs, overwrite=overwrite, silent=False)
226
+ results = raw if isinstance(raw, list) else []
227
+
228
+ written = 0
229
+ for i, result in enumerate(results):
230
+ if isinstance(result, Exception):
231
+ if policy == DuplicatePolicy.FAIL:
232
+ msg = f"Document with id '{documents[i].id}' already exists."
233
+ raise DuplicateDocumentError(msg)
234
+ # SKIP: just move on
235
+ else:
236
+ written += 1
237
+
238
+ return written
239
+
240
+ def delete_documents(self, document_ids: list[str]) -> None:
241
+ """
242
+ Deletes documents by their IDs.
243
+
244
+ :param document_ids: List of document IDs to delete.
245
+ """
246
+ if not document_ids:
247
+ return
248
+ self._ensure_connected()
249
+ col = cast(StandardCollection, self._col)
250
+ col.delete_many([{"_key": doc_id} for doc_id in document_ids])
251
+
252
+ def _embedding_retrieval(
253
+ self,
254
+ query_embedding: list[float],
255
+ *,
256
+ top_k: int = 10,
257
+ filters: dict[str, Any] | None = None,
258
+ ) -> list[Document]:
259
+ """
260
+ Retrieves documents most similar to the query embedding using cosine similarity.
261
+
262
+ This method is used internally by `ArangoEmbeddingRetriever`.
263
+
264
+ :param query_embedding: The query vector.
265
+ :param top_k: Number of top results to return.
266
+ :param filters: Optional metadata filters.
267
+ :returns: List of `Document` objects sorted by descending similarity score.
268
+ """
269
+ if not query_embedding:
270
+ msg = "query_embedding must be a non-empty list of floats"
271
+ raise ValueError(msg)
272
+
273
+ self._ensure_connected()
274
+ db = cast(StandardDatabase, self._db)
275
+ col = cast(StandardCollection, self._col)
276
+ doc_count = col.count()
277
+ if doc_count == 0:
278
+ return []
279
+
280
+ self._ensure_vector_index()
281
+
282
+ aql_func, sort_order, _ = _SIMILARITY_AQL[self.similarity_function]
283
+ bind_vars: dict[str, Any] = {"query_vec": query_embedding, "top_k": top_k}
284
+
285
+ # ArangoDB only uses the vector index when the `APPROX_NEAR_*` call is followed
286
+ # directly by `SORT` + `LIMIT` with no preceding `FILTER`. Metadata filters are
287
+ # therefore applied *after* the vector search.
288
+ if filters:
289
+ expr, fvars = _convert_filters(filters)
290
+ bind_vars.update(fvars)
291
+ bind_vars["candidates"] = doc_count
292
+ aql = f"""
293
+ FOR doc IN (
294
+ FOR d IN {self.collection_name}
295
+ LET score = {aql_func}(d.embedding, @query_vec)
296
+ SORT score {sort_order}
297
+ LIMIT @candidates
298
+ RETURN MERGE(d, {{score: score}})
299
+ )
300
+ FILTER {expr}
301
+ LIMIT @top_k
302
+ RETURN doc
303
+ """
304
+ else:
305
+ aql = f"""
306
+ FOR doc IN {self.collection_name}
307
+ LET score = {aql_func}(doc.embedding, @query_vec)
308
+ SORT score {sort_order}
309
+ LIMIT @top_k
310
+ RETURN MERGE(doc, {{score: score}})
311
+ """
312
+
313
+ cursor = cast(Cursor, db.aql.execute(aql, bind_vars=bind_vars))
314
+ docs = []
315
+ for record in cursor:
316
+ score = record.pop("score", None)
317
+ d = _arango_to_doc(record)
318
+ if score is not None:
319
+ d = dataclasses.replace(d, score=score)
320
+ docs.append(d)
321
+ return docs
322
+
323
+ def to_dict(self) -> dict[str, Any]:
324
+ """
325
+ Serializes the component to a dictionary.
326
+
327
+ :returns: Dictionary with serialized data.
328
+ """
329
+ return default_to_dict(
330
+ self,
331
+ host=self.host,
332
+ database=self.database,
333
+ username=self.username.to_dict(),
334
+ password=self.password.to_dict(),
335
+ collection_name=self.collection_name,
336
+ embedding_dimension=self.embedding_dimension,
337
+ recreate_collection=self.recreate_collection,
338
+ similarity_function=self.similarity_function,
339
+ )
340
+
341
+ @classmethod
342
+ def from_dict(cls, data: dict[str, Any]) -> "ArangoDocumentStore":
343
+ """
344
+ Deserializes the component from a dictionary.
345
+
346
+ :param data: Dictionary to deserialize from.
347
+ :returns: Deserialized component.
348
+ """
349
+ deserialize_secrets_inplace(data["init_parameters"], ["password", "username"])
350
+ return default_from_dict(cls, data)
@@ -0,0 +1,128 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from datetime import datetime
6
+ from typing import Any
7
+
8
+ from haystack.errors import FilterError
9
+
10
+
11
+ def _is_iso_date(value: str) -> bool:
12
+ try:
13
+ datetime.fromisoformat(value)
14
+ return True
15
+ except ValueError:
16
+ return False
17
+
18
+
19
+ def _field_to_aql(field: str) -> str:
20
+ """Maps a Haystack field name to an AQL document field reference."""
21
+ if field == "id":
22
+ return "doc._key"
23
+ if field == "content":
24
+ return "doc.content"
25
+ if field == "embedding":
26
+ return "doc.embedding"
27
+ if field.startswith("meta."):
28
+ key = field[5:]
29
+ return f"doc.meta.`{key}`"
30
+ return f"doc.`{field}`"
31
+
32
+
33
+ def _convert_filters(filters: dict[str, Any]) -> tuple[str, dict[str, Any]]:
34
+ """
35
+ Converts a Haystack filter dict to an AQL FILTER expression and bind vars.
36
+
37
+ :param filters: Haystack filter dict.
38
+ :returns: Tuple of (aql_filter_string, bind_vars).
39
+ """
40
+ bind_vars: dict[str, Any] = {}
41
+ expr = _parse_filter(filters, bind_vars, counter=[0])
42
+ return expr, bind_vars
43
+
44
+
45
+ def _parse_filter(node: dict[str, Any], bind_vars: dict[str, Any], counter: list[int]) -> str:
46
+ if "operator" in node and "conditions" in node:
47
+ op = node["operator"].upper()
48
+ parts = [_parse_filter(c, bind_vars, counter) for c in node["conditions"]]
49
+ if op == "NOT":
50
+ inner = " AND ".join(parts)
51
+ return f"(NOT ({inner}))"
52
+ joiner = " AND " if op == "AND" else " OR "
53
+ inner = joiner.join(parts)
54
+ return f"({inner})"
55
+
56
+ if "field" in node and "operator" in node and "value" in node:
57
+ return _parse_comparison(node, bind_vars, counter)
58
+
59
+ if "NOT" in node:
60
+ inner = _parse_filter(node["NOT"], bind_vars, counter)
61
+ return f"(NOT {inner})"
62
+
63
+ msg = f"Unsupported filter structure: {node}"
64
+ raise FilterError(msg)
65
+
66
+
67
+ _COMPARISON_OPS = {">", ">=", "<", "<="}
68
+
69
+
70
+ def _parse_comparison(node: dict[str, Any], bind_vars: dict[str, Any], counter: list[int]) -> str:
71
+ field = _field_to_aql(node["field"])
72
+ op = node["operator"]
73
+ value = node["value"]
74
+
75
+ if op in _COMPARISON_OPS:
76
+ if value is None:
77
+ return "false"
78
+ if isinstance(value, list):
79
+ msg = f"Filter operator '{op}' does not support list values."
80
+ raise FilterError(msg)
81
+ if isinstance(value, str) and not _is_iso_date(value):
82
+ msg = f"Filter operator '{op}' does not support non-date string values."
83
+ raise FilterError(msg)
84
+ idx = counter[0]
85
+ counter[0] += 1
86
+ var = f"fv{idx}"
87
+ bind_vars[var] = value
88
+ return f"({field} != null AND {field} {op} @{var})"
89
+
90
+ if op == "==":
91
+ if value is None:
92
+ idx = counter[0]
93
+ counter[0] += 1
94
+ var = f"fv{idx}"
95
+ bind_vars[var] = value
96
+ return f"({field} == null OR {field} == @{var})"
97
+ idx = counter[0]
98
+ counter[0] += 1
99
+ var = f"fv{idx}"
100
+ bind_vars[var] = value
101
+ return f"{field} == @{var}"
102
+
103
+ if op == "!=":
104
+ if value is None:
105
+ idx = counter[0]
106
+ counter[0] += 1
107
+ var = f"fv{idx}"
108
+ bind_vars[var] = value
109
+ return f"({field} != null AND {field} != @{var})"
110
+ idx = counter[0]
111
+ counter[0] += 1
112
+ var = f"fv{idx}"
113
+ bind_vars[var] = value
114
+ return f"{field} != @{var}"
115
+
116
+ if op in ("in", "not in"):
117
+ if not isinstance(value, list):
118
+ msg = f"Filter operator '{op}' requires a list value, got {type(value).__name__}."
119
+ raise FilterError(msg)
120
+ idx = counter[0]
121
+ counter[0] += 1
122
+ var = f"fv{idx}"
123
+ bind_vars[var] = value
124
+ aql_op = "IN" if op == "in" else "NOT IN"
125
+ return f"{field} {aql_op} @{var}"
126
+
127
+ msg = f"Unsupported filter operator: {op}"
128
+ raise FilterError(msg)
File without changes