|
| 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 import ElasticsearchDocumentStore |
| 13 | + |
| 14 | + |
| 15 | +@component |
| 16 | +class ElasticsearchInferenceHybridRetriever: |
| 17 | + """ |
| 18 | + A fully server-side hybrid retriever combining BM25 and ELSER sparse vector search via Elasticsearch RRF. |
| 19 | +
|
| 20 | + Issues a single Elasticsearch request using the `retriever.rrf` API (ES 8.9+ for `rank.rrf`, |
| 21 | + ES 8.14+ for the Retriever API). No local embedding model is required and no client-side |
| 22 | + score merging takes place — ranking is handled entirely by Elasticsearch. |
| 23 | +
|
| 24 | + Usage example (Elastic Cloud with ELSER deployed): |
| 25 | +
|
| 26 | + ```python |
| 27 | + import os |
| 28 | + from haystack_integrations.components.retrievers.elasticsearch import ElasticsearchInferenceHybridRetriever |
| 29 | + from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore |
| 30 | +
|
| 31 | + doc_store = ElasticsearchDocumentStore( |
| 32 | + hosts=os.environ["ELASTICSEARCH_URL"], |
| 33 | + api_key=os.environ["ELASTIC_API_KEY"], |
| 34 | + sparse_vector_field="sparse_vec", |
| 35 | + ) |
| 36 | + retriever = ElasticsearchInferenceHybridRetriever( |
| 37 | + document_store=doc_store, |
| 38 | + inference_id=".elser-2-elasticsearch", |
| 39 | + ) |
| 40 | + results = retriever.run(query="What is reinforcement learning?") |
| 41 | + ``` |
| 42 | + """ |
| 43 | + |
| 44 | + def __init__( |
| 45 | + self, |
| 46 | + *, |
| 47 | + document_store: ElasticsearchDocumentStore, |
| 48 | + inference_id: str, |
| 49 | + filters: dict[str, Any] | None = None, |
| 50 | + fuzziness: str = "AUTO", |
| 51 | + top_k: int = 10, |
| 52 | + filter_policy: str | FilterPolicy = FilterPolicy.REPLACE, |
| 53 | + rank_window_size: int = 100, |
| 54 | + rank_constant: int = 60, |
| 55 | + ) -> None: |
| 56 | + """ |
| 57 | + Create the ElasticsearchInferenceHybridRetriever component. |
| 58 | +
|
| 59 | + :param document_store: An instance of ElasticsearchDocumentStore with `sparse_vector_field` configured. |
| 60 | + :param inference_id: The Elasticsearch inference endpoint ID used for sparse vector search e.g. |
| 61 | + ".elser-2-elasticsearch" |
| 62 | + :param filters: Filters applied to both sub-retrievers. |
| 63 | + :param fuzziness: Fuzziness for the BM25 multi_match query. |
| 64 | + :param top_k: Maximum number of Documents to return. |
| 65 | + :param filter_policy: Policy to determine how runtime filters are merged with init-time filters. |
| 66 | + :param rank_window_size: Number of candidates each sub-retriever collects before RRF ranking. |
| 67 | + :param rank_constant: RRF rank constant. Higher values reduce the impact of rank position differences. |
| 68 | + :raises ValueError: If `document_store` is not an ElasticsearchDocumentStore or `inference_id` is empty. |
| 69 | + """ |
| 70 | + if not isinstance(document_store, ElasticsearchDocumentStore): |
| 71 | + msg = "document_store must be an instance of ElasticsearchDocumentStore" |
| 72 | + raise ValueError(msg) |
| 73 | + |
| 74 | + if not inference_id: |
| 75 | + msg = "inference_id must be provided" |
| 76 | + raise ValueError(msg) |
| 77 | + |
| 78 | + self._document_store = document_store |
| 79 | + self._inference_id = inference_id |
| 80 | + self._filters = filters or {} |
| 81 | + self._fuzziness = fuzziness |
| 82 | + self._top_k = top_k |
| 83 | + self._filter_policy = FilterPolicy.from_str(filter_policy) if isinstance(filter_policy, str) else filter_policy |
| 84 | + self._rank_window_size = rank_window_size |
| 85 | + self._rank_constant = rank_constant |
| 86 | + |
| 87 | + def to_dict(self) -> dict[str, Any]: |
| 88 | + """ |
| 89 | + Serializes the component to a dictionary. |
| 90 | +
|
| 91 | + :returns: Dictionary with serialized data. |
| 92 | + """ |
| 93 | + return default_to_dict( |
| 94 | + self, |
| 95 | + document_store=self._document_store.to_dict(), |
| 96 | + inference_id=self._inference_id, |
| 97 | + filters=self._filters, |
| 98 | + fuzziness=self._fuzziness, |
| 99 | + top_k=self._top_k, |
| 100 | + filter_policy=self._filter_policy.value, |
| 101 | + rank_window_size=self._rank_window_size, |
| 102 | + rank_constant=self._rank_constant, |
| 103 | + ) |
| 104 | + |
| 105 | + @classmethod |
| 106 | + def from_dict(cls, data: dict[str, Any]) -> "ElasticsearchInferenceHybridRetriever": |
| 107 | + """ |
| 108 | + Deserializes the component from a dictionary. |
| 109 | +
|
| 110 | + :param data: Dictionary to deserialize from. |
| 111 | + :returns: Deserialized component instance. |
| 112 | + """ |
| 113 | + data["init_parameters"]["document_store"] = ElasticsearchDocumentStore.from_dict( |
| 114 | + data["init_parameters"]["document_store"] |
| 115 | + ) |
| 116 | + if filter_policy := data["init_parameters"].get("filter_policy"): |
| 117 | + data["init_parameters"]["filter_policy"] = FilterPolicy.from_str(filter_policy) |
| 118 | + return default_from_dict(cls, data) |
| 119 | + |
| 120 | + @component.output_types(documents=list[Document]) |
| 121 | + def run( |
| 122 | + self, |
| 123 | + query: str, |
| 124 | + filters: dict[str, Any] | None = None, |
| 125 | + top_k: int | None = None, |
| 126 | + ) -> dict[str, list[Document]]: |
| 127 | + """ |
| 128 | + Run a hybrid retrieval query against Elasticsearch. |
| 129 | +
|
| 130 | + :param query: The query string. |
| 131 | + :param filters: Runtime filters merged with init-time filters according to `filter_policy`. |
| 132 | + :param top_k: Maximum number of documents to return, overrides the init-time value. |
| 133 | + :returns: A dictionary with key `documents` containing the retrieved list of `Document`s. |
| 134 | + """ |
| 135 | + filters = apply_filter_policy(self._filter_policy, self._filters, filters) |
| 136 | + docs = self._document_store._hybrid_retrieval_inference( |
| 137 | + query=query, |
| 138 | + inference_id=self._inference_id, |
| 139 | + filters=filters, |
| 140 | + fuzziness=self._fuzziness, |
| 141 | + top_k=top_k or self._top_k, |
| 142 | + rank_window_size=self._rank_window_size, |
| 143 | + rank_constant=self._rank_constant, |
| 144 | + ) |
| 145 | + return {"documents": docs} |
| 146 | + |
| 147 | + @component.output_types(documents=list[Document]) |
| 148 | + async def run_async( |
| 149 | + self, |
| 150 | + query: str, |
| 151 | + filters: dict[str, Any] | None = None, |
| 152 | + top_k: int | None = None, |
| 153 | + ) -> dict[str, list[Document]]: |
| 154 | + """ |
| 155 | + Asynchronously run a hybrid retrieval query against Elasticsearch. |
| 156 | +
|
| 157 | + :param query: The query string. |
| 158 | + :param filters: Runtime filters merged with init-time filters according to `filter_policy`. |
| 159 | + :param top_k: Maximum number of documents to return, overrides the init-time value. |
| 160 | + :returns: A dictionary with key `documents` containing the retrieved list of `Document`s. |
| 161 | + """ |
| 162 | + filters = apply_filter_policy(self._filter_policy, self._filters, filters) |
| 163 | + docs = await self._document_store._hybrid_retrieval_inference_async( |
| 164 | + query=query, |
| 165 | + inference_id=self._inference_id, |
| 166 | + filters=filters, |
| 167 | + fuzziness=self._fuzziness, |
| 168 | + top_k=top_k or self._top_k, |
| 169 | + rank_window_size=self._rank_window_size, |
| 170 | + rank_constant=self._rank_constant, |
| 171 | + ) |
| 172 | + return {"documents": docs} |
0 commit comments