这是我的结构:
文件1
{
"people": [
{
"name": "Darrell",
"age": "10",
},
{
"name": "Karen",
"age": "20",
},
{
"name": "Gary",
"age": "30",
}
]
}
文件2
{
"people": [
{
"name": "Karen",
"age": "25",
},
{
"name": "Gary",
"age": "30",
}
]
}
现在,如何在与查询匹配的单个数组元素上执行计数聚合?
答案 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"
}
}
}
}
}
}'