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

x33g5p2x  于2022-02-14 转载在 ElasticSearch  
字(1.8k)|赞(0)|评价(0)|浏览(453)

问题

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

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

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

探索

设置一个mapping

  1. PUT store_test_document
  2. {
  3. "mappings": {
  4. "properties": {
  5. "title": {
  6. "type": "text",
  7. "store": true
  8. },
  9. "date": {
  10. "type": "date",
  11. "store": true
  12. },
  13. "content": {
  14. "type": "text"
  15. }
  16. }
  17. }
  18. }

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

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

先进行普通查询:

  1. GET store_test_document/_search
  2. {
  3. "_source": [
  4. "title",
  5. "date"
  6. ]
  7. }
  8. /************ result *************/
  9. {
  10. "_index" : "store_test_document",
  11. "_type" : "_doc",
  12. "_id" : "1",
  13. "_score" : 1.0,
  14. "_source" : {
  15. "date" : "2022-02-13",
  16. "title" : "Some short title"
  17. }
  18. }

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

  1. GET store_test_document/_search
  2. {
  3. "stored_fields": [
  4. "title",
  5. "date"
  6. ]
  7. }
  8. /************ result *************/
  9. {
  10. "_index" : "store_test_document",
  11. "_type" : "_doc",
  12. "_id" : "1",
  13. "_score" : 1.0,
  14. "fields" : {
  15. "date" : [
  16. "2022-02-13T00:00:00.000Z"
  17. ],
  18. "title" : [
  19. "Some short title"
  20. ]
  21. }
  22. }

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

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 进行查询。

相关文章

最新文章

更多