首页/AI/RAG 与向量库速查/Elasticsearch 向量检索(kNN)

Elasticsearch 向量检索(kNN)

Elasticsearch 8.x 支持 dense_vector 字段与近似 kNN 检索:字段定义 dims 与相似度,查询在 knn 段声明 number_of_candidates 与 k,可与 BM25 查询在一个请求内组合。

RAG 与向量库速查AI更新于 2026-10-12

建索引(8.x 写法)

建索引(8.x 写法)
PUT kb_chunks
{
  "mappings": {
    "properties": {
      "content": { "type": "text" },
      "embedding": {
        "type": "dense_vector",
        "dims": 1024,
        "index": true,
        "similarity": "cosine"
      }
    }
  }
}

kNN 检索

kNN 检索
POST kb_chunks/_search
{
  "knn": {
    "field": "embedding",
    "query_vector": [0.1, 0.2, 0.3],
    "k": 10,
    "num_candidates": 100
  },
  "_source": ["content", "source"]
}
dims 与模型输出必须一致;8.x 起向量索引基于 HNSW,num_candidates 影响召回与延迟。

易错点

  • num_candidates 设得比 k 大不了多少,近似检索召回不稳定
  • 老版本(7.x)脚本评分方式迁移到 8.x kNN 时参数体系完全不同

数据来源与参考

  • Elasticsearch 官方文档(dense_vector / kNN search)
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌