跪拜 Guibai
← Back to the summary

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

From Scratch RAG: Storing and Retrieving Vectors with Elasticsearch

Preface

This is the fifth part of the FastRAG series. In the previous part, each chunk was encoded into a 1024-dimensional vector by an embedding model. The problem this part solves is: where are these vectors stored, and what structure is used to retrieve them?

The answer is a "vector database". It is responsible only for storing vectors, building indexes, and quickly recalling by similarity. In RAG, during a query, the user question is also encoded into a vector, and through the vector database we retrieve the top K chunks that are semantically closest, which serve as context for the generation model.

Why a Vector Database

Traditional databases' WHERE excels at exact matching and range queries: WHERE kb_id = 1 AND status = 2 gives a binary answer. But RAG queries are not written like that. A user inputs natural language such as "what are the influencing factors of pulmonary ventilation", and no row in the database matches that text verbatim. The real question is: which paragraphs are semantically closest to this sentence?

After an embedding model encodes text into vectors, this semantic-closeness question becomes: given a 1024-dimensional query vector, find the nearest points in high-dimensional space.

In non-relational databases, common data shapes can be distinguished as four types:

Vector retrieval adds the ability to search by semantic similarity; some existing databases also provide this capability through extensions. Dedicated vector databases bundle this kind of retrieval together with the basic features of traditional databases (storage management, filtering, scalability, backup and restore, ecosystem integration, and access control).

How a Vector Database Works

The core of a vector database is Approximate Nearest Neighbor search (ANN): rather than pursuing absolutely exact nearest neighbors, it finds sufficiently similar vectors at a cost far lower than a "brute force" scan, within an acceptable error margin.

The entire process can be split into five steps:

  1. Vectorization: text, images, audio, and other data go through an embedding model to become high-dimensional float vectors.
  2. Vector storage: vectors are written into the database along with metadata, preserving both the semantic representation and interpretable fields of the original information.
  3. Vector indexing: to enable fast retrieval on massive data, the database builds a special index structure.
  4. Vector search: at query time, the question is first encoded into a vector, then ANN search is done on the index.
  5. Data retrieval and post-processing: based on the hit documents, read the original text and metadata stored with the vectors, then sort, filter, and truncate according to business needs.

image.png

Figure 1: At import time, chunks are saved and indexes built; at query time, the same embedding model encodes the question and recalls fragments within a limited scope.

Vector Index Structures

These indexes all trade off speed and precision. HNSW is one common choice; PQ is often combined with IVF or HNSW to save memory; LSH is considered only in specific scenarios.

Similarity Metrics

The choice of metric should align with the embedding model's training method and whether it is normalized. There are three common ones:

Why Elasticsearch

Elasticsearch, mainly for three reasons:

  1. The author has experience with it, local Docker deployment is easy, and it allows quick verification and learning.
  2. It supports hybrid retrieval: BM25 and kNN can be done in the same index, without needing to piece together a separate vector retrieval component.
  3. Complex filtering can be done before vector retrieval; conditions like tenant and knowledge base can be attached directly in the kNN clause, so filtering happens before nearest-neighbor search.

Note: ES's native RRF is not available in the Basic license. This project needs RRF to fuse multiple result streams; the fusion logic is written in the application layer, which will be detailed in the next part.

Code: FastRAG Chunk Storage

What a Chunk Looks Like in ES

At write time, the vector and metadata go into the same document:

Code: infrastructure/persistence/vector_store_es.go#L712

func vectorDocBody(d repository.VectorDoc) map[string]any {
	return map[string]any{
		constants.FieldTenant:      d.Tenant,
		constants.FieldKbId:        d.KBID,
		constants.FieldDocId:       d.DocID,
		constants.FieldChunkId:     d.ChunkID,
		constants.FieldOrder:       d.Order,
		constants.FieldTitle:       d.Title,
		constants.FieldContent:     d.Content,
		constants.FieldHeadingPath: d.HeadingPath,
		constants.FieldTitleVec:    d.TitleVec,
		constants.FieldContentVec:  d.ContentVec,
		constants.FieldCreateTs:    d.CreateTs,
	}
}

tenant and kb_id scope the business range; doc_id points back to the MySQL document record; order preserves order within a document.

The title vector adds topic information, while the content vector preserves content details. The current implementation uses ES multi-field kNN to add the scores of two sub-clauses that hit the same chunk. This increases vector storage and retrieval costs, and its effectiveness needs to be benchmarked against a single-content-vector approach.

Mapping

The types of these fields are explicitly declared in the index script, divided into three categories: filter fields, full-text fields, and vector fields:

Code: scripts/create-es-index.sh#L69

{
  "properties": {
    "tenant":       { "type": "keyword" },
    "kb_id":        { "type": "long" },
    "doc_id":       { "type": "long" },
    "chunk_id":     { "type": "keyword" },
    "order":        { "type": "integer" },
    "title":        { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart" },
    "content":      { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart" },
    "heading_path": { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart" },
    "title_vec":    { "type": "dense_vector", "dims": 1024, "index": true, "similarity": "cosine" },
    "content_vec":  { "type": "dense_vector", "dims": 1024, "index": true, "similarity": "cosine" },
    "create_ts":    { "type": "long" }
  }
}

keyword keeps exact values for term filtering; text goes through IK tokenization for BM25; dense_vector builds a vector index with 1024 dimensions and cosine metric.

kNN Clause: Hand Filtering to the Nearest-Neighbor Search

Code: infrastructure/persistence/vector_store_es.go#L604

func (s *ESVectorStore) knnClauses(req repository.VectorSearchReq) []any {
	fields := []string{constants.FieldTitleVec, constants.FieldContentVec}

	k := req.KNNTops
	numCandidates := req.NumCandidates
	if numCandidates < k {
		// num_candidates must be >= k, otherwise ES returns 400.
		numCandidates = k
	}

	out := make([]any, 0, len(fields))
	for _, f := range fields {
		out = append(out, map[string]any{
			"field":          f,
			"query_vector":   req.QueryVec,
			"k":              k,
			"num_candidates": numCandidates,
			// filter must be attached to every sub-clause, not just the outer request.
			// Missing one = that clause recalls across tenants, and tenant isolation leaks half.
			"filter": s.filters(req),
		})
	}
	return out
}

k is the number of nearest neighbors to return; num_candidates is the number of candidates explored in the underlying graph per shard. Increasing it usually helps recall but also adds computational cost. The key point is that each clause carries a filter, with the filter conditions derived from the same method:

Code: infrastructure/persistence/vector_store_es.go#L634

func (s *ESVectorStore) filters(req repository.VectorSearchReq) []any {
	out := []any{
		map[string]any{"term": map[string]any{constants.FieldTenant: req.Tenant}},
	}
	if len(req.KBIDs) > 0 {
		out = append(out, map[string]any{"terms": map[string]any{constants.FieldKbId: req.KBIDs}})
	}
	return out
}

Putting the filter inside the kNN clause means "first limit the scope, then find the most similar within it"; searching first and filtering later means "search all over the index, and after filtering you find that what you wanted never made the candidate list."

If you fetch Top K from the entire library and then filter to the current tenant, other tenants' hits can fill the quota, and the correct chunk never enters the candidate set. Also, title and content are two independent sub-clauses; if only one gets a filter, the other still recalls across scope.

image.png

Figure 2: With K = 3 as an example, post-recall filtering can only delete hits from other tenants; it cannot bring back chunks that never entered the candidate list. Filtering must be placed in every kNN sub-clause.

Bulk: HTTP 200 Doesn't Mean Everything Was Written

Writes use Bulk batch; _id uses chunk_id, so same IDs overwrite, distinct IDs add new entries:

Code: infrastructure/persistence/vector_store_es.go#L51

var buf bytes.Buffer
for _, d := range docs {
	if err := writeJSONLine(&buf, map[string]any{
		"index": map[string]any{"_index": s.index, "_id": d.ChunkID},
	}); err != nil {
		return err
	}
	if err := writeJSONLine(&buf, vectorDocBody(d)); err != nil {
		return err
	}
}

res, err := s.client.Bulk(&buf, s.client.Bulk.WithContext(ctx))
if err != nil {
	return apperrors.ErrVectorStoreFailed.Wrap(err)
}
defer res.Body.Close()

if res.IsError() {
	return apperrors.NewSysError(apperrors.CodeVectorStoreFail,
		fmt.Sprintf("bulk request failed: %s", readBody(res.Body)))
}

// bulk pitfall: when an individual item fails, the HTTP status is still 200, and the error is hidden in items.
// Without checking the errors field, the import "succeeds" but half the chunks never went in.
var parsed struct {
	Errors bool `json:"errors"`
	Items  []map[string]struct {
		Status int `json:"status"`
	} `json:"items"`
}
if err := json.NewDecoder(res.Body).Decode(&parsed); err != nil {
	return apperrors.ErrVectorStoreFailed.Wrap(err)
}
if !parsed.Errors {
	return nil
}

failed := 0
for _, item := range parsed.Items {
	for _, r := range item {
		if r.Status >= 300 {
			failed++
		}
	}
}
return apperrors.NewSysError(apperrors.CodeVectorStoreFail, fmt.Sprintf(
	"bulk partial failure: %d/%d items", failed, len(docs)))

The pitfall of Bulk is that HTTP 200 does not mean every item succeeded. Dimensional mismatch, zero-norm vectors, or mapping errors can make a single item fail, yet the entire request still returns 200. So you must check the errors field and the status codes in items.

Conversely, even if Bulk returns an error, already successful items are not rolled back. The write side cannot rely on a single boolean to judge the write state.

image.png

Figure 3: An HTTP 200 response can still contain failed items; checking errors and items identifies partial failures, and successful items are not automatically rolled back.

refresh: Between a Successful Write and Being Searchable There Is One Step

ES writes go into memory first and become searchable only after a refresh; the index script sets refresh_interval=30s. So if something is not found right after writing, it may simply not have been refreshed yet.

Code: infrastructure/persistence/vector_store_es.go#L119

func (s *ESVectorStore) Refresh(ctx context.Context) error {
	res, err := s.client.Indices.Refresh(
		s.client.Indices.Refresh.WithContext(ctx),
		s.client.Indices.Refresh.WithIndex(s.index),
	)

	if err != nil {
		return apperrors.ErrVectorStoreFailed.Wrap(err)
	}
	defer res.Body.Close()

	if res.IsError() {
		return apperrors.NewSysError(apperrors.CodeVectorStoreFail,
			fmt.Sprintf("failed to refresh index: %s", readBody(res.Body)))
	}
	return nil
}

Refresh applies to the entire index, not a single document. In the reimport flow, there are two places that need attention:

Summary

The difficulty of a vector database is not in demo code, but in making selection and trade-offs combined with business: use a dedicated vector database, or reuse the vector capabilities of an existing database? Self-host, or go with a managed cloud service?

If you want peace of mind, managed services are a good choice; but if you truly want to understand the underlying principles of vector retrieval, it's worth setting up your own and writing it yourself.

Full code: PycMono/FastRAG.

Comments

Top 2 of 3 from juejin.cn, machine-translated. The original thread is authoritative.

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.