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

相关推荐
DavidSoCool8 小时前
Elasticsearch 中实现推荐搜索(方案设想)
大数据·elasticsearch·搜索引擎
文艺倾年17 小时前
【八股消消乐】Elasticsearch优化—检索Labubu
大数据·elasticsearch·搜索引擎
会飞的小妖18 小时前
Elasticsearch相关操作
elasticsearch
Elastic 中国社区官方博客20 小时前
ECK 简化:在 GCP GKE Autopilot 上部署 Elasticsearch
大数据·elasticsearch·搜索引擎·k8s·全文检索·googlecloud
超级小忍20 小时前
Spring Boot 集成 Elasticsearch(含 ElasticsearchRestTemplate 示例)
spring boot·elasticsearch
乐世东方客1 天前
Kafka使用Elasticsearch Service Sink Connector直接传输topic数据到Elasticsearch
分布式·elasticsearch·kafka
m0_719084111 天前
es相关知识
elasticsearch
丁学文武2 天前
Mac 安装ElasticSearch和Kibana详细教程
elasticsearch·macos·langchain·jenkins
risc1234562 天前
【Elasticsearch】TF-IDF 和 BM25相似性算法
elasticsearch
不像程序员的程序媛2 天前
es按时间 小时聚合
java·前端·elasticsearch