【问题标题】:How to filter top terms aggregation in ElasticSearch?如何过滤 ElasticSearch 中的热门术语聚合?
【发布时间】:2017-03-20 18:38:33
【问题描述】:

我有orders这样的文件:

{
   "customer":{
      "id":1,
      "Name":"Foobar"
   },
   "products":[
      {
         "id":1,
         "name":"Television",
         "category": 11
      },
      {
         "id":2,
         "name":"Smartphone",
         "category": 12
      }
   ]
}

我正在执行top_terms_aggregation 以了解最畅销的产品。为了在全球范围内做到这一点,我使用:

{
   "size":0,
   "aggs":{
      "products":{
         "nested":{
            "path":"products"
         },
         "aggs":{
            "top_terms_aggregation":{
               "terms":{
                  "field":"products.id",
                  "size":10
               }
            }
         }
      }
   }
}

但是,我将如何过滤给定 category_id 的产品?我尝试添加此过滤器:

  "query":{
      "bool":{
         "must":[
            {
               "match":{
                  "products.category":11
               }
            }
         ]
      }
   }

但这会过滤具有给定类别的一些产品的订单本身,并且聚合会损坏。

我想获得属于特定类别的畅销产品。

【问题讨论】:

标签: elasticsearch nosql-aggregation nosql


【解决方案1】:

这样解决:

{
   "size":0,
   "aggs":{
      "products":{
         "nested":{
            "path":"products"
         },
         "aggs":{
            "first_filter":{
               "filter":{
                  "term":{
                     "products.category":11
                  }
               },
               "aggs":{
                  "top_terms_aggregation":{
                     "terms":{
                        "field":"products.id",
                        "size":10
                     }
                  }
               }
            }
         }
      }
   }
}

必须是aggs 的确切顺序,否则会发生“奇怪的事情”。

【讨论】:

    【解决方案2】:

    您可以使用filter aggregation

    GET _search
    {
       "size":0,
       "aggs":{
          "products":{
             "nested":{
                "path":"products"
             },
             "filter": {
               "term": {
                 "category": 11
               }
             }, 
             "aggs":{
                "top_terms_aggregation":{
                   "terms":{
                      "field":"products.id",
                      "size":10
                   }
                }
             }
          }
       }
    }
    

    【讨论】:

    • 不起作用,因为它属于Found two aggregation type definitions in [products]: [nested] and [filter]。不过谢谢你的回答!
    • 是的..你是对的。我只是在 SO 编辑器中输入了这个查询,因此错过了这个问题。很高兴您能够根据答案自行解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2014-07-09
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多