elasticsearch 从 _source 与 stored_fields 获取数据不一致?

2022-07-15 09:29:42

elasticsearch 从 _source 与 stored_fields 获取数据不一致?

问题

如题:elasticsearch 从 _source 与 stored_fields 获取数据不一致?

大伙都知道,使用 elasticsearch 进行数据存储的时候,查询数据会默认存储在_source中,但是若开启了store 存储(默认关闭),那么,就可以使用 stored_fields 进行查询。

但是查询出来的数据,有时候会和预想的结果不一致,那么我们来探究一下。

探索

设置一个mapping

PUT store_test_document{"mappings":{"properties":{"title":{"type":"text","store":true},"date":{"type":"date","store":true},"content":{"type":"text"}}}}

将 title 与 date 两个字段 store设置为 true,那么,这两个字段将能被 stored_fields 所查询。
接下来存储一条数据

PUT store_test_document/_doc/1{"title":"Some short title","date":"2022-02-13","content":"A very long content field..."}

先进行普通查询:

GET store_test_document/_search{"_source":["title","date"]}
/************ result *************/{"_index":"store_test_document","_type":"_doc","_id":"1","_score":1.0,"_source":{"date":"2022-02-13","title":"Some short title"}}

我们能看到结果数据和预期的一致,那么再进行 stored_fields 查询呢?

GET store_test_document/_search{"stored_fields":["title","date"]}
/************ result *************/{"_index":"store_test_document","_type":"_doc","_id":"1","_score":1.0,"fields":{"date":["2022-02-13T00:00:00.000Z"],"title":["Some short title"]}}

我们发现,查询的结果并不是我们所希望的,它被数组所包装,那么这是为什么呢?其实,官方文档已经给出了解释。

For consistency, stored fields are always returned as an array because there is no way of knowing if the original field value was a single value, multiple values, or an empty array.
If you need the original value, you should retrieve it from the _source field instead.

由于不清楚使用的人会存啥,所以都以数组的形式进行存储。
如果需要返回原始的值,那么还是得使用 _source 进行查询。

  • 作者:胡歌粉丝
  • 原文链接:https://blog.csdn.net/qq_29064815/article/details/122909447
    更新时间:2022-07-15 09:29:42