2016-02-23 46 views
0

这是我的结构: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. 如果我查询名称:凯伦,我需要的数量为2
  2. 如果我查询名称:莫文蔚& &年龄:20,我需要的数量为1
  3. 如果我查询名称:加里& &年龄:30,我需要的数量为2

回答

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" 
      } 
     } 
     } 
    } 
    } 
}' 
+0

感谢VAL。它告诉我一个错误 - “bool查询不支持[filter]” – user3658423

+0

哦,我使用ES 2.而你可能不是。我已经使用2.0以前的有效查询更新了我的答案。 – Val

+0

由于某些原因,术语聚合不起作用。我切换到value_count,它的工作。非常感谢。 – user3658423