Home / AI & GenAI / Vector Databases

AI & GenAICheat sheetIntermediate

Elasticsearch vector search cheat sheet: dense_vector mappings, kNN queries, filters, hybrid RRF and index health

The Elasticsearch calls for running a RAG vector index - dense_vector mappings, quantization options, bulk loads, filtered kNN, hybrid RRF retrievers, alias swaps and health checks.

Deepak Bhardwaj8 min read

Applies toElasticsearch 8.12+ and 9.x, self-managed and Elastic Cloud (defaults, retrievers and quantization options vary by version and license)

How to use this sheet

The calls use curl against a cluster with basic auth. In Kibana Dev Tools, drop the curl wrapper and keep the method, path and body.

export ES=https://es-prod:9200
alias escurl='curl -s -u elastic:$ES_PW -H "Content-Type: application/json"'
escurl "$ES/"            # check version.number before you copy anything below

Tip

The default index_options for dense_vector has changed several times. Older 8.x releases used hnsw, later 8.x used int8_hnsw for float vectors, and 9.x uses bbq_hnsw for float vectors with 384 or more dimensions. Set index_options explicitly so the index behaves the same whichever version created it.

Mappings

A RAG chunk index

escurl -X PUT "$ES/rag-docs-v1" -d '{
  "settings": { "number_of_shards": 1, "number_of_replicas": 1 },
  "mappings": {
    "properties": {
      "embedding": {
        "type": "dense_vector",
        "dims": 1536,
        "index": true,
        "similarity": "cosine",
        "index_options": { "type": "int8_hnsw", "m": 16, "ef_construction": 100 }
      },
      "content":    { "type": "text" },
      "title":      { "type": "text" },
      "doc_id":     { "type": "keyword" },
      "chunk_id":   { "type": "keyword" },
      "tenant":     { "type": "keyword" },
      "acl_groups": { "type": "keyword" },
      "updated_at": { "type": "date" }
    }
  }
}'

dims must match the embedding model's output exactly. Map every field you filter on (tenant, acl_groups, dates) as keyword or date, not text.

Mapping options

Option Values Notes
similarity cosine, dot_product, l2_norm, max_inner_product dot_product needs unit-length vectors; use cosine if you're not sure
index_options.type hnsw, int8_hnsw, int4_hnsw, bbq_hnsw, flat, int8_flat, int4_flat, bbq_flat Quantized types use less memory; availability varies by version
m default 16 Graph connections per node. Higher means better recall, more memory
ef_construction default 100 Build-time candidate list. Higher means slower indexing and better graphs
index: false Stores vectors but builds no HNSW graph, so only brute-force script_score works

HNSW search runs fast only when the vectors fit in the operating system page cache, outside the JVM heap. Elastic's tuning guide gives these approximate sizes for each vector field:

Type Approximate bytes
float (hnsw) num_vectors * 4 * (dims + 12)
int8_hnsw num_vectors * (dims + 4)
bbq_hnsw num_vectors * (dims / 8 + 14)

So 10 million 1,536-dimension vectors need about 61 GB as float and about 15 GB as int8_hnsw, summed across the nodes that hold the shards. Leave that much RAM free beyond the heap.

Loading data

Settings for a bulk load

escurl -X PUT "$ES/rag-docs-v1/_settings" -d '{
  "index": { "refresh_interval": "-1", "number_of_replicas": 0 }
}'

# NDJSON file: action line + document line, file must end with a newline
curl -s -u elastic:$ES_PW -H "Content-Type: application/x-ndjson" \
  -X POST "$ES/_bulk" --data-binary @chunks.ndjson | jq '.errors'

escurl -X PUT "$ES/rag-docs-v1/_settings" -d '{
  "index": { "refresh_interval": "1s", "number_of_replicas": 1 }
}'
escurl -X POST "$ES/rag-docs-v1/_refresh"

A _bulk response with HTTP 200 can still contain failed items. Always check .errors, and if it's true, list the failures:

jq '.items[] | select(.index.error) | .index.error.reason' bulk-response.json | sort | uniq -c

Python bulk helper

from elasticsearch import Elasticsearch, helpers

es = Elasticsearch("https://es-prod:9200", basic_auth=("elastic", pw))
actions = ({"_index": "rag-docs-v1", "_id": c["chunk_id"], "_source": c} for c in chunks)
ok, errors = helpers.bulk(es, actions, chunk_size=500, raise_on_error=False)
print(ok, len(errors))

Use chunk_id as _id so a re-run overwrites the same documents instead of adding duplicates.

Force merge after the load

Every segment has its own HNSW graph, and each one is searched separately. After a one-off load into an index that won't get more writes, merge the segments:

escurl "$ES/_cat/segments/rag-docs-v1?v&h=shard,segment,docs.count,size" | wc -l
escurl -X POST "$ES/rag-docs-v1/_forcemerge?max_num_segments=1"

Warning

Don't force merge an index that is still taking regular writes. The merge is I/O heavy, and the large segment it creates won't be merged away cleanly later. Run it out of hours on a newly built index, before you move the alias onto it.

Queries

Approximate kNN

escurl -X POST "$ES/rag-docs/_search" -d '{
  "knn": {
    "field": "embedding",
    "query_vector": [0.012, -0.044, 0.031],
    "k": 10,
    "num_candidates": 100
  },
  "_source": ["doc_id", "chunk_id", "title", "content"]
}'

Each shard collects num_candidates and the top k are returned. To improve recall, raise num_candidates (for example 50 to 200, up to the 10,000 limit) before you change m. You can also add "similarity": 0.75 to drop results below a minimum score.

Filtered kNN

escurl -X POST "$ES/rag-docs/_search" -d '{
  "knn": {
    "field": "embedding",
    "query_vector": [0.012, -0.044, 0.031],
    "k": 10,
    "num_candidates": 100,
    "filter": {
      "bool": {
        "filter": [
          { "term":  { "tenant": "acme" } },
          { "terms": { "acl_groups": ["sg-ops", "sg-all"] } },
          { "range": { "updated_at": { "gte": "now-365d" } } }
        ]
      }
    }
  }
}'
Where you put the filter What happens
knn.filter Applied during the graph search, so you still get k matching results
post_filter Applied after kNN, so you can get fewer than k results, or none
Top-level query next to knn Not a filter. The two scores are added together (hybrid)

Caution

For permission-aware RAG, put the ACL filter in knn.filter, and also in the query part of any hybrid request. If one side of a hybrid query is unfiltered, it will return documents the user is not allowed to see.

Hybrid with RRF retrievers

escurl -X POST "$ES/rag-docs/_search" -d '{
  "retriever": {
    "rrf": {
      "retrievers": [
        { "standard": { "query": { "bool": {
            "must":   { "match": { "content": "reset kubelet certificate" } },
            "filter": { "term":  { "tenant": "acme" } } } } } },
        { "knn": {
            "field": "embedding",
            "query_vector": [0.012, -0.044, 0.031],
            "k": 20, "num_candidates": 100,
            "filter": { "term": { "tenant": "acme" } } } }
      ],
      "rank_window_size": 50,
      "rank_constant": 60
    }
  },
  "size": 10
}'

Retrievers became generally available in 8.x. RRF may need a particular license tier on self-managed clusters, so check yours. If RRF is rejected, use a bool query plus a top-level knn, each with a boost, as a fallback.

Python query

resp = es.search(
    index="rag-docs",
    knn={"field": "embedding", "query_vector": qvec, "k": 10, "num_candidates": 100,
         "filter": {"term": {"tenant": "acme"}}},
    source=["doc_id", "chunk_id", "content"],
)
hits = [(h["_score"], h["_source"]["chunk_id"]) for h in resp["hits"]["hits"]]

Aliases for zero-downtime re-index

Applications query the rag-docs alias, never a versioned index name.

escurl -X POST "$ES/_aliases" -d '{
  "actions": [
    { "remove": { "index": "rag-docs-v1", "alias": "rag-docs" } },
    { "add":    { "index": "rag-docs-v2", "alias": "rag-docs" } }
  ]
}'
escurl "$ES/_cat/aliases/rag-docs?v"

Both actions run atomically. Keep rag-docs-v1 until the new index passes your recall checks, because rolling back is the same call with the index names swapped.

Health checks

escurl "$ES/_cluster/health/rag-docs-*?pretty"
escurl "$ES/_cat/indices/rag-docs-*?v&h=index,health,docs.count,store.size,pri,rep"
escurl "$ES/_cat/shards/rag-docs-*?v&h=index,shard,prirep,state,node,unassigned.reason"
escurl "$ES/rag-docs/_mapping/field/embedding?pretty"           # dims, similarity, index_options
escurl "$ES/rag-docs/_stats?filter_path=_all.primaries.dense_vector"   # vector count, recent versions
escurl "$ES/_nodes/stats/os?filter_path=nodes.*.name,nodes.*.os.mem"

docs.count in _cat/indices counts nested and hidden documents too, so use GET rag-docs/_count when you compare against the number of source chunks.

Symptom → cause → fix

Symptom Likely cause Fix
400 mentioning dimensions on index or query Embedding model changed or dims wrong Build a new index with the right dims and re-embed; you can't change dims in place
kNN fails with a message that the field is not indexed Field mapped with index: false Re-index into a mapping with index: true
Fewer than k results Filter in post_filter, or the filter is very selective Move the filter into knn.filter
Relevant chunks missing (low recall) num_candidates too low, or heavy quantization Raise num_candidates; test int8_hnsw against bbq_hnsw on your golden set
First queries after a restart take seconds Vectors not in the page cache yet Warm up with sample queries; add RAM so the vectors fit
Latency grows as data is loaded Many small segments Force merge rebuilt indexes; check _cat/segments
Hybrid search returns other tenants' documents Filter on only one retriever Filter every retriever

Prevent it next time

  • Put dims, similarity and index_options in a version-controlled index template, and always set them explicitly.
  • Build into a new versioned index, run a recall check, then move the alias.
  • Alert on cluster health, unassigned shards and node memory, and keep vector memory below the RAM left after the heap.
  • Record the embedding model name in each document or in index metadata, so a model change can't quietly mix incompatible vectors.