Search Tutorials
--Ads--Vector Search with Elasticsearch and OpenSearch
kNN vector search and hybrid queries in Elasticsearch, OpenSearch and Amazon OpenSearch Service.
Many organisations already run Elasticsearch or OpenSearch for logs and site search. Both now support approximate k-nearest-neighbour (kNN) vector search alongside their mature keyword search, so they can serve as the retrieval layer for RAG without adding another database. This lesson shows how to create a vector index, index chunks, and run filtered kNN and hybrid queries in Elasticsearch, OpenSearch and Amazon OpenSearch Service.
What you will learn
- How to map a
dense_vectorfield in Elasticsearch and aknn_vectorfield in OpenSearch - How to run kNN queries with filters in both engines
- How to combine keyword and vector search with RRF in Elasticsearch
- How to connect to Amazon OpenSearch Service with AWS credentials
Prerequisites
- Hybrid Search with BM25 and Reciprocal Rank Fusion
- A running Elasticsearch or OpenSearch cluster (local Docker or managed)
Query bodies follow the Elasticsearch 9.x and OpenSearch documentation of November 2026. The Python calls pass those bodies as keyword arguments, which is how both clients work; they have not been executed against a live cluster for this tutorial. Features and licences differ between versions and distributions, so check your cluster's documentation, especially for hybrid search and RRF.
Part A: Elasticsearch
pip install "elasticsearch>=9" sentence-transformers
Use a client major version that matches your cluster: the 9.x client works with Elasticsearch 9.x and 10.x, and the 8.x client with 8.x and 9.x.
Create the index
import os
from elasticsearch import Elasticsearch, helpers
from rag_helpers import embed
es = Elasticsearch(hosts=[os.environ["ELASTICSEARCH_URL"]], api_key=os.environ["ELASTIC_API_KEY"])
INDEX = "rag-chunks"
es.indices.create(index=INDEX, mappings={
"properties": {
"text": {"type": "text"}, # BM25 keyword search
"embedding": {"type": "dense_vector", "dims": 384, "similarity": "cosine"},
"doc_id": {"type": "keyword"},
"tenant_id": {"type": "keyword"},
"allowed_groups": {"type": "keyword"},
"source": {"type": "keyword"},
}
})
A dense_vector field is indexed for approximate kNN by default. Recent versions also quantise vectors automatically to save memory; see the index_options section of the dense_vector documentation to choose a specific type.
Index chunks
CHUNKS = [
{"doc_id": "hr-leave", "text": "Employees get 18 days of paid leave in their first year.",
"tenant_id": "acme", "allowed_groups": ["staff"], "source": "leave-policy.md"},
{"doc_id": "it-vpn", "text": "Error VPN-403 means your device certificate has expired.",
"tenant_id": "acme", "allowed_groups": ["staff"], "source": "vpn-guide.md"},
]
vectors = embed([c["text"] for c in CHUNKS])
helpers.bulk(es, ({"_index": INDEX, "_id": f"{c['doc_id']}#0", **c, "embedding": vectors[i].tolist()}
for i, c in enumerate(CHUNKS)), refresh=True)
Filtered kNN search
Put the permission filter inside the knn clause. It is then applied while candidates are gathered, so you still get k results that the user may see:
def es_knn(question: str, tenant_id: str, groups: list[str], k: int = 5) -> list[dict]:
response = es.search(index=INDEX, knn={
"field": "embedding",
"query_vector": embed(question, query=True)[0].tolist(),
"k": k,
"num_candidates": 100, # more candidates: better recall, slower
"filter": {"bool": {"filter": [{"term": {"tenant_id": tenant_id}},
{"terms": {"allowed_groups": groups}}]}},
}, source=["doc_id", "text", "source"])
return [hit["_source"] | {"score": hit["_score"]} for hit in response["hits"]["hits"]]
Hybrid search with RRF
An RRF retriever runs a keyword query and a kNN query and fuses their rankings. The same filter must be applied to both branches:
def es_hybrid(question: str, tenant_id: str, groups: list[str], k: int = 5) -> list[dict]:
permission = [{"term": {"tenant_id": tenant_id}}, {"terms": {"allowed_groups": groups}}]
response = es.search(index=INDEX, size=k, retriever={"rrf": {
"retrievers": [
{"standard": {"query": {"bool": {"must": {"match": {"text": question}}, "filter": permission}}}},
{"knn": {"field": "embedding", "query_vector": embed(question, query=True)[0].tolist(),
"k": 50, "num_candidates": 100, "filter": {"bool": {"filter": permission}}}},
],
"rank_window_size": 50,
}})
return [hit["_source"] for hit in response["hits"]["hits"]]
RRF availability can depend on your Elasticsearch version and subscription; if it is not available, run the two searches separately and fuse them in Python with the rrf function from Hybrid Search.
Part B: OpenSearch
pip install opensearch-py sentence-transformers
Create a k-NN index
import os
from opensearchpy import OpenSearch
from rag_helpers import embed
client = OpenSearch(
hosts=[{"host": os.environ["OPENSEARCH_HOST"], "port": 9200}],
http_auth=(os.environ["OPENSEARCH_USER"], os.environ["OPENSEARCH_PASSWORD"]),
use_ssl=True, verify_certs=True,
)
INDEX = "rag-chunks"
client.indices.create(index=INDEX, body={
"settings": {"index": {"knn": True, "knn.algo_param.ef_search": 100}},
"mappings": {"properties": {
"text": {"type": "text"},
"embedding": {
"type": "knn_vector", "dimension": 384, "space_type": "l2",
"method": {"name": "hnsw", "engine": "faiss", "parameters": {"ef_construction": 128, "m": 24}},
},
"tenant_id": {"type": "keyword"},
"allowed_groups": {"type": "keyword"},
}},
})
The embeddings from rag_helpers.embed are normalised to length 1, so L2 distance ranks results exactly like cosine similarity. ef_search, ef_construction and m are the HNSW parameters explained in Vector Index Types.
Filtered k-NN query
def os_knn(question: str, tenant_id: str, groups: list[str], k: int = 5) -> list[dict]:
body = {"size": k, "query": {"knn": {"embedding": {
"vector": embed(question, query=True)[0].tolist(),
"k": k,
"filter": {"bool": {"must": [{"term": {"tenant_id": tenant_id}},
{"terms": {"allowed_groups": groups}}]}},
}}}}
response = client.search(index=INDEX, body=body)
return [hit["_source"] for hit in response["hits"]["hits"]]
A filter inside the field clause uses OpenSearch's efficient filtering (supported by the lucene, faiss and jvector engines). A top-level post_filter instead runs after the vector search and can return fewer than k results. OpenSearch also supports hybrid keyword-plus-vector queries through search pipelines; see its hybrid search documentation.
Amazon OpenSearch Service
On AWS, sign requests with your IAM credentials instead of a password:
import boto3
from opensearchpy import OpenSearch, RequestsAWSV4SignerAuth, RequestsHttpConnection
credentials = boto3.Session().get_credentials()
auth = RequestsAWSV4SignerAuth(credentials, "us-east-1", "es") # "aoss" for OpenSearch Serverless
aws_client = OpenSearch(hosts=[{"host": os.environ["OPENSEARCH_DOMAIN_HOST"], "port": 443}],
http_auth=auth, use_ssl=True, verify_certs=True,
connection_class=RequestsHttpConnection, pool_maxsize=20)
When to choose a search engine for RAG
| Good fit | Less ideal |
|---|---|
| You already operate Elasticsearch or OpenSearch | You need the simplest possible stack for a small corpus |
| Keyword search, facets, highlighting and analysers matter | You want vector-first features and tuning above all |
| You need hybrid search over large, mixed data | Your team has no search-engine operations experience |
Common errors and troubleshooting
- Dimension mismatch errors: the vector length differs from
dims/dimensionin the mapping. - Fewer results than expected: you used a post-filter; move the filter into the kNN clause.
- Client errors after an upgrade: client and server major versions are incompatible.
- 403 on Amazon OpenSearch: the IAM identity is not mapped in the domain's access policy or fine-grained access control.
Key takeaways
- Elasticsearch uses
dense_vectorfields andknnsearches; OpenSearch usesknn_vectorfields andknnqueries. - Put permission filters inside the kNN clause in both engines.
- Elasticsearch's RRF retriever fuses keyword and vector results; OpenSearch offers hybrid queries through search pipelines.
- On AWS, sign OpenSearch requests with IAM credentials.
Frequently asked questions
Can Elasticsearch create embeddings itself?
Yes, both engines can run or call embedding models during ingestion and search (inference endpoints in Elasticsearch, ML connectors in OpenSearch). This lesson embeds in Python to keep the model consistent with the rest of the tutorial.
Is OpenSearch the same as Elasticsearch?
OpenSearch started as a fork of Elasticsearch 7.10. They share concepts but have diverged in APIs, features and licensing, so use the client and documentation for the engine you run.
Practice exercises
- Index the same chunks in Elasticsearch and compare kNN-only and RRF hybrid results for questions containing codes.
- Measure recall@10 for
num_candidatesvalues of 50, 100 and 500 on your test set.
Related tutorials
- Azure AI Search for RAG
- Qdrant Tutorial for RAG
- Deploying RAG on AWS