跪拜 Guibai
← All articles
Frontend · Backend · Interview

Elasticsearch as a RAG Vector Store: Filtering Inside kNN, Bulk API Partial Failures, and Refresh Visibility

By 我是Allen ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Multi-tenant RAG deployments that filter after kNN can silently leak data across tenants and miss the correct chunks entirely; putting filters inside each kNN clause is the only way to keep the candidate set scoped. Elasticsearch's Bulk API and refresh semantics also catch out developers expecting an all-or-nothing write path.

Summary

RAG systems turn text into high-dimensional vectors, and the question is where to put them and how to find the nearest neighbors quickly. Vector databases exist for that job, but Elasticsearch steps in with hybrid search: BM25 for keywords and kNN for embeddings in one index, plus the ability to attach filters directly to the kNN sub-clauses.

The code shows a document with both title and content vectors, each 1024 dimensions, mapped as dense_vector with cosine similarity. Filters such as tenant and kb_id go inside every kNN clause to avoid cross-tenant leakage. Two common ES pitfalls get attention: Bulk requests can return HTTP 200 while individual items fail, so the errors and items statuses must be inspected; and writes aren't searchable until a refresh, which the code triggers explicitly in the reimport flow.

The trade-offs are constant: dedicated vector databases versus extending a database you already run, or managed services versus self-hosting.

Takeaways
— Embeddings in FastRAG are 1024-dimensional vectors.
— HNSW, IVF, PQ, and LSH are common ANN index structures, each trading speed and accuracy.
— Cosine, dot product, and Euclidean distance are the three similarity metrics; choice must match embedding model normalization.
— ES mapping uses dense_vector with dims=1024 and similarity=cosine for vectors, keyword for exact filter fields, and text with IK analyzer for BM25.
— kNN sub-clauses must include filter conditions; otherwise, each clause can recall across tenants.
— num_candidates must be >= k or ES returns a 400 error.
— Bulk API returns HTTP 200 even when some items fail; the errors field and item statuses need checking.
— Successful items in a Bulk request are not rolled back if other items fail.
— Writes are not searchable until the next refresh (refresh_interval=30s); the code calls refresh explicitly before delete_by_query and sets refresh=true on the delete request.
— ES native RRF is not available in the Basic license; the project implements fusion at the application layer.
Conclusions

Using Elasticsearch for vector storage is a pragmatic move when you already run it: it gives you BM25 and kNN in one query, but the Basic license's lack of native RRF forces you to implement result fusion yourself.

Filtering inside each kNN clause is mandatory for multi-tenant isolation; filtering after retrieval cannot recover chunks that never made the candidate list, so the only correct place for the filter is inside the search itself.

The Bulk API's partial-failure behavior means write success must be checked per item, and since successful items aren't rolled back, an import operation needs its own deduplication or idempotency strategy.

ES's refresh semantics separate 'written' from 'searchable'; any system that needs immediate consistency after writes has to explicitly trigger a refresh or wait for the interval.

Concepts & terms
ANN (Approximate Nearest Neighbor)
A search technique that trades exactness for speed, used by vector databases to find similar vectors within an acceptable error range.
HNSW (Hierarchical Navigable Small World)
A graph-based index that links similar vectors across layers, quickly approximating from coarse to fine during search.
IVF (Inverted File Index)
Partitions vector space into clusters and searches only the most relevant clusters at query time; good for large-scale but lower-precision needs.
PQ (Product Quantization)
Compresses high-dimensional vectors by splitting into subspaces and quantizing, saving memory and speeding up distance computation.
RRF (Reciprocal Rank Fusion)
A method to combine multiple result lists by summing reciprocal ranks; ES's native RRF is unavailable in the Basic license.
From the discussion

The supplementary discussion centers on four concrete operational traps when using Elasticsearch for RAG: multi-field kNN score addition skewing ranking, non-comparable BM25 and kNN scores forcing fake fusion, the heavy memory burden of 1024-bit float32 vectors, and a default num_candidates that is too small. The article's practical choice of ES and its emphasis on batch-write timeout/retry receive direct agreement. Opinions don't conflict; the comments extend the article's content with real experience rather than contesting it.

— Multi-field kNN score addition lets a slice that hits in both title and content dominate the ranking, so per-clause boosts or rank-based fusion (RRF) must replace plain score addition.
— BM25 and kNN scores occupy different scales (unbounded term frequency vs. bounded similarity), making direct summation a fake fusion that requires normalization or RRF.
— The memory cost of 1024-dim float32 vectors is 4KB each, so 1M slices alone consume 4GB plus HNSW graph overhead; int8_hnsw quantization, dimensionality reduction, or sharding all become necessary at scale.
— The default num_candidates is too small, and increasing it (e.g., to 200) often restores missing relevant snippets at far lower cost than replacing the embedding model.
— The article's kNN syntax and runnable examples make it immediately actionable, and the batch-write timeout/retry advice is essential because skipping it leads to failures down the road.
Featured comments
stormsha 1 likes

This article makes clear that a vector store is just storage + indexing + retrieval. I'll add a few pitfalls you'll actually hit on ES: 1) **Adding scores from multiple kNN fields lets 'double hits' top the ranking**. If the same slice hits in both title and content, its score is roughly twice that of a single hit, distorting order directly. Either give each subclause a `boost` to control weight, or fuse by rank (RRF) instead of summing scores. The author mentions the basic version has no native RRF and fusion happens in the application layer—in that case especially, fuse by rank, not by score. 2) **BM25 and kNN scores are not comparable**. One is term-frequency scoring (no upper bound), the other is similarity (in the 0–1 range). Adding them directly is a 'fake fusion'; you must normalize or use RRF first. This is the most common hidden bug in hybrid search: the result doesn't error, just ranks inexplicably. 3) **The memory math for 1024 dims × float32 needs to be done up front**: a single vector is 4KB, so 1M slices is 4GB just for vectors, and HNSW also stores graph structure on top. To really scale, go `int8_hnsw` quantization, reduce dimensions, or shard. ES's `m` / `ef_construction` are tuned for recall, not the bigger the better (both build time and memory grow). 4) **The default `num_candidates` is on the small side**. The symptom is 'clearly there are more relevant snippets but they aren't returned'—many people's first reaction is to suspect the embedding model, but it's actually the candidate set being too small. Bump it up and check the effect; the cost is far lower than swapping models. I've stepped on #4 myself: swapped two versions of embeddings with no improvement, and it only worked after raising `num_candidates` from the default to 200.

我是Allen

Thanks for the supplement.

去吧波波鸟

Choosing ES as the vector store is a solid pick; the kNN syntax and full runnable examples are laid out, so you can just follow along and run it. The timeout-and-retry for batch writes is well raised—if you don't write it, trouble comes sooner or later.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗