|
| 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.elasticsearch.document_store import ElasticsearchDocumentStore |
| 13 | + |
| 14 | + |
| 15 | +@component |
| 16 | +class ElasticsearchInferenceDenseRetriever: |
| 17 | + """ |
| 18 | + ElasticsearchInferenceDenseRetriever retrieves documents using Elasticsearch server-side dense vector inference. |
| 19 | +
|
| 20 | + Unlike ``ElasticsearchEmbeddingRetriever``, no local embedding model is required — the query embedding |
| 21 | + is generated by an Elasticsearch inference endpoint (e.g. a text embedding model deployed via the |
| 22 | + Elastic Inference API such as ``".multilingual-e5-small-elasticsearch"`` on Serverless or a |
| 23 | + custom endpoint on a stateful cluster). |
| 24 | +
|
| 25 | + Only the query is embedded at search time. The indexed documents must already have their |
| 26 | + ``embedding`` field populated with vectors produced by the **same** inference endpoint, for |
| 27 | + example by writing them through an ingest pipeline with an ``inference`` processor whose |
| 28 | + ``output_field`` is ``"embedding"``. Vectors from a different model, or a different dimension, |
| 29 | + will return meaningless results or fail at query time. |
| 30 | +
|
| 31 | + Usage example: |
| 32 | +
|
| 33 | + ```python |
| 34 | + from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore |
| 35 | + from haystack_integrations.components.retrievers.elasticsearch import ElasticsearchInferenceDenseRetriever |
| 36 | +
|
| 37 | + document_store = ElasticsearchDocumentStore(hosts="https://my-cluster.es.io:443") |
| 38 | + retriever = ElasticsearchInferenceDenseRetriever( |
| 39 | + document_store=document_store, |
| 40 | + inference_id=".multilingual-e5-small-elasticsearch", |
| 41 | + ) |
| 42 | +
|
| 43 | + result = retriever.run(query="Find documents about Berlin") |
| 44 | + for doc in result["documents"]: |
| 45 | + print(doc.content) |
| 46 | + ``` |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + *, |
| 52 | + document_store: ElasticsearchDocumentStore, |
| 53 | + inference_id: str, |
| 54 | + filters: dict[str, Any] | None = None, |
| 55 | + top_k: int = 10, |
| 56 | + num_candidates: int | None = None, |
| 57 | + filter_policy: str | FilterPolicy = FilterPolicy.REPLACE, |
| 58 | + ) -> None: |
| 59 | + """ |
| 60 | + Create the ElasticsearchInferenceDenseRetriever component. |
| 61 | +
|
| 62 | + :param document_store: An instance of ElasticsearchDocumentStore. |
| 63 | + :param inference_id: The Elasticsearch inference endpoint ID used to embed the query text. |
| 64 | + :param filters: Filters applied to the retrieved Documents. |
| 65 | + :param top_k: Maximum number of Documents to return. |
| 66 | + :param num_candidates: Number of approximate kNN candidates per shard. Defaults to ``top_k * 10``. |
| 67 | + :param filter_policy: Policy to determine how filters are applied. |
| 68 | + :raises ValueError: If ``document_store`` is not an instance of ``ElasticsearchDocumentStore`` or |
| 69 | + ``inference_id`` is empty. |
| 70 | + """ |
| 71 | + if not isinstance(document_store, ElasticsearchDocumentStore): |
| 72 | + msg = "document_store must be an instance of ElasticsearchDocumentStore" |
| 73 | + raise ValueError(msg) |
| 74 | + |
| 75 | + if not inference_id: |
| 76 | + msg = "inference_id must be provided" |
| 77 | + raise ValueError(msg) |
| 78 | + |
| 79 | + self._document_store = document_store |
| 80 | + self._inference_id = inference_id |
| 81 | + self._filters = filters or {} |
| 82 | + self._top_k = top_k |
| 83 | + self._num_candidates = num_candidates |
| 84 | + self._filter_policy = FilterPolicy.from_str(filter_policy) if isinstance(filter_policy, str) else filter_policy |
| 85 | + |
| 86 | + def to_dict(self) -> dict[str, Any]: |
| 87 | + """ |
| 88 | + Serializes the component to a dictionary. |
| 89 | +
|
| 90 | + :returns: Dictionary with serialized data. |
| 91 | + """ |
| 92 | + return default_to_dict( |
| 93 | + self, |
| 94 | + document_store=self._document_store.to_dict(), |
| 95 | + inference_id=self._inference_id, |
| 96 | + filters=self._filters, |
| 97 | + top_k=self._top_k, |
| 98 | + num_candidates=self._num_candidates, |
| 99 | + filter_policy=self._filter_policy.value, |
| 100 | + ) |
| 101 | + |
| 102 | + @classmethod |
| 103 | + def from_dict(cls, data: dict[str, Any]) -> "ElasticsearchInferenceDenseRetriever": |
| 104 | + """ |
| 105 | + Deserializes the component from a dictionary. |
| 106 | +
|
| 107 | + :param data: Dictionary to deserialize from. |
| 108 | + :returns: Deserialized component. |
| 109 | + """ |
| 110 | + data["init_parameters"]["document_store"] = ElasticsearchDocumentStore.from_dict( |
| 111 | + data["init_parameters"]["document_store"] |
| 112 | + ) |
| 113 | + if filter_policy := data["init_parameters"].get("filter_policy"): |
| 114 | + data["init_parameters"]["filter_policy"] = FilterPolicy.from_str(filter_policy) |
| 115 | + return default_from_dict(cls, data) |
| 116 | + |
| 117 | + def close(self) -> None: |
| 118 | + """ |
| 119 | + Release the synchronous resources of the underlying Document Store. |
| 120 | + """ |
| 121 | + self._document_store.close() |
| 122 | + |
| 123 | + async def close_async(self) -> None: |
| 124 | + """ |
| 125 | + Release the asynchronous resources of the underlying Document Store. |
| 126 | + """ |
| 127 | + await self._document_store.close_async() |
| 128 | + |
| 129 | + @component.output_types(documents=list[Document]) |
| 130 | + def run( |
| 131 | + self, |
| 132 | + query: str, |
| 133 | + filters: dict[str, Any] | None = None, |
| 134 | + top_k: int | None = None, |
| 135 | + ) -> dict[str, list[Document]]: |
| 136 | + """ |
| 137 | + Retrieve documents using inference-based dense vector search. |
| 138 | +
|
| 139 | + :param query: Query text to embed and search with. |
| 140 | + :param filters: Filters applied when fetching documents from the Document Store. |
| 141 | + The way runtime filters are applied depends on the ``filter_policy`` selected when |
| 142 | + initializing the Retriever. |
| 143 | + :param top_k: Maximum number of documents to return. |
| 144 | + :returns: A dictionary with the following keys: |
| 145 | + - ``documents``: List of ``Document``s most similar to the given ``query`` |
| 146 | + """ |
| 147 | + filters = apply_filter_policy(self._filter_policy, self._filters, filters) |
| 148 | + docs = self._document_store._dense_retrieval_inference( |
| 149 | + query=query, |
| 150 | + inference_id=self._inference_id, |
| 151 | + filters=filters, |
| 152 | + top_k=top_k if top_k is not None else self._top_k, |
| 153 | + num_candidates=self._num_candidates, |
| 154 | + ) |
| 155 | + return {"documents": docs} |
| 156 | + |
| 157 | + @component.output_types(documents=list[Document]) |
| 158 | + async def run_async( |
| 159 | + self, |
| 160 | + query: str, |
| 161 | + filters: dict[str, Any] | None = None, |
| 162 | + top_k: int | None = None, |
| 163 | + ) -> dict[str, list[Document]]: |
| 164 | + """ |
| 165 | + Asynchronously retrieve documents using inference-based dense vector search. |
| 166 | +
|
| 167 | + :param query: Query text to embed and search with. |
| 168 | + :param filters: Filters applied when fetching documents from the Document Store. |
| 169 | + The way runtime filters are applied depends on the ``filter_policy`` selected when |
| 170 | + initializing the Retriever. |
| 171 | + :param top_k: Maximum number of documents to return. |
| 172 | + :returns: A dictionary with the following keys: |
| 173 | + - ``documents``: List of ``Document``s most similar to the given ``query`` |
| 174 | + """ |
| 175 | + filters = apply_filter_policy(self._filter_policy, self._filters, filters) |
| 176 | + docs = await self._document_store._dense_retrieval_inference_async( |
| 177 | + query=query, |
| 178 | + inference_id=self._inference_id, |
| 179 | + filters=filters, |
| 180 | + top_k=top_k if top_k is not None else self._top_k, |
| 181 | + num_candidates=self._num_candidates, |
| 182 | + ) |
| 183 | + return {"documents": docs} |
0 commit comments