映射:詳解 _source & store 字段
- 1._source 字段
- 1.1 特點
- 1.2 示例
- 2.store 字段
- 2.1 特點
- 2.2 示例
- 3.兩者對比
- 3.1 使用建議
- 3.2 實際應用示例
1._source 字段
_source
是 Elasticsearch 中一個特殊的元字段,它存儲了文檔在索引時的原始 JSON 內容。
1.1 特點
- 默認啟用:所有文檔都會自動存儲原始 JSON 數據在
_source
中。 - 完整存儲:保存文檔的完整原始結構。
- 重要用途:
- 返回搜索結果中的原始文檔內容。
- 支持高亮顯示。
- 支持重新索引操作。
- 支持更新文檔(因為需要原始內容)。
1.2 示例
PUT my_index/_doc/1
{"title": "Elasticsearch Guide","author": "John Doe","content": "This is a comprehensive guide..."
}GET my_index/_doc/1
返回結果中會包含完整的 _source
內容。
禁用 _source
。
PUT my_index
{"mappings": {"_source": {"enabled": false}}
}
禁用后無法獲取原始文檔內容,且某些功能將不可用。
2.store 字段
store
是字段級別的屬性,決定是否將字段值單獨存儲在 Lucene 中(獨立于 _source
)。
2.1 特點
- 默認關閉:大多數情況下不需要單獨存儲字段。
- 特定場景使用:
- 當只需要檢索個別字段,而不需要整個
_source
時。 - 當
_source
被禁用,但仍需要某些字段時。
- 當只需要檢索個別字段,而不需要整個
- 存儲方式:以列式存儲,單獨存儲。
2.2 示例
PUT my_index
{"mappings": {"properties": {"title": {"type": "text","store": true },"content": {"type": "text"}}}
}
檢索存儲字段。
GET my_index/_search
{"stored_fields": ["title"]
}
3.兩者對比
特性 | _source 字段 | store 屬性 |
---|---|---|
存儲級別 | 文檔級(整個原始文檔) | 字段級(單個字段) |
默認值 | 啟用 | 禁用 |
存儲方式 | 原始 JSON | 單獨列式存儲 |
主要用途 | 獲取完整文檔、重新索引、更新等操作 | 高效檢索特定字段 |
存儲開銷 | 較高(存儲完整文檔) | 較低(只存儲指定字段) |
檢索方式 | 通過 _source 獲取 | 通過 stored_fields 獲取 |
3.1 使用建議
- 大多數情況:保持
_source
啟用,不需要設置store: true
。 - 禁用
_source
時:對需要檢索的字段設置store: true
。 - 性能優化:當文檔很大但只需要少量字段時,可考慮存儲特定字段。
- 注意:存儲字段會增加索引大小,應謹慎使用。
3.2 實際應用示例
PUT news_articles
{"mappings": {"_source": {"enabled": true},"properties": {"headline": {"type": "text","store": true},"body": {"type": "text"},"publish_date": {"type": "date","store": true}}}
}
這樣設計可以:
- 通過
_source
獲取完整文章內容。 - 快速單獨訪問
headline
和publish_date
字段(如用于列表展示)。 body
內容只通過_source
獲取,減少存儲開銷。