Skip to content

Commit 1961d1e

Browse files
feat(elasticsearch): add ElasticsearchInferenceDenseRetriever (#3525)
Co-authored-by: David S. Batista <dsbatista@gmail.com>
1 parent ed99247 commit 1961d1e

7 files changed

Lines changed: 762 additions & 9 deletions

File tree

‎integrations/elasticsearch/README.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,15 @@
1313
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
1414

1515
To run integration tests locally, you need a Docker container running ElasticSearch.
16-
Use the provided `docker-compose.yml` file to start the container: `docker compose up -d`.
16+
Use the provided `docker-compose.yml` file to start the container: `docker compose up -d`.
17+
18+
The `test_cloud_*` integration tests run against a managed Elastic Cloud project and are skipped unless the
19+
required environment variables are set:
20+
21+
| Variable | Required | Default | Description |
22+
|---|---|---|---|
23+
| `ELASTICSEARCH_URL` | yes | – | Elastic Cloud endpoint, e.g. `https://<id>.es.<region>.elastic.cloud:443` |
24+
| `ELASTIC_API_KEY` | yes | – | Base64-encoded API key |
25+
| `ELASTICSEARCH_INFERENCE_ID` | no | `.elser-2-elastic` | Sparse (ELSER) inference endpoint used by the sparse and hybrid tests |
26+
| `ELASTICSEARCH_DENSE_INFERENCE_ID` | no | `.multilingual-e5-small-elasticsearch` | Dense text-embedding inference endpoint used by the dense tests |
27+
| `ELASTICSEARCH_DENSE_EMBEDDING_DIMS` | no | `384` | Output dimension of the dense model, used by the dense ingest pipeline tests |

‎integrations/elasticsearch/pydoc/config_docusaurus.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ loaders:
22
- modules:
33
- haystack_integrations.components.retrievers.elasticsearch.bm25_retriever
44
- haystack_integrations.components.retrievers.elasticsearch.embedding_retriever
5+
- haystack_integrations.components.retrievers.elasticsearch.inference_dense_retriever
6+
- haystack_integrations.components.retrievers.elasticsearch.inference_hybrid_retriever
7+
- haystack_integrations.components.retrievers.elasticsearch.inference_sparse_retriever
58
- haystack_integrations.components.retrievers.elasticsearch.sql_retriever
69
- haystack_integrations.document_stores.elasticsearch.document_store
710
- haystack_integrations.document_stores.elasticsearch.filters

‎integrations/elasticsearch/src/haystack_integrations/components/retrievers/elasticsearch/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from .bm25_retriever import ElasticsearchBM25Retriever
55
from .elasticsearch_hybrid_retriever import ElasticsearchHybridRetriever
66
from .embedding_retriever import ElasticsearchEmbeddingRetriever
7+
from .inference_dense_retriever import ElasticsearchInferenceDenseRetriever
78
from .inference_hybrid_retriever import ElasticsearchInferenceHybridRetriever
89
from .inference_sparse_retriever import ElasticsearchInferenceSparseRetriever
910
from .sparse_embedding_retriever import ElasticsearchSparseEmbeddingRetriever
@@ -13,6 +14,7 @@
1314
"ElasticsearchBM25Retriever",
1415
"ElasticsearchEmbeddingRetriever",
1516
"ElasticsearchHybridRetriever",
17+
"ElasticsearchInferenceDenseRetriever",
1618
"ElasticsearchInferenceHybridRetriever",
1719
"ElasticsearchInferenceSparseRetriever",
1820
"ElasticsearchSQLRetriever",
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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}

‎integrations/elasticsearch/src/haystack_integrations/document_stores/elasticsearch/document_store.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1549,6 +1549,115 @@ async def _hybrid_retrieval_inference_async(
15491549
)
15501550
return await self._search_documents_async(**body)
15511551

1552+
def _create_dense_retrieval_inference_body(
1553+
self,
1554+
query: str,
1555+
inference_id: str,
1556+
*,
1557+
filters: dict[str, Any] | None = None,
1558+
top_k: int = 10,
1559+
num_candidates: int | None = None,
1560+
) -> dict[str, Any]:
1561+
"""
1562+
Builds the Elasticsearch kNN search body for server-side dense retrieval using an inference endpoint.
1563+
1564+
The query embedding is generated by Elasticsearch via the inference API — no local embedding
1565+
model is required. Uses ``knn.query_vector_builder`` (available since ES 8.0).
1566+
1567+
:param query: Query text to embed and search with.
1568+
:param inference_id: Elasticsearch inference endpoint ID (e.g. ``".multilingual-e5-small-elasticsearch"``).
1569+
:param filters: Optional filters to narrow down the search space.
1570+
:param top_k: Maximum number of documents to return.
1571+
:param num_candidates: Number of approximate kNN candidates per shard. Defaults to ``top_k * 10``.
1572+
:returns: Search body for Elasticsearch.
1573+
:raises ValueError: If ``query`` is empty.
1574+
"""
1575+
if not query:
1576+
msg = "query must be a non-empty string for inference-based dense retrieval"
1577+
raise ValueError(msg)
1578+
1579+
if num_candidates is None:
1580+
num_candidates = top_k * 10
1581+
1582+
body: dict[str, Any] = {
1583+
"knn": {
1584+
"field": "embedding",
1585+
"query_vector_builder": {
1586+
"text_embedding": {
1587+
"model_id": inference_id,
1588+
"model_text": query,
1589+
}
1590+
},
1591+
"k": top_k,
1592+
"num_candidates": num_candidates,
1593+
},
1594+
}
1595+
1596+
if filters:
1597+
body["knn"]["filter"] = _normalize_filters(filters)
1598+
1599+
return body
1600+
1601+
def _dense_retrieval_inference(
1602+
self,
1603+
query: str,
1604+
inference_id: str,
1605+
*,
1606+
filters: dict[str, Any] | None = None,
1607+
top_k: int = 10,
1608+
num_candidates: int | None = None,
1609+
) -> list[Document]:
1610+
"""
1611+
Retrieves documents using server-side dense vector inference search.
1612+
1613+
Elasticsearch generates the query embedding from ``query`` using the specified inference
1614+
endpoint — no local embedder is needed.
1615+
1616+
:param query: Query text to use for inference-based dense retrieval.
1617+
:param inference_id: Elasticsearch inference endpoint ID.
1618+
:param filters: Optional filters to narrow down the search space.
1619+
:param top_k: Maximum number of documents to return.
1620+
:param num_candidates: Number of approximate kNN candidates per shard.
1621+
:returns: List of Documents most similar to the query.
1622+
"""
1623+
body = self._create_dense_retrieval_inference_body(
1624+
query=query,
1625+
inference_id=inference_id,
1626+
filters=filters,
1627+
top_k=top_k,
1628+
num_candidates=num_candidates,
1629+
)
1630+
return self._search_documents(**body)
1631+
1632+
async def _dense_retrieval_inference_async(
1633+
self,
1634+
query: str,
1635+
inference_id: str,
1636+
*,
1637+
filters: dict[str, Any] | None = None,
1638+
top_k: int = 10,
1639+
num_candidates: int | None = None,
1640+
) -> list[Document]:
1641+
"""
1642+
Asynchronously retrieves documents using server-side dense vector inference search.
1643+
1644+
:param query: Query text to use for inference-based dense retrieval.
1645+
:param inference_id: Elasticsearch inference endpoint ID.
1646+
:param filters: Optional filters to narrow down the search space.
1647+
:param top_k: Maximum number of documents to return.
1648+
:param num_candidates: Number of approximate kNN candidates per shard.
1649+
:returns: List of Documents most similar to the query.
1650+
"""
1651+
await self._ensure_initialized_async()
1652+
body = self._create_dense_retrieval_inference_body(
1653+
query=query,
1654+
inference_id=inference_id,
1655+
filters=filters,
1656+
top_k=top_k,
1657+
num_candidates=num_candidates,
1658+
)
1659+
return await self._search_documents_async(**body)
1660+
15521661
def count_documents_by_filter(self, filters: dict[str, Any]) -> int:
15531662
"""
15541663
Returns the number of documents that match the provided filters.

0 commit comments

Comments
 (0)