ElasticSearch-通过聚合的嵌套子项过滤文档

时间:2019-11-12 16:11:35

标签: elasticsearch filtering aggregation

我有一个具有以下映射的索引:

{
  "mappings": {
    "properties": {
      "id": {"type": "keyword"},
      "sortingKey": {"type": "integer"},
      "articleName": {"type": "text"},

      "category": {"type": "keyword"},
      "color": {"type": "keyword"},
      "season": {"type": "keyword"},

      "stocks": {
        "type": "nested",
        "properties": {
          "storageId": {"type": "keyword"},
          "availableStock": {"type": "integer"}
      }
    }
  }
}

更简单地说,对象看起来像:

{
  id: 123,
  sortingKey: 10
  articleName: "Flower Dress",
  category: "dress",
  color: "red",
  season: "summer",

  stocks: {
    [storageId: 1, availableStock: 2],
    [storageId: 2, availableStock: 1],
    [storageId: 3, availableStock: 4],
    ...
  }
}

在搜索之前,我会得到几个我关心的storageId,例如2和3。

我想做的是:  -仅将我关心的storageIds上的可用库存相加  -如果上级单据的总库存低于最小值,则应将其过滤掉  -最后,所有文件应按其排序键进行排序

我尝试过的是根据允许的storageId进行过滤,并使用聚合对availableStock进行求和,但最后我不知道如何按sortingKey对它们进行排序。我也希望我可以在某处注入inner_hits: {},以便使汇总返回通过过滤器的文档。

这是我的查询:

{
  "size": 0,
  "aggs": {
    "buckets": {
      "terms": {"field": "id"},
      "aggs": {
        "stock": {
          "nested": {"path": "stocks"},
          "aggs": {
            "storage_filter": {
              "filter": {"terms": {"stocks.storageId": ["25_0", "25_1"]}},
              "aggs": {
                "summed": {
                  "sum": {"field": "stocks.availableStock"}}}}}}}}}} 

0 个答案:

没有答案