【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 的性能和存储效率,满足不同的检索需求。

相关推荐
一个处女座的暖男程序猿4 小时前
2G2核服务器安装ES 7X版本
服务器·elasticsearch·jenkins
jiuweiC4 小时前
常用es sql
大数据·sql·elasticsearch
GeminiJM6 小时前
优化Elasticsearch批量写入性能:从单分片瓶颈到多索引架构
elasticsearch·架构·jenkins
Elasticsearch7 小时前
通过混合搜索重排序提升多语言嵌入模型的相关性
elasticsearch
Elastic 中国社区官方博客1 天前
Elastic AI agent builder 介绍(三)
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索
zjshuster1 天前
elastic search 学习
学习·elasticsearch·jenkins
Darenm1111 天前
Git介绍
大数据·elasticsearch·搜索引擎
光仔December1 天前
【Elasticsearch入门到落地】18、Elasticsearch实战:Java API详解高亮、排序与分页
java·elasticsearch·es排序·es分页·es高亮
月屯1 天前
es大页读取
大数据·elasticsearch·搜索引擎