基于 Elasticsearch 向量搜索创建 RAG 应用
如果无法正常显示,请先停止浏览器的去广告插件。
1. 运用 Elasticsearch 向量搜
索创建 RAG 应用
姓名
刘晓国,Elastic 中国社区首席布道师
2. 目录
01 智能时代的搜索需求
02 Elasticsearch 向量搜索介绍
03 使用 Elasticsearch 在企业搜索中的案例分
享
3.
4. 智能时代的搜索需求
5. AI 时代对搜索提出了新要求
向量搜索
语义搜索
过去用户需求
全文搜索
聚合统计
分词
结构化搜索
复杂混合搜索
排序调优
向量和经典搜
索的混合
模型重排序
RAG
现在用户需求
6. 语义搜索
根据搜索查询的意图和上下文含义检索结果,而不仅仅是关键字
how to set up elasticsearch ml?
Prelert
anomaly detection
configure
machine learning
site: elastic.co
install
machine learning settings
getting started
7. 词汇搜索结果
how to set up elasticsearch ml?
8. 语义搜索结果
how to set up elasticsearch ml?
9. 通过文字搜索找到图片:覆盖雪的山峰
通过图像比较找到相似的图片
如何在 Elastic 中实现图片相似度搜
10. Elasticsearch 向量搜索介绍
11. 有两种向量模型
DENSE Vector
一长串数字,每个维度一个
● 在数据集上进行训练,以获得较高的 “域内” 性能
● 低维(312, 512, 1536, ..)
● 捕捉语义
● 对于相似性和聚类有用
● 多模式支持
○ Text
○ Image
○ Audio
○…
● 较大的数据集占用大量内存
● 可解释性差
SPARSE Vector
Token Weighted Pairs
● 数十万至数百万的标记词汇量
● Token 加权对
○ Token : Weight
● 每个文档 - 仅存储 N 个最高权重的标记(其余为 0)
● 通过 DotProduct 实现语义搜索
● 与密集向量搜索相比,内存要求更低
● 稀疏模型可以实现 “后期交互”
12. Text Expansion Scoring
(.088*2.02)
+(.74*1.07)
+(.62*1.04)
droids
you’re
looking
for
Score =
1.61
##oids
2.09
android
robot
0.08
.74
1.07
2.02
android
do
androids
robot
cartoon
.62
1.04
cartoon
list
galaxy .74
lamb
1.16
2.46
sheep
dream
of
electric
sheep
.86
13. 向量搜索概念架构
使用向量最近邻生成搜索排名
14. 向量搜索支持的应用程序架构
了解 5 个关键组件
注 :inference API 不适合图像搜索
15. 步骤 1:设置机器学习模型
$ eland_import_hub_model
--url https://cluster_URL --hub-model-id
BERT-MiniLM-L6 --task-type text_embedding --
start
BERT-MiniLM-L6
选择合适的模型
将模型加载到集群
管理模型
16. 步骤二: 数据摄取和嵌入生成
POST /_doc
Standard field indexing for non-vector
types
Source data
POST /_doc
Encoding via Inference
Processor
{
"_id":"product-1234",
"product_name":"Summer Dress",
"description":"Our best-selling…",
"Price": 118,
"color":"blue",
"fabric":"cotton",
} "desc_embedding":[0.452,0.3242,…]
}
17. 步骤三: 发出向量查询
使用 _search 端点发出查询,带有 kNN 子句,使用先前
生成的嵌入
c
3
查询被提交给搜索驱动的应用程序
a
GET product-catalog/_search
{
b
生成查询嵌入
POST /_ml/trained_models/my-model/_infer
{
}
"docs": {
"description": "summer clothes"
}
Transformer model
}
"query": {
"match": {
"description": {
"query": "summer clothes",
"boost": 0.9
}
}
},
"knn": {
"field": "desc_embbeding",
"query_vector": [0.123, 0.244,...],
"k": 5,
"num_candidates": 50,
"boost": 0.1,
需要计算后填入
"filter": {
"term": {
"department": "women"
}
}
},
"size": 10
18. 把两个步骤合为一个 - 8.7 +
GET product-catalog/_search
{
"knn": {
"field": "desc_embbeding",
"k": 5,
"num_candidates": 50,
"query_vector_builder": {
"text_embedding": {
"model_text”: "summer
clothes”,
"model_id": <text-embedding-model>
},
Transformer model
}
"filter": {
"term": {
"department": "women"
}
}
},
"size": 10
19. Elasticsearch 混合搜索
BM25
文本搜索
第三方 Embedding模型
密集向量
text
embeddings
密集向量
image embeddings
RRF
Elasticsearch Search APIs
强大的语义和混合搜索
稀疏向量
20. 混合评分让你两全其美
Traditional, term-based
score
Vector similarity score
Combine
- Convex Combination
- Reciprocal Rank Fusion/RFF
GET product-catalog/_search
{
"query": {
"match": {
"description": {
"query": "summer clothes",
"boost": 0.9
}
}
},
"knn": {
"field": "desc_embbeding",
"query_vector": [0.123, 0.244,...],
"k": 5,
"num_candidates": 50,
"boost": 0.1,
"filter": {
"term": {
"department": "women"
}
}
},
pre-filtering
"size": 10
}
21. Reciprocal Rank Fusion (RRF) 算分示例
BM25 相关性排名
密集向量相关性排名
Search
Query
RRF结果 k=0
A 1 B 1 B:1/2 + 1/1 = 1.5
B 2 C 2 A:1/1 + 1/3 = 1.3
C 3 A 3 C: 1/3 + 1/2 = 0.83
Keyword Search
Sparse Vector Search
Dense Search
Hybrid Store
( Inverted Index | Sparse Vectors | Dense Vectors )
Keyword Search
Results
A
C
Sparse Vector Search
Results
B
Z
A
B
Z
Reciprocal Rank Fusion (RRF)
Best Results
A
B
Dense Vector Search Results
Z
A
B
22. kNN 相似度阈值
Query
只接受足够相似的文档作为 kNN 搜索的结果
驱动
Filtering only
relevant results
● 用户请求
● 完成 facets 的故事 - 这是我们的一个关键优势
客户价值
● 避免向用户浮动误报
● 完整实用的解决方案
○ Facets - 必须要求
○ 用户讨厌误报
○ 按排名质量阈值过滤 - 实际需要
POST image-index/_search
{
"knn": {
"field": "image-vector",
"query_vector": [1, 5, -20],
"k": 5,
"num_candidates": 50,
" similarity ": 36,
"filter": {
"term": {
"file-type": "png"
}
}
},
"fields": ["title"],
"_source": false
}
23. Elastic 能够提供你需要的所有功能
大多数的向量数据库
混合搜索
(文本 + 向量)
存储和搜索
向量
一些向量数据库
Elasticsearch
Inference
AutoOps Service
聚合
自动提示
创建
Embeddings
文本, 地理位置搜索
Inference
数据摄取 (web crawler, API
搜索分析
开箱即用的
训练模型
● 基于 HNSW 的索引/CAGRA
● 原生向量数据库,并非是插件
● 与现有 ES 搜索功能高度融合进行混合搜索
● 生成式人工智能应用所需的全部功能
embedding
模型
过滤 及切面
文档级别安全
ES|QL for
Search
Native
Chunking
connectors, Beats,
Agent, API framework)
自部署 / 云 Retrievers
/ 混合云
Reranking
24. Elasticsearch 向量引擎最新进展
硬件加速 增加单个查询并发
利用 CPU 硬件指令加速向量索引和
计算速度。GPU 加速/CAGRA(
CUDA ANN GRAph)) 增加查询并发度,充分利用更多的计算
核心
更快
更强
标量量化 并发查询间协同
向量有损压缩,float 到 int8、int4、
bit(BBQ) 向量来平衡精度、速度和
成本 一个查询的多个并发线程间协同共享信
息,提前终止一些查询线程
Elasticsearch 回顾:向量搜索创新的时间线
25. Elasticsearch 向量引擎- 搜索并发及硬件效率改进
现在
以前
• 集群整体吞吐优先
• 限制单个查询的资源
• 每个查询每个分片一个查询线程
• 每个查询每个分片中的段一个查询线程、逻辑分区
• 改进了搜索延迟
• 可以重复利用更多核心数
• 并发间协调
• IO 并发
• 稀疏索引
• 提前终止
• 快速模式
Apache Lucene 10 已发布!Lucene 硬件效率改进及其他改进
26. 搜索发生了哪些变化 …
FUTURE
Relevance Tuning
Hybrid search
Vector search
Textual search
27. 搜索趋势
检索技术和查询形成
Final reranking
(10 - 100 docs)
-
-
更加关注重新排序
● 系统地应用各种机器学习模
型和技术
● 填补准确率与成本之间的梯
度
AI based models
Personalization
Mid-stage rerankers
(1k - 10k docs)
- Query rescorers
- Learning To Rank
First-stage retrieval
(100k - millions of documents)
-
-
-
BM25
ANN dense retrieval
Sparse retrieval (e.g. ELSER)
28. Learning-to-rank
端到端工作流程概述
Judgment list
Model upload
w/ Eland
Inference
Model Training
介绍 Elasticsearch 中的 Learning to Tank - 学习排名
(rescore clause in _search)
29. _inference/rerank
Search Experience
Reranked
documents
"query": ...
Retrieved
documents
/_search query
"input":
Retrieved
documents
"query": ...
1.23
Scores
/_inference/rerank
Elasticsearch
Cohere Rerank V3
Model provider
30. _inference/rerank
Search Experience
multiplied
Reranked
documents
"retriever": ...
/_inference/rerank
/_search query
Elasticsearch
Hugging Face
Model provider
Elastic reranker
Cohere Rerank V3
31. Rescorer Retriever
Retrievers - 检索器
Learning to
rank
3. Final semantically
2. RRF-combined
reranked results
and ranked resu lts
1. Initial retrieval
result sets
"retriever": {
"text_similarity_reranker": {
// ... semantic reranking parameters
"retriever": {
"rrf": {
"retrievers": [{
"standard": {
"query"."semantic": {
"field": "a-semantic_text-field",
"query": "why are retrievers fun?"
}}},{
"knn": {
// ... knn parameters
// ... query_vector_builder parameters
"model_text": "why are retrievers fun?"
}}}},{
"standard": {
"query"."match": {
"some-field": "why are retrievers fun?"
}}}}]}}}}
32. 等等 —— 我可以将我所有的私密数据向量化吗?
YES … 确实需要一个分块策略
深入思考:
单个向量能代表整个小说吗?
33. 分块策略
Chance “answer” in one
contiguous chunk
Semantic Precision
粗粒度
“Big chunk”
细粒度
“Small chunk”
Chunk Size
34. 分块策略
几种示例
向量模型在能够接受的输入 token 数量
上是有限制的。
Chapter 1
Chapter 1
Chapter 1
Paragraph
大多数模型在前 X 个 token 之后会截断
,导致丢失语义。
page
page
Sentence
paragraph
paragraph
paragraph
Word
块越小,单个块包含
回答问题所需所有信
息的可能性就越小。
35. 使用 semantic_text 自动在 Elasticsearch 中进行分块
● 文本被分成250个单词组成的块
● 每个块包含来自前一个块的 100 个
单词
● 块传递给推理 API 以进行嵌入
● 原始文本与块、块向量一起存储
● 使用 semantic 查询将自动搜索
semantic_text 字段中的嵌套块。
-
-
8.16+, 默认基于句子
8.16 之前,默认基于单词
36. Semantic Text 字段类型
存储和自动分块:简化 RAG 应用程序
"embeddings": {
"##oid": 1.9103845,
"##oids": 1.768872,
"free": 1.693662,
"dr": 1.6103356,
"around": 1.4376559,
"these": 1.1396849}
Auto-chunk!
Elasticsearch:检索增强生成背后的重要思想
Vectorize
37. 简化向量搜索使用
Query
PUT _inference/sparse_embedding/my-inf-
endpoint
{
"service": "elser",
"service_settings": {
"num_allocations": 1,
"num_threads": 1
}
} PUT test-index/_doc/doc1
{
"my_inference_field": "my doc text"
}
PUT test-index
{
"mappings": {
"properties": {
"my_inference_field": {
"type": "semantic_text",
"inference_id": "my-inf-endpoint"
}
}
} GET <index>/_search
{
"query": {
"semantic": {
"field": "my_inference_field",
"query": "my query text"
}
}
}
Doc
Chunk
Pick ML node
Pick model
Run model per chunk
Quantize vector
Run model per chunk
Vector fields
(the right type and nested)
Index
38. Elasticsearch AI 功能和集成第三方服务
Elasticsearch
Inference API
embedding、chat、rerank
Elasticsearch
部署的模型
私有化部署的模型
在线推理服务
阿里云、亚马逊网络服务 (AWS)、Anthropic 的 Claude、Cohere、Confluent、
Dataiku、DataRobot、Galileo、谷歌云、Hugging Face、LangChain、LlamaIndex
、Mistral AI、微软、NVIDIA、OpenAI、Protect AI、Red Hat、Vectorize.io 和
Unstructured。
39. Elastic serverless - 存算分离
Elastic Cloud
Hosted
Elastic Cloud
Serverless
40. 使用 Elasticsearch 在企业
搜索中的案例分享
41. 生成式人工智能
面临着特定的挑战
●
●
●
●
●
●
基础模型知识仅限于公共训练数据
训练和微调后数据就冻结
幻觉、错误答案
复杂的技术堆栈
实时访问私人数据
安全和隐私
● …
42. LLM 变 “聪明”的三种方式
Pre-training
Fine-tuning
情境学习(prompt)
基础模型的训练成本高达数千万到数亿美元。LLM 从大量公共数据
集中学习语言和知识。
• 特定任务培训(分类等)
• 提高某一领域的响应质量
• 添加来自特定数据源的知识
• 符合保障措施和道德限制
• Prompt engineering 技术
• Retrieval Augmented Generation - RAG
43. Retrieval Augmented Generation : 多路召回
格式化
来自 LLM 的响应
Create Prompt
User Question
+
返回用户
Context Window
用户问题
聊天完成 LLM
托管或自托管
代码层 API 调用
Elasticsearch Vector Database
Retrieve and Score
Semantic Search
Input
Query
Compute Query
Vector Embedding
Lexical Search
Combine and Rank
Retrieve and Score
Return
top K
44. 从文本生成到决策 - Agentic RAG
Prompting an LLM
提示 LLM 并得到回应。不需要
其他工具或组件。
User
Agentic Flow
Retrieval Augmented Generation
添加知识库以提高准确性并为 LLM
添加新信息
Hybrid
Search
已启用决策功能。 LLM 可以提示用户信息,选择使用工具,
与其他代理交互,并影响现实世界(即触发警报、发送消息等
)
User
User
Gather
further
information
from user
Prompt
Prompt
Factor in
tool
output
LLM
Tools
LLM
Vector DB
LLM
Context
Select and
use a tool
Generated
Response
Retrieval
Augmented
Generated
Response
Action /
Outcome
Activation
Tool
Augmented
Response
45. 用于路由的自适应 RAG
Agentic RAG 详解 - 从头开始构建你自己的智能体系统
46. HyDE (Hypothetical Document Embedding)
假设文档(Hypothetical Documents)更能反映你的文档结构。使用假设文档而不是嵌入可以显著提高相关性!
Generated Hypothetical
Document
Original Query
LLM
Tell me about Fish.
Fish: A Comprehensive Overview
Fish are aquatic vertebrate animals that live in water
bodies across the globe. They are characterized by
several key features:
Physical Characteristics:
●
●
●
●
●
Gills for breathing underwater
Fins for movement and stability
Scales covering most species
Streamlined bodies for efficient swimming
Cold-blooded (ectothermic)
Search Result Document
Vector
Similarity
Match
A fish (pl.: fish or fishes) is an aquatic,
anamniotic, gill-bearing vertebrate animal
with swimming fins and a hard skull, but
lacking limbs with digits. Fish can be
grouped into the more basal jawless fish
and the more common jawed fish, the
latter including all living cartilaginous and
bony fish, as well as the extinct
placoderms and acanthodians.
47. 混合搜索及查询重写提高搜索精度及召回率
48. embedding_cols=[
'keyphrases_embedding',
'potential_questions_embedding',
'entities_embedding',
'chunk_embedding'
]
combination_weights=
[
0.1,
0.15,
0.05,
0.7
]
49.
50. 欢迎交流
个人微信
Elastic
51. THANKS
大模型正在重新定义软件
Large Language Model Is Redefining The Software