alloydb-haystack 0.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.
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: alloydb-haystack
3
+ Version: 0.1.0
4
+ Summary: An integration of Google Cloud AlloyDB with Haystack for vector search
5
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations
6
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/alloydb/README.md
7
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
8
+ Author-email: deepset GmbH <info@deepset.ai>, Gary Badwal <gurpreet071999@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
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 :: 3.14
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: google-cloud-alloydb-connector[psycopg]>=1.0.0
23
+ Requires-Dist: haystack-ai>=2.28.0
24
+ Requires-Dist: pgvector>=0.3.0
25
+ Requires-Dist: psycopg[binary]
26
+ Description-Content-Type: text/markdown
27
+
28
+ # AlloyDB Haystack Integration
29
+
30
+ [![PyPI - Version](https://img.shields.io/pypi/v/alloydb-haystack.svg)](https://pypi.org/project/alloydb-haystack)
31
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/alloydb-haystack.svg)](https://pypi.org/project/alloydb-haystack)
32
+
33
+ ---
34
+
35
+ [AlloyDB](https://cloud.google.com/alloydb) is a fully managed, PostgreSQL-compatible database service on Google Cloud,
36
+ optimised for demanding transactional and analytical workloads.
37
+
38
+ This package provides a Haystack `DocumentStore` backed by AlloyDB with the
39
+ [pgvector extension](https://cloud.google.com/alloydb/docs/ai/work-with-embeddings), enabling both dense vector
40
+ similarity search and full-text keyword search.
41
+
42
+ Connections are established through the
43
+ [AlloyDB Python Connector](https://github.com/GoogleCloudPlatform/alloydb-python-connector),
44
+ which handles IAM-based authentication and TLS encryption without requiring manual firewall rules or IP allowlisting.
45
+
46
+ ## Installation
47
+
48
+ ```console
49
+ pip install alloydb-haystack
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ```python
55
+ from haystack_integrations.document_stores.alloydb import AlloyDBDocumentStore
56
+ from haystack_integrations.components.retrievers.alloydb import (
57
+ AlloyDBEmbeddingRetriever,
58
+ AlloyDBKeywordRetriever,
59
+ )
60
+ ```
61
+
62
+ ### Environment Variables
63
+
64
+ | Variable | Description |
65
+ |---|---|
66
+ | `ALLOYDB_INSTANCE_URI` | AlloyDB instance URI: `projects/P/locations/R/clusters/C/instances/I` |
67
+ | `ALLOYDB_USER` | Database user (or IAM principal for IAM auth) |
68
+ | `ALLOYDB_PASSWORD` | Database password (not required when `enable_iam_auth=True`) |
69
+
70
+ ### Basic Example
71
+
72
+ ```python
73
+ import os
74
+ from haystack import Document
75
+ from haystack_integrations.document_stores.alloydb import AlloyDBDocumentStore
76
+
77
+ # Requires ALLOYDB_INSTANCE_URI, ALLOYDB_USER, and ALLOYDB_PASSWORD env vars
78
+ store = AlloyDBDocumentStore(
79
+ db="my-database",
80
+ embedding_dimension=768,
81
+ recreate_table=True,
82
+ )
83
+
84
+ store.write_documents([
85
+ Document(content="Paris is the capital of France", embedding=[0.1] * 768),
86
+ Document(content="Berlin is the capital of Germany", embedding=[0.2] * 768),
87
+ ])
88
+
89
+ print(store.count_documents()) # 2
90
+ ```
91
+
92
+ ### IAM Authentication
93
+
94
+ When using a service account for database access:
95
+
96
+ ```python
97
+ store = AlloyDBDocumentStore(
98
+ db="my-database",
99
+ user=Secret.from_env_var("ALLOYDB_IAM_USER"), # e.g. "my-sa@my-project.iam"
100
+ enable_iam_auth=True,
101
+ embedding_dimension=768,
102
+ )
103
+ ```
104
+
105
+ ### Vector Similarity Search
106
+
107
+ ```python
108
+ from haystack_integrations.components.retrievers.alloydb import AlloyDBEmbeddingRetriever
109
+
110
+ retriever = AlloyDBEmbeddingRetriever(document_store=store, top_k=5)
111
+ result = retriever.run(query_embedding=[0.1] * 768)
112
+ print(result["documents"])
113
+ ```
114
+
115
+ ### Keyword Search
116
+
117
+ ```python
118
+ from haystack_integrations.components.retrievers.alloydb import AlloyDBKeywordRetriever
119
+
120
+ retriever = AlloyDBKeywordRetriever(document_store=store, top_k=5)
121
+ result = retriever.run(query="capital France")
122
+ print(result["documents"])
123
+ ```
124
+
125
+ ### HNSW Index
126
+
127
+ For large datasets, the HNSW index provides approximate nearest-neighbour search with significantly
128
+ better query throughput:
129
+
130
+ ```python
131
+ store = AlloyDBDocumentStore(
132
+ db="my-database",
133
+ embedding_dimension=768,
134
+ search_strategy="hnsw",
135
+ hnsw_index_creation_kwargs={"m": 16, "ef_construction": 64},
136
+ hnsw_ef_search=40,
137
+ )
138
+ ```
139
+
140
+ ## Integration Tests
141
+
142
+ Integration tests require a running AlloyDB instance. Set the following environment variables
143
+ before running:
144
+
145
+ ```console
146
+ export ALLOYDB_INSTANCE_URI="projects/MY_PROJECT/locations/MY_REGION/clusters/MY_CLUSTER/instances/MY_INSTANCE"
147
+ export ALLOYDB_USER="my-db-user"
148
+ export ALLOYDB_PASSWORD="my-db-password"
149
+ ```
150
+
151
+ Then run:
152
+
153
+ ```console
154
+ cd integrations/alloydb
155
+ hatch run test:integration
156
+ ```
157
+
158
+ ## License
159
+
160
+ `alloydb-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,13 @@
1
+ haystack_integrations/components/retrievers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/retrievers/alloydb/__init__.py,sha256=v1DUf05F3KWk5MOj5wPsKpsIM5-vJ1FZvRI_w7Ps4io,395
3
+ haystack_integrations/components/retrievers/alloydb/embedding_retriever.py,sha256=5pSTCpj2BAmV5hVQOAhmr1A-K4_4O8oc04v9GzTXxTo,5462
4
+ haystack_integrations/components/retrievers/alloydb/keyword_retriever.py,sha256=BurpT6-yRorubjTxLvPl4YBi40p7w-nXeVbpZHS-r6Q,4167
5
+ haystack_integrations/document_stores/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ haystack_integrations/document_stores/alloydb/__init__.py,sha256=7eqlPU5nLgxCW--ZEJtwnHVdNR8ZpHf3_p4g_U9WVZc,241
7
+ haystack_integrations/document_stores/alloydb/converters.py,sha256=KC-aKJFEwJdLbjOcSSQ5oZZ9hQD3YfpXagDC4YA2vfk,3311
8
+ haystack_integrations/document_stores/alloydb/document_store.py,sha256=d31NlA5EfZTvVcPCHfDLzSbU3yv7tTxjFMpmvYHvJrc,54112
9
+ haystack_integrations/document_stores/alloydb/filters.py,sha256=E1nfNa-ci5an_gG33skudVixIBpl8ZUXqG5tSWMKHUY,9660
10
+ alloydb_haystack-0.1.0.dist-info/METADATA,sha256=PI1oA4RY3xKystbwxLDwlsUVMB5GoeQ149gULaHcsxc,5205
11
+ alloydb_haystack-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
12
+ alloydb_haystack-0.1.0.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
13
+ alloydb_haystack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,73 @@
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, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
@@ -0,0 +1,8 @@
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.alloydb.embedding_retriever import AlloyDBEmbeddingRetriever
6
+ from haystack_integrations.components.retrievers.alloydb.keyword_retriever import AlloyDBKeywordRetriever
7
+
8
+ __all__ = ["AlloyDBEmbeddingRetriever", "AlloyDBKeywordRetriever"]
@@ -0,0 +1,119 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any, Literal
6
+
7
+ from haystack import component, default_from_dict, default_to_dict
8
+ from haystack.dataclasses import Document
9
+ from haystack.document_stores.types import FilterPolicy
10
+ from haystack.document_stores.types.filter_policy import apply_filter_policy
11
+
12
+ from haystack_integrations.document_stores.alloydb import AlloyDBDocumentStore
13
+
14
+
15
+ @component
16
+ class AlloyDBEmbeddingRetriever:
17
+ """
18
+ Retrieves documents from the `AlloyDBDocumentStore` by embedding similarity.
19
+
20
+ Must be connected to the `AlloyDBDocumentStore`.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ *,
26
+ document_store: AlloyDBDocumentStore,
27
+ filters: dict[str, Any] | None = None,
28
+ top_k: int = 10,
29
+ vector_function: Literal["cosine_similarity", "inner_product", "l2_distance"] | None = None,
30
+ filter_policy: str | FilterPolicy = FilterPolicy.REPLACE,
31
+ ) -> None:
32
+ """
33
+ Create the `AlloyDBEmbeddingRetriever` component.
34
+
35
+ :param document_store: An instance of `AlloyDBDocumentStore` to use as the document store.
36
+ :param filters: Filters applied to the retrieved documents.
37
+ :param top_k: Maximum number of documents to return.
38
+ :param vector_function: The similarity function to use when searching for similar embeddings.
39
+ Overrides the `vector_function` set in the `AlloyDBDocumentStore`.
40
+ `"cosine_similarity"` and `"inner_product"` are similarity functions and
41
+ higher scores indicate greater similarity between the documents.
42
+ `"l2_distance"` returns the straight-line distance between vectors,
43
+ and the most similar documents are the ones with the smallest score.
44
+ **Important**: when using the `"hnsw"` search strategy, make sure to use the same
45
+ vector function as the one used when the HNSW index was created.
46
+ If not specified, the `vector_function` of the `AlloyDBDocumentStore` is used.
47
+ :param filter_policy: Policy to determine how filters are applied at query time.
48
+ `FilterPolicy.REPLACE` (default) replaces the init filters with the run-time filters.
49
+ `FilterPolicy.MERGE` merges the init filters with the run-time filters.
50
+ :raises ValueError: If `document_store` is not an instance of `AlloyDBDocumentStore`.
51
+ """
52
+ if not isinstance(document_store, AlloyDBDocumentStore):
53
+ msg = "document_store must be an instance of AlloyDBDocumentStore"
54
+ raise ValueError(msg)
55
+
56
+ self.document_store = document_store
57
+ self.filters = filters or {}
58
+ self.top_k = top_k
59
+ self.vector_function = vector_function
60
+ self.filter_policy = (
61
+ filter_policy if isinstance(filter_policy, FilterPolicy) else FilterPolicy.from_str(filter_policy)
62
+ )
63
+
64
+ @component.output_types(documents=list[Document])
65
+ def run(
66
+ self,
67
+ query_embedding: list[float],
68
+ filters: dict[str, Any] | None = None,
69
+ top_k: int | None = None,
70
+ vector_function: Literal["cosine_similarity", "inner_product", "l2_distance"] | None = None,
71
+ ) -> dict[str, list[Document]]:
72
+ """
73
+ Retrieve documents from the `AlloyDBDocumentStore` by embedding similarity.
74
+
75
+ :param query_embedding: A vector representation of the query.
76
+ :param filters: Filters applied to the retrieved documents.
77
+ The `filter_policy` set at initialization determines how these are combined with the init filters.
78
+ :param top_k: Maximum number of documents to return. Overrides the `top_k` set at initialization.
79
+ :param vector_function: The similarity function to use when searching for similar embeddings.
80
+ Overrides the `vector_function` set at initialization.
81
+ :returns: A dictionary containing the `documents` retrieved from the document store.
82
+ """
83
+ filters = apply_filter_policy(self.filter_policy, self.filters, filters)
84
+ docs = self.document_store._embedding_retrieval(
85
+ query_embedding=query_embedding,
86
+ filters=filters,
87
+ top_k=top_k or self.top_k,
88
+ vector_function=vector_function or self.vector_function,
89
+ )
90
+ return {"documents": docs}
91
+
92
+ def to_dict(self) -> dict[str, Any]:
93
+ """
94
+ Serializes the component to a dictionary.
95
+
96
+ :returns: Dictionary with serialized data.
97
+ """
98
+ return default_to_dict(
99
+ self,
100
+ document_store=self.document_store.to_dict(),
101
+ filters=self.filters,
102
+ top_k=self.top_k,
103
+ vector_function=self.vector_function,
104
+ filter_policy=self.filter_policy.value,
105
+ )
106
+
107
+ @classmethod
108
+ def from_dict(cls, data: dict[str, Any]) -> "AlloyDBEmbeddingRetriever":
109
+ """
110
+ Deserializes the component from a dictionary.
111
+
112
+ :param data: Dictionary to deserialize from.
113
+ :returns: Deserialized component.
114
+ """
115
+ document_store = AlloyDBDocumentStore.from_dict(data["init_parameters"]["document_store"])
116
+ data["init_parameters"]["document_store"] = document_store
117
+ if filter_policy := data["init_parameters"].get("filter_policy"):
118
+ data["init_parameters"]["filter_policy"] = FilterPolicy.from_str(filter_policy)
119
+ return default_from_dict(cls, data)
@@ -0,0 +1,104 @@
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
+ from haystack.document_stores.types import FilterPolicy
10
+ from haystack.document_stores.types.filter_policy import apply_filter_policy
11
+
12
+ from haystack_integrations.document_stores.alloydb import AlloyDBDocumentStore
13
+
14
+
15
+ @component
16
+ class AlloyDBKeywordRetriever:
17
+ """
18
+ Retrieves documents from the `AlloyDBDocumentStore` by keyword search.
19
+
20
+ Uses PostgreSQL full-text search (`to_tsvector` / `plainto_tsquery`) to find documents.
21
+ Must be connected to the `AlloyDBDocumentStore`.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ *,
27
+ document_store: AlloyDBDocumentStore,
28
+ filters: dict[str, Any] | None = None,
29
+ top_k: int = 10,
30
+ filter_policy: str | FilterPolicy = FilterPolicy.REPLACE,
31
+ ) -> None:
32
+ """
33
+ Create the `AlloyDBKeywordRetriever` component.
34
+
35
+ :param document_store: An instance of `AlloyDBDocumentStore` to use as the document store.
36
+ :param filters: Filters applied to the retrieved documents.
37
+ :param top_k: Maximum number of documents to return.
38
+ :param filter_policy: Policy to determine how filters are applied at query time.
39
+ `FilterPolicy.REPLACE` (default) replaces the init filters with the run-time filters.
40
+ `FilterPolicy.MERGE` merges the init filters with the run-time filters.
41
+ :raises ValueError: If `document_store` is not an instance of `AlloyDBDocumentStore`.
42
+ """
43
+ if not isinstance(document_store, AlloyDBDocumentStore):
44
+ msg = "document_store must be an instance of AlloyDBDocumentStore"
45
+ raise ValueError(msg)
46
+
47
+ self.document_store = document_store
48
+ self.filters = filters or {}
49
+ self.top_k = top_k
50
+ self.filter_policy = (
51
+ filter_policy if isinstance(filter_policy, FilterPolicy) else FilterPolicy.from_str(filter_policy)
52
+ )
53
+
54
+ @component.output_types(documents=list[Document])
55
+ def run(
56
+ self,
57
+ query: str,
58
+ filters: dict[str, Any] | None = None,
59
+ top_k: int | None = None,
60
+ ) -> dict[str, list[Document]]:
61
+ """
62
+ Retrieve documents from the `AlloyDBDocumentStore` by keyword search.
63
+
64
+ :param query: A keyword query to search for.
65
+ :param filters: Filters applied to the retrieved documents.
66
+ The `filter_policy` set at initialization determines how these are combined with the init filters.
67
+ :param top_k: Maximum number of documents to return. Overrides the `top_k` set at initialization.
68
+ :returns: A dictionary containing the `documents` retrieved from the document store.
69
+ """
70
+ filters = apply_filter_policy(self.filter_policy, self.filters, filters)
71
+ docs = self.document_store._keyword_retrieval(
72
+ query=query,
73
+ filters=filters,
74
+ top_k=top_k or self.top_k,
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
+ filters=self.filters,
88
+ top_k=self.top_k,
89
+ filter_policy=self.filter_policy.value,
90
+ )
91
+
92
+ @classmethod
93
+ def from_dict(cls, data: dict[str, Any]) -> "AlloyDBKeywordRetriever":
94
+ """
95
+ Deserializes the component from a dictionary.
96
+
97
+ :param data: Dictionary to deserialize from.
98
+ :returns: Deserialized component.
99
+ """
100
+ document_store = AlloyDBDocumentStore.from_dict(data["init_parameters"]["document_store"])
101
+ data["init_parameters"]["document_store"] = document_store
102
+ if filter_policy := data["init_parameters"].get("filter_policy"):
103
+ data["init_parameters"]["filter_policy"] = FilterPolicy.from_str(filter_policy)
104
+ 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.alloydb.document_store import AlloyDBDocumentStore
6
+
7
+ __all__ = ["AlloyDBDocumentStore"]
@@ -0,0 +1,81 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from dataclasses import replace
6
+ from typing import Any
7
+
8
+ from haystack import logging
9
+ from haystack.dataclasses import ByteStream, Document
10
+ from psycopg.types.json import Jsonb
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def _from_haystack_to_pg_documents(documents: list[Document]) -> list[dict[str, Any]]:
16
+ """
17
+ Internal method to convert a list of Haystack Documents to a list of dictionaries.
18
+
19
+ The resulting dictionaries can be used to insert documents into the AlloyDBDocumentStore.
20
+ """
21
+
22
+ db_documents = []
23
+ for document in documents:
24
+ db_document = {k: v for k, v in document.to_dict(flatten=False).items() if k not in ["score", "blob"]}
25
+
26
+ blob = document.blob
27
+ db_document["blob_data"] = blob.data if blob else None
28
+ db_document["blob_meta"] = Jsonb(blob.meta) if blob and blob.meta else None
29
+ db_document["blob_mime_type"] = blob.mime_type if blob and blob.mime_type else None
30
+ db_document["meta"] = Jsonb(db_document["meta"])
31
+ # PostgreSQL text fields cannot contain NUL (0x00) bytes, removing NUL bytes
32
+ if content := db_document["content"]:
33
+ db_document["content"] = content.replace("\x00", "")
34
+
35
+ if "sparse_embedding" in db_document:
36
+ sparse_embedding = db_document.pop("sparse_embedding", None)
37
+ if sparse_embedding:
38
+ logger.warning(
39
+ "Document {doc_id} has the `sparse_embedding` field set,"
40
+ "but storing sparse embeddings in AlloyDB is not currently supported."
41
+ "The `sparse_embedding` field will be ignored.",
42
+ doc_id=db_document["id"],
43
+ )
44
+
45
+ db_documents.append(db_document)
46
+
47
+ return db_documents
48
+
49
+
50
+ def _from_pg_to_haystack_documents(documents: list[dict[str, Any]]) -> list[Document]:
51
+ """
52
+ Internal method to convert a list of dictionaries from AlloyDB to a list of Haystack Documents.
53
+ """
54
+
55
+ haystack_documents = []
56
+ for document in documents:
57
+ haystack_dict = dict(document)
58
+ blob_data = haystack_dict.pop("blob_data")
59
+ blob_meta = haystack_dict.pop("blob_meta")
60
+ blob_mime_type = haystack_dict.pop("blob_mime_type")
61
+
62
+ # convert the embedding to a list of floats
63
+ # for strange reasons, halfvec and vector have different methods to convert the embedding to a list
64
+ if document.get("embedding") is not None:
65
+ if hasattr(document["embedding"], "tolist"): # vector
66
+ haystack_dict["embedding"] = document["embedding"].tolist()
67
+ else: # halfvec
68
+ haystack_dict["embedding"] = document["embedding"].to_list()
69
+ # Document.from_dict expects the meta field to be a dict or not be present (not None)
70
+ if "meta" in haystack_dict and haystack_dict["meta"] is None:
71
+ haystack_dict.pop("meta")
72
+
73
+ haystack_document = Document.from_dict(haystack_dict)
74
+
75
+ if blob_data:
76
+ blob = ByteStream(data=blob_data, meta=blob_meta, mime_type=blob_mime_type)
77
+ haystack_document = replace(haystack_document, blob=blob)
78
+
79
+ haystack_documents.append(haystack_document)
80
+
81
+ return haystack_documents