Elasticsearch 数组值计数聚合

6

示例文档:

{
    "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聚合时,它会给出总数。但我需要按照预期输出中给定的名称值进行列出。

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html - blackmamba
@blackmamba 我已经看过了。不清楚如何满足我的需求。当我将路径设置为“attributes”时,会出现异常。当我设置为“attributes.name”时,计数为0。 - Sriram
你已经将属性和它的父级映射为嵌套了,对吧? - blackmamba
你需要将它们都作为嵌套类型,并在填充数据之前预定义它们。 - blackmamba
让我们在聊天中继续这个讨论 - Sriram
显示剩余2条评论
1个回答

5

正如你所说,属性字段是嵌套的。 尝试这个,它会起作用。

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

刚刚看到了这个回答:https://dev59.com/WYzda4cB1Zd3GeqPlVtt#31052532,正是我一直在寻找的答案。当我来这里告诉你时,你已经完美地回答了它 :) - Sriram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接