嵌套字段上的聚合不起作用

时间:2016-01-14 09:25:47

标签: elasticsearch

我无法对嵌套文档进行聚合。以下是2个示例文档: 文件1

{
  "name": "Samuel Lone",
  "assignments": [
    {
      "subject": "data structures",
      "score": 43,
      "dept": "cs"
    },
    {
      "subject": "fluid theory",
      "score": 37,
      "dept": "ec"
    }
  ]
}

文件2

{
  "name": "Manya Pious",
  "assignments": [
    {
      "subject": "data structures",
      "score": 43,
      "dept": "cs"
    },
    {
      "subject": "fluid theory",
      "score": 37,
      "dept": "ec"
    }
  ]
}

当我给出以下聚合查询时,结果没有结果。

{
  "aggs": {
    "dept_breakdown": {
      "terms": {
        "field": "assignments.dept"
      }
    }
  }
}

如何在“assignments.dept”字段上完成聚合?

2 个答案:

答案 0 :(得分:1)

对于nested字段,请使用nested aggregations

POST /your_index/_search?search_type=count
{
   "aggs": {
      "nested_assignments": {
         "nested": {
            "path": "assignments"
         },
         "aggs": {
            "dept_terms": {
               "terms": {
                  "field": "assignments.dept"
               }
            }
         }
      }
   }
}

如果这没有帮助,请发布您的文档映射。

答案 1 :(得分:0)

如果字段"assignments"属于nested类型,则需要使用nested aggregations。如果"assignments"字段不属于nested类型,则原始查询可以正常工作。

{
   "aggs": {
      "dept_breakdown": {
         "nested": {
            "path": "assignments"
         },
         "aggs": {
            "departments": {
               "terms": {
                  "field": "assignments.dept"
               }
            }
         }
      }
   }
}