ElasticSearch数组值计数聚合

wlzqhblo  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(1)|浏览(183)

示例文档

{
    "id": "62655",
    "attributes": [
        {
            "name": "genre",
            "value": "comedy"
        },
        {
            "name": "year",
            "value": "2016"
        }
    ]
}

{
    "id": "62656",
    "attributes": [
        {
            "name": "genre",
            "value": "horror"
        },
        {
            "name": "year",
            "value": "2016"
        }
    ]
}

{
    "id": "62657",
    "attributes": [
        {
            "name": "language",
            "value": "english"
        },
        {
            "name": "year",
            "value": "2015"
        }
    ]
}

预期输出

{
    "hits" : {
        "total": 3,
        "hits": []
    },
    "aggregations": {
        "attribCount": {
            "language": 1,
            "genre": 2,
            "year": 3
        },
        "attribVals": {
            "language": {
                "english": 1
            },
            "genre": {
                "comedy": 1,
                "horror": 1
            },
            "year": {
                "2016": 2,
                "2015": 1
            }
        }
    }
}

我的查询

我可以使用下面的查询得到“attribCount”聚合。但是我不知道如何得到每个属性值的计数。

{
    "query": {
        "filtered": {
            "query": {
                "match_all": {}
            }
        }
    },
    "aggs": {
        "attribCount": {
            "terms": {
                "field": "attributes.name",
                "size": 0
            }
        }
    },
    "size": 0
}

当我使用attributes.value进行聚合时,它给出了总计数。但是我需要将它列在预期输出中给出的名称value下。

xdyibdwo

xdyibdwo1#

就像你说的,属性字段是嵌套的。试试这个,它会起作用的

{
  "size": 0,
  "aggs": {
    "count": {
      "nested": {
        "path": "attributes"
      },
      "aggs": {
        "attribCount": {
          "terms": {
            "field": "attributes.name"
          }
        },
        "attribVal": {
          "terms": {
            "field": "attributes.name"
          },
          "aggs": {
            "attribval2": {
              "terms": {
                "field": "attributes.value"
              }
            }
          }
        }
      }
    }
  }
}

相关问题