如何返回列表中匹配多个字段的文档?
示例:
每份文件都包含有关大学的信息。
其中一个字段是以下格式的学生列表:
"students": [
{"name":"John", "age":23},
{"name":"Joe", "age":65},
{"name":"John","age":12}
]
因此,文档1有自己的学生列表,文档2有自己的学生列表等。
如何查询返回所有大学(文件),这些大学(文件)的学生名为“John”,年龄至少为21岁?
答案 0 :(得分:2)
您应该将学生定义为映射中的嵌套字段,以便能够执行此类查询。
{
"mappings": {
"university": {
"properties": {
"students": {
"type": "nested"
}
}
}
}
}
然后你的查询非常简单
{
"query": {
"nested": {
"path": "students",
"query": {
"bool": {
"must": [
{ "match": { "students.name": "John" }},
{ "range": {"students.age": {"gte": 21}}}
]
}
}
}
}
}
如果有名叫约翰的学生年龄至少为21岁,它将返回每份文件。