模板查询
2.19 版本引入
使用 template
查询创建包含占位符变量的搜索查询。占位符使用 "${variable_name}"
语法指定(请注意,变量必须用引号括起来)。当你提交搜索请求时,这些占位符在被搜索请求处理器处理之前保持未解析状态。当你的初始搜索请求包含需要在运行时转换或生成的数据时,此方法特别有用。
例如,在使用 ml_inference 搜索请求处理器时,你可能会使用模板查询,该处理器在搜索过程中将文本输入转换为向量嵌入。处理器将在执行最终查询之前,用生成的值替换占位符。
有关完整示例,请参阅使用模板查询进行查询重写。
示例
以下示例展示了一个模板 k-NN 查询,其中包含一个 "vector": "${text_embedding}"
占位符。占位符 "${text_embedding}"
将被 ml_inference
搜索请求处理器从 text
输入字段生成的嵌入替换。
GET /template-knn-index/_search?search_pipeline=my_knn_pipeline
{
"query": {
"template": {
"knn": {
"text_embedding": {
"vector": "${text_embedding}", // Placeholder for the vector field
"k": 2
}
}
}
},
"ext": {
"ml_inference": {
"text": "sneakers" // Input text for the ml_inference processor
}
}
}
要将模板查询与搜索请求处理器一起使用,你需要配置一个搜索管道。以下是 ml_inference
搜索请求处理器的一个示例配置。input_map
将文档字段映射到模型输入。在此示例中,文档中的 ext.ml_inference.text
源字段被映射到 inputText
字段,即模型的预期输入字段。output_map
将模型输出映射到文档字段。在此示例中,模型的 embedding
输出字段被映射到文档中的 text_embedding
目标字段。
PUT /_search/pipeline/my_knn_pipeline
{
"request_processors": [
{
"ml_inference": {
"model_id": "Sz-wFZQBUpPSu0bsJTBG",
"input_map": [
{
"inputText": "ext.ml_inference.text" // Map input text from the request
}
],
"output_map": [
{
"text_embedding": "embedding" // Map output to the placeholder
}
]
}
}
]
}
在 ml_inference
搜索请求处理器运行后,搜索请求将被重写。vector
字段包含处理器生成的嵌入,而 text_embedding
字段包含处理器输出。
GET /template-knn-1/_search
{
"query": {
"template": {
"knn": {
"text_embedding": {
"vector": [0.6328125, 0.26953125, ...],
"k": 2
}
}
}
},
"ext": {
"ml_inference": {
"text": "sneakers",
"text_embedding": [0.6328125, 0.26953125, ...]
}
}
}
限制
模板查询至少需要一个搜索请求处理器来解析占位符。搜索请求处理器必须配置为生成管道中预期的变量。
后续步骤
- 有关完整示例,请参阅模板查询。