ES7.10 父子文档搜索:根据子文档字段进行查询
在 ES7.10 中,你可以使用嵌套字段的方式来搜索父子文档,并根据子文档的特定字段进行过滤。
首先,你需要创建一个父子关系的索引,并将父文档和子文档插入到该索引中。在创建索引时,你需要使用nested类型来定义子文档的字段。
PUT my_index
{
"mappings": {
"properties": {
"parent_field": { // 父文档字段
"type": "text"
},
"child_field": { // 子文档字段
"type": "nested",
"properties": {
"nested_field": { // 子文档中的字段
"type": "text"
}
}
}
}
}
}
接下来,你可以使用nested查询来搜索父子文档。在查询中,你可以通过path参数指定子文档字段的路径,并使用query参数来定义子文档字段的搜索条件。
GET my_index/_search
{
"query": {
"nested": {
"path": "child_field",
"query": {
"match": {
"child_field.nested_field": "keyword" // 根据子文档字段进行搜索
}
}
}
}
}
在这个例子中,通过指定nested查询的path为child_field,并且在match查询中使用child_field.nested_field来指定子文档字段的搜索条件。这将返回匹配指定子文档字段的父文档。
请注意,为了正确地使用嵌套查询,你还需要在搜索请求中设置inner_hits参数,以便返回与查询匹配的子文档。
GET my_index/_search
{
"query": {
"nested": {
"path": "child_field",
"query": {
"match": {
"child_field.nested_field": "keyword"
}
},
"inner_hits": {} // 返回匹配的子文档
}
}
}
这样,你就可以根据子文档的字段进行搜索,并获取与查询匹配的父子文档。
原文地址: https://www.cveoy.top/t/topic/prbI 著作权归作者所有。请勿转载和采集!