Hybrid keyword and semantic search: RRF

Updated at:

In AI knowledge bases (RAG), code search, and product search, keyword search is good at precisely hitting proper nouns such as model numbers, order IDs, and error codes, while vector search is good at understanding synonyms and colloquial expressions. Agentic ES supports retriever.rrf (Reciprocal Rank Fusion), which runs full-text and vector retrieval within a single _search request and fuses the most relevant results without manual weight tuning.

Note

All API examples in this topic provide CONSOLE / CURL / GO / PYTHON / JAVASCRIPT / JAVA code tabs (CONSOLE can be copied directly into Kibana Dev Tools and run). The examples build on Quick start, reusing the demo-knowledge-chunks collection and the sample data created there.

1. Why use RRF for hybrid search

Keyword search alone tends to miss synonyms and colloquial expressions, while vector search alone tends to misjudge proper nouns such as model numbers, order IDs, and error codes. If you merge the two result sets in the application layer, you usually need to normalize them repeatedly and tune the weights manually, because full-text BM25 scores have no fixed upper bound while vector cosine scores are fixed in [0, 1], so a direct sum is easily dominated by one path.

Using retriever.rrf brings three direct benefits:

  • No weight tuning, ready to use: Fusion is based only on ranks rather than raw scores, which naturally eliminates the scale difference between BM25 scores and vector scores. You do not need to retune the weights after you change the model or the dataset.

  • Fusion completed on the server side in a single request: This saves the network round trips and merge code that would otherwise be required to send two queries from the application layer and deduplicate, sort, and truncate the pages yourself.

  • Significantly improved Top-K hit quality: Documents that match both the keyword and the semantics are automatically ranked first, and documents that are highly relevant in a single path are still reasonably recalled.

At execution time, the server runs keyword search (standard) and vector search (knn) in parallel, takes the top-ranked results from each path, computes a fusion score of 1 / (rank_constant + rank), and aggregates the ranking.

image

Concrete scoring example (default rank_constant = 60): Suppose a user searches for "I bought the wrong item and want a refund (model A100)". The two paths each take the top 10 candidates from the knowledge base, and the ranks of three representative documents are as follows:

Document

Keyword search rank

Vector semantic rank

RRF fusion score

Final rank

"A100 Return and Refund Policy"

Rank 2 (contains A100, but with a lower term frequency than the specifications)

Rank 3 (semantically relevant, but less focused than the general guide)

1/(60+2) + 1/(60+3) = 0.0320

Rank 1

"A100 Hardware Specifications"

Rank 1 (A100 appears frequently in the full text)

Not in the top 10 (unrelated to refunds)

1/(60+1) = 0.0164

Tied for rank 2

"Seven-Day No-Reason Return Guide"

Not in the top 10 (does not literally contain A100)

Rank 1 (semantically closest to "bought the wrong item, want a refund")

1/(60+1) = 0.0164

Tied for rank 2

As shown, keyword search alone would rank "A100 Hardware Specifications" first, and vector search alone would rank "Seven-Day No-Reason Return Guide" first. With RRF fusion, although "A100 Return and Refund Policy" is not first in either single path, it ranks high in both paths and is automatically ranked first without manual weight tuning, while highly relevant single-path documents are still reasonably recalled. For more details about the principle, see Elasticsearch documentation: Reciprocal Rank Fusion (RRF).

2. Run a full-text + vector hybrid search

The following example, within the kb-a slice, fuses keyword search (standard) and vector search (knn), and writes the scalar filter category = "after-sales" that both paths share at the top level of rrf.filter so that it takes effect on both paths at the same time:

CONSOLE

POST /demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false
{
  "retriever": {
    "rrf": {
      "retrievers": [
        {
          "standard": {
            "query": { "match": { "title": "refund" } }
          }
        },
        {
          "knn": {
            "field": "embedding",
            "query_vector": [0.80, 0.12, 0.05, 0.03],
            "k": 5,
            "num_candidates": 50
          }
        }
      ],
      "filter": { "term": { "category": "after-sales" } },
      "rank_window_size": 10,
      "rank_constant": 60
    }
  },
  "size": 5,
  "_source": ["title", "category"]
}

CURL

curl -u "$ES_USER:$ES_PASSWORD" -X POST \
  "$ES_ENDPOINT/demo-knowledge-chunks/_search?_slice=kb-a&allow_partial_search_results=false" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "retriever": {
    "rrf": {
      "retrievers": [
        {
          "standard": {
            "query": { "match": { "title": "refund" } }
          }
        },
        {
          "knn": {
            "field": "embedding",
            "query_vector": [0.80, 0.12, 0.05, 0.03],
            "k": 5,
            "num_candidates": 50
          }
        }
      ],
      "filter": { "term": { "category": "after-sales" } },
      "rank_window_size": 10,
      "rank_constant": 60
    }
  },
  "size": 5,
  "_source": ["title", "category"]
}
JSON

GO

res, err := client.Search().
	Index("demo-knowledge-chunks").
	Routing("kb-a").
	AllowPartialSearchResults(false).
	Retriever(&types.RetrieverContainer{
		Rrf: &types.RRFRetriever{
			Retrievers: []types.RRFRetrieverEntry{
				// Full-text search
				types.RetrieverContainer{
					Standard: &types.StandardRetriever{
						Query: &types.Query{
							Match: map[string]types.MatchQuery{"title": {Query: "refund"}},
						},
					},
				},
				// Vector search
				types.RetrieverContainer{
					Knn: &types.KnnRetriever{
						Field:         "embedding",
						QueryVector:   []float32{0.80, 0.12, 0.05, 0.03},
						K:             5,
						NumCandidates: some.Int(50),
					},
				},
			},
			// The shared scalar filter is written at the top level of rrf.filter so that it applies to both the full-text and vector paths
			Filter:         []types.Query{{Term: map[string]types.TermQuery{"category": {Value: "after-sales"}}}},
			RankWindowSize: some.Int(10),
			RankConstant:   some.Int(60),
		},
	}).
	Size(5).
	SourceIncludes_("title", "category").
	Do(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Hits.Hits)

PYTHON

res = client.search(
    index="demo-knowledge-chunks",
    routing="kb-a",
    allow_partial_search_results=False,
    retriever={
        "rrf": {
            "retrievers": [
                {"standard": {"query": {"match": {"title": "refund"}}}},
                {
                    "knn": {
                        "field": "embedding",
                        "query_vector": [0.80, 0.12, 0.05, 0.03],
                        "k": 5,
                        "num_candidates": 50,
                    }
                },
            ],
            # The shared scalar filter is written at the top level of rrf.filter so that it applies to both the full-text and vector paths
            "filter": {"term": {"category": "after-sales"}},
            "rank_window_size": 10,
            "rank_constant": 60,
        }
    },
    size=5,
    source=["title", "category"],
)
print(res["hits"]["hits"])

JAVASCRIPT

const res = await client.search({
  index: 'demo-knowledge-chunks',
  routing: 'kb-a',
  allow_partial_search_results: false,
  retriever: {
    rrf: {
      retrievers: [
        { standard: { query: { match: { title: 'refund' } } } },
        {
          knn: {
            field: 'embedding',
            query_vector: [0.80, 0.12, 0.05, 0.03],
            k: 5,
            num_candidates: 50,
          },
        },
      ],
      // The shared scalar filter is written at the top level of rrf.filter so that it applies to both the full-text and vector paths
      filter: { term: { category: 'after-sales' } },
      rank_window_size: 10,
      rank_constant: 60,
    },
  },
  size: 5,
  _source: ['title', 'category'],
})
console.log(res.hits.hits)

JAVA

SearchResponse<Map> res = client.search(s -> s
    .index("demo-knowledge-chunks")
    .routing("kb-a")
    .allowPartialSearchResults(false)
    .retriever(r -> r.rrf(rrf -> rrf
        // Full-text search
        .retrievers(e -> e.retriever(sub -> sub.standard(st -> st
            .query(q -> q.match(mt -> mt.field("title").query("refund"))))))
        // Vector search
        .retrievers(e -> e.retriever(sub -> sub.knn(k -> k
            .field("embedding")
            .queryVector(0.80f, 0.12f, 0.05f, 0.03f)
            .k(5)
            .numCandidates(50))))
        // The shared scalar filter is written at the top level of rrf.filter so that it applies to both the full-text and vector paths
        .filter(f -> f.term(t -> t.field("category").value("after-sales")))
        .rankWindowSize(10)
        .rankConstant(60)))
    .size(5)
    .source(src -> src.filter(f -> f.includes("title", "category"))),
    Map.class);
System.out.println(res.hits().hits());

3. Key parameters and combined usage

  • rank_window_size (candidate set size of each path): Controls how many top results each of the keyword and vector paths contributes to the fusion. It must be greater than or equal to the outer size and is usually set based on the size at 2 to 5 times its value. For example, if you want the top 5 results in the end, set rank_window_size to 10 to 25.

  • rank_constant (smoothing constant, default 60): The smoothing baseline when the rank score of each path is computed as 1 / (rank_constant + rank). The default value 60 balances "an extremely high rank" and "a high rank in both paths", and generally does not need to be changed.

  • Combine scalar filters in RRF: When both paths share the same filter condition, write it at the top level of rrf.filter as in the preceding example so that it takes effect on both paths. If the two paths need different filter logic, write the filters separately in standard.query (bool.filter) and knn.filter.

  • Combine multi-slice queries and DiskBBQ tuning: RRF also supports multi-slice queries (such as ?_slice=kb-a,kb-b), and in the knn clause you can pass visit_percentage and rescore_vector (see Tune vector search accuracy and speed: DiskBBQ).

  • Plan concurrency quotas: Because RRF runs multiple sub-queries in parallel within a single request, it occupies multiple single-slice query concurrency slots (the single-slice limit is 16). Leave sufficient concurrency headroom in high-concurrency scenarios (see Migration guide, error codes, and FAQ).