欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > 【Elasticsearch】 Compound Queries

【Elasticsearch】 Compound Queries

2025/2/5 12:50:42 来源:https://blog.csdn.net/risc123456/article/details/145400139  浏览:    关键词:【Elasticsearch】 Compound Queries

Elasticsearch Compound Queries

Elasticsearch 的 Compound Queries 是一种强大的工具,用于组合多个查询子句,以实现更复杂的搜索逻辑。这些查询子句可以是叶查询(Leaf Queries)或复合查询(Compound Queries),并且可以用于组合结果和分数、改变行为或从查询上下文切换到过滤上下文。

主要的复合查询类型

  1. bool 查询

    • 用于组合多个叶查询或复合查询子句,支持 mustshouldmust_notfilter 子句。mustshould 子句的分数会被合并,而 must_notfilter 子句在过滤上下文中执行。

    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" } }]}}
    }
  2. boosting 查询

    • 返回匹配 positive 查询的文档,但会降低也匹配 negative 查询的文档的分数。

    JSON复制

    {"query": {"boosting": {"positive": { "match": { "content": "multiple queries" }},"negative": { "term": { "status": "archived" }},"negative_boost": 0.5}}
    }
  3. constant_score 查询

    • 包装另一个查询,但在过滤上下文中执行它。所有匹配的文档都将获得相同的“常量” _score

  4. dis_max 查询

    • 接受多个查询,并返回匹配任何查询子句的文档。与 bool 查询合并所有匹配查询的分数不同,dis_max 查询使用单个最佳匹配查询子句的分数。

    JSON复制

    {"query": {"dis_max": {"queries": [{ "match": { "name": "kimchy" }},{ "match": { "name": "elasticsearch" }}],"boost": 1.2,"tie_breaker": 0.7}}
    }
  5. 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 查询根据自定义逻辑调整文档分数。

通过合理使用这些复合查询,您可以构建更复杂、更灵活的搜索逻辑,以满足不同的业务需求。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com