聚合密钥与其嵌套聚合密钥的elasticsearch无痛组合

时间:2018-10-31 22:46:51

标签: elasticsearch elasticsearch-painless

正在为Elasticsearch查询结果进行转换

{
   'key': factoryA,
   'buckets': [
       {
          'key': 'productX'
       }
    ]

},
{
   'key': factoryB,
   'buckets': [
       {
          'key': 'productX'
       },
       {
          'key': 'productY'
       }
    ]

}

我想要一个列表,该列表的项是工厂聚合及其嵌套聚合产品的组合:

[
   {'factory': 'factoryA', 'product': 'productX'},
   {'factory': 'factoryB', 'product': 'productX'},
   {'factory': 'factoryB', 'product': 'productY'},
]
关于无痛脚本的任何建议?先感谢您。或在任何地方都可以找到全面的无痛指南。没有Doc的无痛是完全痛苦的。

1 个答案:

答案 0 :(得分:0)

我想下面的查询就是您要寻找的东西:

查询

POST <your_index_name>/_search
{  
   "size":0,
   "aggs":{  
      "myagg":{  
         "terms":{  
            "script":{  
               "source":"'factory: ' + doc['factory.keyword'].value + params.param + 'product: ' + doc['product.keyword'].value",
               "lang":"painless",
               "params":{  
                  "param":", "
               }
            },
            "order":{  
               "_term":"asc"
            }
         }
      }
   }
}

查询响应

{
  "took": 6,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "myagg": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "factory: factory A, product: product A",
          "doc_count": 1
        },
        {
          "key": "factory: factory B, product: product B",
          "doc_count": 1
        }
      ]
    }
  }
}

请注意,我假设两个字段factoryproduct的类型均为keyword

让我知道是否有帮助!