Elasticsearch:如何通过嵌套对象中的求和值进行过滤?

时间:2014-07-22 20:16:08

标签: elasticsearch

我在elasticsearch中有以下产品结构:

POST /test/products/1
{
  "name": "product1",
  "sales": [
    {
      "quantity": 10,
      "customer": "customer1",
      "date": "2014-01-01"
    },
    {
      "quantity": 1,
      "customer": "customer1",
      "date": "2014-01-02"
    },
    {
      "quantity": 5,
      "customer": "customer2",
      "date": "2013-12-30"
    }
  ]
}

POST /test/products/2
{
  "name": "product2",
  "sales": [
    {
      "quantity": 1,
      "customer": "customer1",
      "date": "2014-01-01"
    },
    {
      "quantity": 15,
      "customer": "customer1",
      "date": "2014-02-01"
    },
    {
      "quantity": 1,
      "customer": "customer2",
      "date": "2014-01-21"
    }
  ]
}

sales字段是嵌套对象。我需要过滤这样的产品: “获取总数量> = 16且sales.customer ='customer1'”的所有产品。 总数量为sum(sales.quantity),其中sales.customer ='customer1'。 因此,搜索结果应仅包含“product2”。

我尝试使用aggs,但我不明白在这种情况下如何过滤。 我在elasticsearch文档中没有找到任何关于它的信息。 可能吗? 我会欢迎任何想法,谢谢!

1 个答案:

答案 0 :(得分:-2)

首先要明确你想要的结果是什么?是计数还是查询字段?聚合仅提供计数,对于字段,您需要在查询中使用过滤器。如果您想要字段,那么您无法过滤 sum(sales.quantity)> = 16 ,如果您想要计数,您可以使用范围聚合但是我认为你只能在elasticsearch文档字段中使用范围而不是某些计算值。 我能给你的最近解决方案如下

{
  "size" : 0,
  "query" :{
  "filtered" : {
    "query" :{  "match_all": {} },
      "filter" : {
        "nested": {
          "path": "sales",
          "filter" : {"term" : {"sales.customer" : "customer1"}}
                }
        }
      }
  },
  "aggregations" :{
    "salesNested" : {
          "nested" : {"path" : "sales"},
            "aggregations" :{ 
                "aggByrange" : {
                  "numeric_range": {
                    **"field": "sales.quantity"**,
                    "ranges": [
                      {
                        "from": 16
                      }]
                  }
    }
  },
"aggregations" : {
  "quantityStats" : {
    "stats" : {
      { "field" : "sales.quantity" }
    }
  }

}
}
}
}

在上面的查询中,我们使用“field”:“sales.quantity”。对于您的解决方案,使用必须能够更改sales.quantity与quantityStats聚合的总和值,我认为elasticsearch不提供。