13

为什么在能够过滤查询时看不到 _timestamp 字段?

以下查询返回正确的文档,但不返回时间戳本身。如何返回时间戳?

{
  "fields": [
    "_timestamp",
    "_source"
  ],
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "range": {
          "_timestamp": {
            "from": "2013-01-01"
          }
        }
      }
    }
  }
}

映射是:

{
    "my_doctype": {
        "_timestamp": {
            "enabled": "true"
        },
        "properties": {
            "cards": {
                "type": "integer"
            }
        }
    }
}

样本输出:

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 2,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "test1",
      "_type" : "doctype1",
      "_id" : "HjfryYQEQL6RkEX3VOiBHQ",
      "_score" : 1.0, "_source" : {"cards": "5"}
    }, {
      "_index" : "test1",
      "_type" : "doctype1",
      "_id" : "sDyHcT1BTMatjmUS0NSoEg",
      "_score" : 1.0, "_source" : {"cards": "2"}
    }]
  }
4

2 回答 2

15

启用时间戳字段后,默认情况下会对其进行索引但不存储。因此,虽然您可以按时间戳字段进行搜索和过滤,但您无法通过记录轻松检索它。为了能够检索时间戳字段,您需要使用以下映射重新创建索引:

{
    "my_doctype": {
        "_timestamp": {
            "enabled": "true",
            "store": "yes"
        },
        "properties": {
            ...
        }
    }
}

这样,您将能够检索时间戳作为自纪元以来的毫秒数。

于 2013-03-27T10:19:53.867 回答
6

没有必要存储时间戳字段,因为它的确切值被保存为一个术语,它也更有可能已经存在于 RAM 中,特别是如果您正在查询它。您可以使用以下术语通过时间戳访问时间戳script_value

{
    "query": {
        ...
    },
    "script_fields": {
        "timestamp": {
            "script": "_doc['_timestamp'].value"
        }
    }
}

结果值以自 UNIX 纪元以来的毫秒数表示。ElasticSearch 无法为您做到这一点,这真是太可耻了,但是,嘿,没有什么是完美的。

于 2014-11-18T02:13:50.330 回答