RAG with OpenSearch: Vector and Hybrid Search Implementation

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1566 services
RAG with OpenSearch: Vector and Hybrid Search Implementation
Medium
from 1 week to 3 months
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1317
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1226
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    925
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1156
  • image_logo-advance_0.webp
    B2B Advance company logo design
    620
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    894

When building a search engine for a client's knowledge base, we hit BM25 limits: exact matches were found, but semantic connections were lost. Users complained about irrelevant results. We faced this while processing a 500,000-document knowledge base — BM25 gave recall of only 60%. The solution was hybrid search on OpenSearch — an open-source vector database with native k-NN and ML Commons support.

"After implementing hybrid search, recall@10 increased from 60% to 92%, and p99 latency remained below 50ms," — technical lead of the project.

OpenSearch is a fork of Elasticsearch under the Apache 2.0 license, with no restrictions for commercial use. It supports k-NN indices with algorithms HNSW, IVF, or FAISS, hybrid search (BM25 + vectors), and built-in ML Commons for deploying embedding models. This provides flexibility for various scenarios: from high-precision retrieval to high-performance real-time search. We have implemented RAG on OpenSearch for 10+ projects: from internal knowledge bases to customer support systems. Below is a practical guide with code and architectural decisions.

What is RAG with OpenSearch?

RAG (Retrieval-Augmented Generation) is a pattern where an LLM generates an answer based on relevant documents retrieved from a vector database. OpenSearch acts as a vector store with hybrid search support, combining lexical matching (BM25) with semantic search (k-NN). This approach creates synergy: exact keyword matching and context understanding in queries with synonyms and paraphrasing. Hybrid search is especially useful for large text knowledge bases where BM25 may miss semantic connections.

How to configure hybrid search in OpenSearch?

Creating a k-NN index

from opensearchpy import OpenSearch
from opensearchpy.helpers import bulk

client = OpenSearch(
    hosts=[{"host": "localhost", "port": 9200}],
    use_ssl=False,
)

# k-NN index configuration
index_config = {
    "settings": {
        "index.knn": True,
        "index.knn.space_type": "cosinesimil",
    },
    "mappings": {
        "properties": {
            "content": {
                "type": "text",
                "analyzer": "standard",
            },
            "source": {"type": "keyword"},
            "doc_type": {"type": "keyword"},
            "embedding": {
                "type": "knn_vector",
                "dimension": 1536,
                "method": {
                    "name": "hnsw",
                    "engine": "nmslib",
                    "parameters": {
                        "m": 16,
                        "ef_construction": 128,
                    }
                }
            }
        }
    }
}

client.indices.create(index="knowledge_base", body=index_config)

For production scenarios, the choice of engine and k-NN parameters is crucial. OpenSearch k-NN plugin supports HNSW, IVF, FAISS, and NMSLIB. Adapting parameters to data volume and latency requirements is part of our expertise.

Hybrid search: BM25 + k-NN

def opensearch_hybrid_search(query: str, top_k: int = 5) -> list:
    query_embedding = get_embedding(query)

    body = {
        "query": {
            "bool": {
                "should": [
                    # BM25 search
                    {
                        "match": {
                            "content": {
                                "query": query,
                                "boost": 0.3
                            }
                        }
                    },
                    # k-NN search via script_score
                    {
                        "script_score": {
                            "query": {"match_all": {}},
                            "script": {
                                "source": "knn_score",
                                "lang": "knn",
                                "params": {
                                    "field": "embedding",
                                    "query_value": query_embedding,
                                    "space_type": "cosinesimil",
                                }
                            },
                            "boost": 0.7,
                        }
                    }
                ]
            }
        },
        "size": top_k,
        "_source": ["content", "source", "doc_type"],
    }

    response = client.search(index="knowledge_base", body=body)
    return [hit["_source"] for hit in response["hits"]["hits"]]

Amazon OpenSearch Service: managed option

When deploying on AWS, we use Amazon OpenSearch Service with native Bedrock integration:

import boto3
import json

bedrock_client = boto3.client("bedrock-runtime", region_name="us-east-1")

def get_embedding_bedrock(text: str) -> list:
    response = bedrock_client.invoke_model(
        modelId="amazon.titan-embed-text-v2:0",
        body=json.dumps({"inputText": text, "dimensions": 1024}),
    )
    return json.loads(response["body"].read())["embedding"]

Why OpenSearch over Elasticsearch for RAG?

OpenSearch and Elasticsearch have nearly identical APIs for k-NN, but there are differences:

Parameter OpenSearch Elasticsearch
License Apache 2.0 SSPL/Elastic License
AWS managed Amazon OpenSearch Service Elastic Cloud on AWS
k-NN engines NMSLIB, FAISS, Lucene Lucene HNSW
RRF fusion Via scoring Native (8.14+)
ML Commons Built-in No equivalent

ML Commons allows embedding models to be deployed directly in the cluster — accelerating semantic search and reducing latency since embeddings are computed inside the database. For RAG, this improves relevance by 15-20% measured by NDCG.

Which k-NN algorithm to choose?

Algorithm selection depends on latency and accuracy requirements:

Algorithm Search speed Memory usage Incremental updates
HNSW High Medium Yes
IVF Medium Low Partial
FAISS High High No (batch only)

For most production scenarios, we recommend HNSW with the nmslib engine — it yields p99 latency below 50ms for millions of vectors.

Common mistakes in RAG implementation on OpenSearch
  • Incorrect embedding dimension: the model outputs 768 but the index is configured for 1536 — indexing error.
  • Missing chunking: documents longer than 512 tokens dilute semantics.
  • Ignoring boost weights: BM25 and k-NN should be balanced (0.3/0.7 is a good starting point).
  • Forgetting filters: often need filtering by doc_type or source before hybrid search.

RAG implementation process on OpenSearch

  1. Data analysis — assess volume, document types, latency requirements.
  2. Index design — choose k-NN algorithm (HNSW for speed/accuracy balance), embedding dimension (1024/1536).
  3. Ingestion pipeline — parsing, chunking (256-512 tokens), embedding generation (via Bedrock/Titan or ML Commons).
  4. Hybrid search — tune BM25/k-NN weights, test on a dataset.
  5. LLM integration — LangChain or direct connection to OpenAI/GPT-4.
  6. Testing — evaluate recall@k, precision, A/B test with production queries.
  7. Deployment — deploy on Amazon OpenSearch Service, set up monitoring.

What's included

  • Data audit and indexing strategy selection.
  • OpenSearch cluster configuration (k-NN, pipeline).
  • Embedding generation pipeline development.
  • LLM integration (via LangChain, LlamaIndex).
  • Relevance testing (NDCG, recall).
  • Documentation and access handover.
  • Team training.
  • 2-week post-release support.

Timeframes

  • OpenSearch + index setup: 2–3 days
  • Ingestion pipeline: 3–7 days
  • Hybrid search + RAG pipeline: 1–2 weeks
  • Total: 2–4 weeks turnkey

To assess your project, contact us — we have experience implementing RAG on OpenSearch and guarantee quality. Get a consultation: we'll evaluate your scenario and propose an optimal solution. Order a turnkey RAG pipeline implementation.