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`功能!