elasticsearch - 聚合数组匹配的计数

时间:2016-02-23 10:09:35

标签: elasticsearch

这是我的结构:

文件1

{
  "people": [
    {
      "name": "Darrell",
      "age": "10",
    },
    {
      "name": "Karen",
      "age": "20",
    },
    {
      "name": "Gary",
      "age": "30",
    }
  ]
}

文件2

{
  "people": [
    {
      "name": "Karen",
      "age": "25",
    },
    {
      "name": "Gary",
      "age": "30",
    }
  ]
}

现在,如何在与查询匹配的单个数组元素上执行计数聚合?

  1. 如果我查询姓名:Karen,我需要将计数作为2.
  2. 如果我查询姓名:Karen&&年龄:20岁,我需要数为1。
  3. 如果我查询姓名:Gary&&年龄:30岁,我需要数为2。

1 个答案:

答案 0 :(得分:2)

您需要将people对象映射为nested objects,否则it won't work as you expect

curl -XPUT localhost:9200/your_index -d '{
  "mappings": {
    "your_type": {
      "properties": {
        "people": {
          "type": "nested",
          "properties": {
              "name": {"type": "string"},
              "age": {"type": "integer"}
          }
        }
      }
    }
  }
}'

创建索引和映射类型后,在重新索引数据后,您将能够像这样运行查询:

curl -XPOST localhost:9200/your_index/_search -d '{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "people",
            "query": {
              "term": {
                "people.name": "karen"
              }
            }
          }
        },
        {
          "nested": {
            "path": "people",
            "query": {
              "term": {
                "people.age": "20"
              }
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "people": {
      "nested": {
        "path": "people"
      },
      "aggs": {
        "names": {
          "terms": {
             "field": "people.name"
          }
        }
      }
    }
  }
}'