【Elasticsearch】stored_fields

在 Elasticsearch 中,`stored_fields` 是一个非常重要的概念,主要用于控制文档存储和检索时的行为。以下是对 `stored_fields` 的详细解释:

1\. `stored_fields` 的作用

`stored_fields` 用于指定在检索文档时需要返回的字段。默认情况下,Elasticsearch 在索引文档时会将所有字段存储在 `_source` 中,而 `_source` 是一个 JSON 格式的字段,包含了完整的文档内容。但是,有时我们并不需要检索整个 `_source`,而是只需要某些特定字段。通过设置 `stored_fields`,可以优化检索性能和存储空间。

2\. 使用场景

  • 优化性能:如果只需要检索文档中的某些字段,而不是整个 `_source`,设置 `stored_fields` 可以减少数据传输量,从而提高检索性能。

  • 节省存储空间:在某些情况下,某些字段可能不需要存储,或者只需要存储部分字段用于检索,这样可以节省磁盘空间。

  • 提高安全性:在某些场景下,某些字段可能包含敏感信息,通过设置 `stored_fields`,可以避免这些字段被检索或返回。

3\. 如何设置 `stored_fields`

在索引映射中设置

在创建索引时,可以通过映射(mapping)来指定哪些字段需要存储。例如:

```json

PUT /my_index

{

"mappings": {

"properties": {

"field1": {

"type": "text",

"store": true // 设置为 true 表示存储该字段

},

"field2": {

"type": "keyword",

"store": false // 设置为 false 表示不存储该字段

}

}

}

}

```

  • `store: true` 表示该字段会被单独存储,可以在检索时通过 `stored_fields` 参数返回。

  • `store: false` 表示该字段不会被单独存储,只能通过 `_source` 获取。

在检索时使用 `stored_fields` 参数

在查询文档时,可以通过 `stored_fields` 参数指定需要返回的字段。例如:

```json

GET /my_index/_search

{

"query": {

"match_all": {}

},

"stored_fields": ["field1", "field2"] // 指定返回的字段

}

```

如果字段被设置为 `store: true`,则可以通过 `stored_fields` 参数返回该字段的值。如果字段没有被存储(`store: false`),则无法通过 `stored_fields` 返回,只能通过 `_source` 获取。

4\. `stored_fields` 与 `_source` 的区别

  • 存储方式:

  • `_source` 是一个 JSON 格式的字段,包含完整的文档内容,存储在 Lucene 的 `_source` 字段中。

  • `stored_fields` 是单独存储的字段,存储在 Lucene 的存储字段中,可以单独检索。

  • 检索性能:

  • 检索 `_source` 时,需要解析整个 JSON 数据,性能相对较低。

  • 检索 `stored_fields` 时,直接返回存储的字段值,性能更高。

  • 适用场景:

  • `_source` 适用于需要完整文档内容的场景,例如更新文档、重新索引等。

  • `stored_fields` 适用于只需要部分字段的场景,例如快速检索某些字段的值。

5\. 注意事项

  • 存储成本:虽然 `stored_fields` 可以提高检索性能,但存储字段会占用额外的磁盘空间。因此,需要根据实际需求合理选择存储的字段。

  • 字段类型:某些字段类型(如 `text` 类型的字段)在存储时会占用较多空间,需要谨慎使用。

  • 更新字段:如果需要更新存储的字段,需要重新索引文档,因为存储的字段在文档索引后无法直接修改。

通过合理使用 `stored_fields`,可以优化 Elasticsearch 的性能和存储效率,满足不同的检索需求。

相关推荐
33255_40857_280595 小时前
ElasticSearch实战指南:从零部署到Java高效集成
java·elasticsearch
G皮T9 小时前
【ELasticsearch】集群故障模拟方案(一):节点宕机、节点离线
大数据·elasticsearch·搜索引擎·集群·高可用·故障模拟·容错能力
Freed&11 小时前
部署 Kibana 8.2.2 可视化管理 Elasticsearch 8.2.2 集群
大数据·elasticsearch·搜索引擎
夜斗小神社19 小时前
【黑马SpringCloud微服务开发与实战】(九)elasticsearch基础
elasticsearch·spring cloud·微服务
Elastic 中国社区官方博客1 天前
用于 UBI 的 Elasticsearch 插件:从搜索查询中分析用户行为
大数据·数据库·elasticsearch·搜索引擎·全文检索
wdfk_prog1 天前
实战指南:如何将Git仓库中的特定文件夹及其历史完整迁移到另一个仓库
大数据·linux·运维·笔记·git·学习·elasticsearch
乌萨奇也要立志学C++1 天前
【Linux】linux基础开发工具(三) 版本控制器Git、调试器 - gdb/cgdb使用、一些实用的调试技巧
linux·git·elasticsearch
阿乾之铭2 天前
Elasticsearch
elasticsearch·搜索引擎
程序员编程指南3 天前
Qt 开发 IDE 插件开发指南
c语言·c++·ide·qt·elasticsearch
谷新龙0013 天前
Elasticsearch服务器开发(第2版) - 读书笔记 第二章 索引
服务器·elasticsearch