Elasticsearch Compound Queries
Elasticsearch 的 Compound Queries 是一种强大的工具,用于组合多个查询子句,以实现更复杂的搜索逻辑。这些查询子句可以是叶查询(Leaf Queries)或复合查询(Compound Queries),并且可以用于组合结果和分数、改变行为或从查询上下文切换到过滤上下文。
主要的复合查询类型
bool 查询:
用于组合多个叶查询或复合查询子句,支持 must、should、must_not 和 filter 子句。must 和 should 子句的分数会被合并,而 must_not 和 filter 子句在过滤上下文中执行。
JSON复制
GET /products/_search
{
“query”: {
“bool”: {
“must”: [
{ “match”: { “description”: “wireless headphones” } }
],
“filter”: [
{ “term”: { “brand”: “BrandA” } }
],
“should”: [
{ “range”: { “price”: { “lte”: 100 } } }
],
“must_not”: [
{ “term”: { “color”: “red” } }
]
}
}
}
boosting 查询:
返回匹配 positive 查询的文档,但会降低也匹配 negative 查询的文档的分数。
JSON复制
{
“query”: {
“boosting”: {
“positive”: { “match”: { “content”: “multiple queries” }},
“negative”: { “term”: { “status”: “archived” }},
“negative_boost”: 0.5
}
}
}
constant_score 查询:
包装另一个查询,但在过滤上下文中执行它。所有匹配的文档都将获得相同的“常量” _score。
dis_max 查询:
接受多个查询,并返回匹配任何查询子句的文档。与 bool 查询合并所有匹配查询的分数不同,dis_max 查询使用单个最佳匹配查询子句的分数。
JSON复制
{
“query”: {
“dis_max”: {
“queries”: [
{ “match”: { “name”: “kimchy” }},
{ “match”: { “name”: “elasticsearch” }}
],
“boost”: 1.2,
“tie_breaker”: 0.7
}
}
}
function_score 查询:
使用函数修改主查询返回的分数,考虑因素如流行度、最近性、距离或通过脚本实现的自定义算法。
JSON复制
{
“query”: {
“function_score”: {
“query”: { “match”: { “name”: “kimchy” }},
“functions”: [
{ “random_score”: { “seed”: 1234 }},
{ “exponential_decay”: { “field”: “age”, “origin”: 0, “scale”: 1 }}
],
“score_mode”: “multiply”
}
}
}
使用场景
组合多个条件:使用 bool 查询组合多个搜索条件,例如同时匹配多个字段。
调整查询权重:使用 boosting 查询调整某些文档的权重。
固定分数:使用 constant_score 查询为所有匹配文档分配固定分数。
选择最佳匹配:使用 dis_max 查询选择最佳匹配的查询子句。
自定义评分:使用 function_score 查询根据自定义逻辑调整文档分数。
通过合理使用这些复合查询,您可以构建更复杂、更灵活的搜索逻辑,以满足不同的业务需求。