Elasticsearch 7.13 多层嵌套对象查询如何仅返回匹配的内层嵌套结果
问题原因
你当前的查询仅能筛选出「存在符合profile.id条件且profile.following中至少有一条符合搜索词」的父文档,但默认会返回该文档下profile.following的全部条目,不会过滤不匹配的内层嵌套对象。你需要借助inner_hits参数获取仅匹配过滤条件的嵌套条目。
修改后的查询参数
let params: RequestParams.Search = { index: index, body: { size: 30, // 关闭原始source返回,仅取需要的inner_hits减少数据传输 _source: false, query: { bool: { must: [ { nested: { path: "profile", query: { bool: { must: [ { match: { "profile.id": profileId } } ] } } } } ], filter: [ { nested: { path: "profile.following", ignore_unmapped: true, query: { query_string: { fields: [ "profile.following.name", "profile.following.username" ], query: searchWord + "*" } }, // 新增inner_hits配置,仅返回匹配过滤条件的following条目 inner_hits: { // 如果需要对匹配的following结果排序,可在此添加sort配置 // sort: [{ "profile.following.name.keyword": "asc" }] } } } ] } } } };
结果提取方式
查询返回后,可通过以下逻辑整理得到你期望的返回结构:
const res = body.hits.hits.flatMap(hit => hit.inner_hits['profile.following'].hits.hits.map(item => item._source) );
内容的提问来源于stack exchange,提问作者Victor Ezequiel
相关产品推荐
相关产品推荐

