1

我有这样的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
               }
            }
         ]
      }
   }

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

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

4

2 回答 2

3

以这种方式解决:

{
   "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或“奇怪的事情”发生。

于 2017-03-21T12:25:04.827 回答
2

您可以使用过滤器聚合

GET _search
{
   "size":0,
   "aggs":{
      "products":{
         "nested":{
            "path":"products"
         },
         "filter": {
           "term": {
             "category": 11
           }
         }, 
         "aggs":{
            "top_terms_aggregation":{
               "terms":{
                  "field":"products.id",
                  "size":10
               }
            }
         }
      }
   }
}
于 2017-03-21T06:07:09.770 回答