首页 > 解决方案 > 同一查询中不同搜索的 Elasticsearch 聚合

问题描述

无论使用什么其他参数(术语、术语等),我都想进行查询以仅基于匹配进行聚合。更具体地说,我有一个在线商店,我在其中使用多个过滤器(颜色、大小等)。如果我检查一个字段,例如颜色:红色,则不再聚合其他颜色。我正在使用的一个解决方案是进行 2 个单独的查询(一个用于应用过滤器的搜索,另一个用于聚合。知道如何组合这 2 个单独的查询吗?

标签: elasticsearch

解决方案


您可以利用post_filter哪些不适用于您的聚合,但只会过滤要返回的hits。例如:

创建商店

PUT online_shop
{
  "mappings": {
    "properties": {
      "color": {
        "type": "keyword"
      },
      "size": {
        "type": "integer"
      },
      "name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

用一些产品填充它

POST online_shop/_doc
{"color":"red","size":35,"name":"Louboutin High heels abc"}

POST online_shop/_doc
{"color":"black","size":34,"name":"Louboutin Boots abc"}

POST online_shop/_doc
{"color":"yellow","size":36,"name":"XYZ abc"}

将共享查询应用到hits以及aggregations用于post_filter...后过滤命中:

GET online_shop/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "abc"
          }
        }
      ]
    }
  },
  "aggs": {
    "by_color": {
      "terms": {
        "field": "color"
      }
    },
    "by_size": {
      "terms": {
        "field": "size"
      }
    }
  },
  "post_filter": {
    "bool": {
      "must": [
        {
          "term": {
            "color": {
              "value": "red"
            }
          }
        }
      ]
    }
  }
}

预期结果

{
  ...
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.11750763,
    "hits" : [
      {
        "_index" : "online_shop",
        "_type" : "_doc",
        "_id" : "cehma3IBG_KW3EFn1QYa",
        "_score" : 0.11750763,
        "_source" : {
          "color" : "red",
          "size" : 35,
          "name" : "Louboutin High heels abc"
        }
      }
    ]
  },
  "aggregations" : {
    "by_color" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "black",
          "doc_count" : 1
        },
        {
          "key" : "red",
          "doc_count" : 1
        },
        {
          "key" : "yellow",
          "doc_count" : 1
        }
      ]
    },
    "by_size" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 34,
          "doc_count" : 1
        },
        {
          "key" : 35,
          "doc_count" : 1
        },
        {
          "key" : 36,
          "doc_count" : 1
        }
      ]
    }
  }
}


推荐阅读