Retrieve inner hits 是 Elasticsearch 中的一个功能,用于在嵌套查询或父子查询中,返回导致主文档匹配的具体嵌套对象或子/父文档的详细信息,帮助用户更直观地理解查询结果的来源。
在 Elasticsearch 中,`Retrieve inner hits`是一个功能强大的特性,用于在嵌套查询(`nested`)或父子查询(`has_child`/`has_parent`)中检索匹配的嵌套对象或子/父文档。它允许用户不仅能看到主文档的匹配,还能看到导致主文档匹配的具体嵌套对象或子/父文档。
1.什么是`inner_hits`?
`inner_hits`的主要作用是返回导致主文档匹配的具体嵌套对象或子/父文档。在嵌套查询中,主文档可能包含多个嵌套对象,而`inner_hits`可以明确指出是哪些嵌套对象导致了主文档的匹配。
2.使用场景
假设你有一个包含嵌套对象的文档结构,例如:
```json
PUT test/_doc/1?refresh
{
"title": "Test title",
"comments": [
{ "author": "kimchy", "number": 1 },
{ "author": "nik9000", "number": 2 }
]
}
```
如果你希望查询`number`字段为`2`的评论,并且想看到是哪个评论导致了主文档的匹配,可以使用`inner_hits`。
3.查询示例
以下是一个使用`inner_hits`的查询示例:
```json
POST test/_search
{
"query": {
"nested": {
"path": "comments",
"query": {
"match": { "comments.number": 2 }
},
"inner_hits": {} // 添加 inner_hits
}
}
}
```
4.响应结构
查询的响应将包含`inner_hits`部分,明确指出匹配的嵌套对象:
```json
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "1",
"_score": 1.0,
"_source": {
"title": "Test title",
"comments": [
{ "author": "kimchy", "number": 1 },
{ "author": "nik9000", "number": 2 }
]
},
"inner_hits": {
"comments": {
"hits": {
"total": { "value": 1, "relation": "eq" },
"max_score": 1.0,
"hits": [
{
"_index": "test",
"_id": "1",
"_nested": { "field": "comments", "offset": 1 },
"_score": 1.0,
"_source": { "author": "nik9000", "number": 2 }
}
]
}
}
}
}
]
}
}
```
在这个响应中:
• 主文档`_id`为`1`的文档被检索出来。
• `inner_hits`明确指出了是哪个嵌套对象(`{"author": "nik9000", "number": 2}`)导致了主文档的匹配。
5.性能优化
为了优化性能,可以设置`_source: false`并使用`docvalue_fields`,避免解析`_source`:
```json
POST test/_search
{
"query": {
"nested": {
"path": "comments",
"query": {
"match": { "comments.number": 2 }
},
"inner_hits": {
"_source": false,
"docvalue_fields": ["comments.number"]
}
}
}
}
```
这种方式可以减少查询的解析时间和响应大小。
6.不使用`inner_hits`的区别
如果不使用`inner_hits`,查询只会返回主文档的`_source`,而不会明确指出是哪个嵌套对象导致了匹配。例如:
```json
POST test/_search
{
"query": {
"nested": {
"path": "comments",
"query": {
"match": { "comments.number": 2 }
}
}
}
}
```
响应中将不包含`inner_hits`部分,只返回主文档的内容。
7.总结
• `inner_hits`的作用:明确指出导致主文档匹配的具体嵌套对象或子/父文档。
• 性能优化:通过设置`_source: false`和`docvalue_fields`,可以减少查询的解析时间和响应大小。
• 适用场景:当你需要调试查询或分析具体是哪些嵌套对象导致了主文档匹配时,`inner_hits`是非常有用的工具。
希望这些信息能帮助你更好地理解和使用 Elasticsearch 的`Retrieve inner hits`功能!