pgvector-haystack 3.0.1__py3-none-any.whl → 3.2.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.
@@ -151,7 +151,8 @@ class PgvectorEmbeddingRetriever:
151
151
  :param top_k: Maximum number of Documents to return.
152
152
  :param vector_function: The similarity function to use when searching for similar embeddings.
153
153
 
154
- :returns: List of Documents similar to `query_embedding`.
154
+ :returns: A dictionary with the following keys:
155
+ - `documents`: List of `Document`s that are similar to `query_embedding`.
155
156
  """
156
157
  filters = apply_filter_policy(self.filter_policy, self.filters, filters)
157
158
  top_k = top_k or self.top_k
@@ -164,3 +165,36 @@ class PgvectorEmbeddingRetriever:
164
165
  vector_function=vector_function,
165
166
  )
166
167
  return {"documents": docs}
168
+
169
+ @component.output_types(documents=List[Document])
170
+ async def run_async(
171
+ self,
172
+ query_embedding: List[float],
173
+ filters: Optional[Dict[str, Any]] = None,
174
+ top_k: Optional[int] = None,
175
+ vector_function: Optional[Literal["cosine_similarity", "inner_product", "l2_distance"]] = None,
176
+ ):
177
+ """
178
+ Asynchronously retrieve documents from the `PgvectorDocumentStore`, based on their embeddings.
179
+
180
+ :param query_embedding: Embedding of the query.
181
+ :param filters: Filters applied to the retrieved Documents. The way runtime filters are applied depends on
182
+ the `filter_policy` chosen at retriever initialization. See init method docstring for more
183
+ details.
184
+ :param top_k: Maximum number of Documents to return.
185
+ :param vector_function: The similarity function to use when searching for similar embeddings.
186
+
187
+ :returns: A dictionary with the following keys:
188
+ - `documents`: List of `Document`s that are similar to `query_embedding`.
189
+ """
190
+ filters = apply_filter_policy(self.filter_policy, self.filters, filters)
191
+ top_k = top_k or self.top_k
192
+ vector_function = vector_function or self.vector_function
193
+
194
+ docs = await self.document_store._embedding_retrieval_async(
195
+ query_embedding=query_embedding,
196
+ filters=filters,
197
+ top_k=top_k,
198
+ vector_function=vector_function,
199
+ )
200
+ return {"documents": docs}
@@ -136,3 +136,33 @@ class PgvectorKeywordRetriever:
136
136
  top_k=top_k,
137
137
  )
138
138
  return {"documents": docs}
139
+
140
+ @component.output_types(documents=List[Document])
141
+ async def run_async(
142
+ self,
143
+ query: str,
144
+ filters: Optional[Dict[str, Any]] = None,
145
+ top_k: Optional[int] = None,
146
+ ):
147
+ """
148
+ Asynchronously retrieve documents from the `PgvectorDocumentStore`, based on keywords.
149
+
150
+ :param query: String to search in `Document`s' content.
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 Documents to return.
155
+
156
+ :returns: A dictionary with the following keys:
157
+ - `documents`: List of `Document`s that match the query.
158
+ """
159
+ filters = apply_filter_policy(self.filter_policy, self.filters, filters)
160
+
161
+ top_k = top_k or self.top_k
162
+
163
+ docs = await self.document_store._keyword_retrieval_async(
164
+ query=query,
165
+ filters=filters,
166
+ top_k=top_k,
167
+ )
168
+ return {"documents": docs}
@@ -0,0 +1,69 @@
1
+ from typing import Any, Dict, List
2
+
3
+ from haystack import logging
4
+ from haystack.dataclasses import ByteStream, Document
5
+ from psycopg.types.json import Jsonb
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ def _from_haystack_to_pg_documents(documents: List[Document]) -> List[Dict[str, Any]]:
11
+ """
12
+ Internal method to convert a list of Haystack Documents to a list of dictionaries that can be used to insert
13
+ documents into the PgvectorDocumentStore.
14
+ """
15
+
16
+ db_documents = []
17
+ for document in documents:
18
+ db_document = {k: v for k, v in document.to_dict(flatten=False).items() if k not in ["score", "blob"]}
19
+
20
+ blob = document.blob
21
+ db_document["blob_data"] = blob.data if blob else None
22
+ db_document["blob_meta"] = Jsonb(blob.meta) if blob and blob.meta else None
23
+ db_document["blob_mime_type"] = blob.mime_type if blob and blob.mime_type else None
24
+ db_document["meta"] = Jsonb(db_document["meta"])
25
+
26
+ if "sparse_embedding" in db_document:
27
+ sparse_embedding = db_document.pop("sparse_embedding", None)
28
+ if sparse_embedding:
29
+ logger.warning(
30
+ "Document {doc_id} has the `sparse_embedding` field set,"
31
+ "but storing sparse embeddings in Pgvector is not currently supported."
32
+ "The `sparse_embedding` field will be ignored.",
33
+ doc_id=db_document["id"],
34
+ )
35
+
36
+ db_documents.append(db_document)
37
+
38
+ return db_documents
39
+
40
+
41
+ def _from_pg_to_haystack_documents(documents: List[Dict[str, Any]]) -> List[Document]:
42
+ """
43
+ Internal method to convert a list of dictionaries from pgvector to a list of Haystack Documents.
44
+ """
45
+
46
+ haystack_documents = []
47
+ for document in documents:
48
+ haystack_dict = dict(document)
49
+ blob_data = haystack_dict.pop("blob_data")
50
+ blob_meta = haystack_dict.pop("blob_meta")
51
+ blob_mime_type = haystack_dict.pop("blob_mime_type")
52
+
53
+ # convert the embedding to a list of floats
54
+ # for strange reasons, halfvec and vector have different methods to convert the embedding to a list
55
+ if document.get("embedding") is not None:
56
+ if hasattr(document["embedding"], "tolist"): # vector
57
+ haystack_dict["embedding"] = document["embedding"].tolist()
58
+ else: # halfvec
59
+ haystack_dict["embedding"] = document["embedding"].to_list()
60
+
61
+ haystack_document = Document.from_dict(haystack_dict)
62
+
63
+ if blob_data:
64
+ blob = ByteStream(data=blob_data, meta=blob_meta, mime_type=blob_mime_type)
65
+ haystack_document.blob = blob
66
+
67
+ haystack_documents.append(haystack_document)
68
+
69
+ return haystack_documents