2013-03-27 90 views
13

为什么我不能看到_timestamp字段,同时能够通过它过滤查询?返回elasticsearch中的时间戳字段

以下查询返回正确的文档,但不是时间戳本身。我怎样才能返回时间戳?

{ 
    "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"} 
    }] 
    } 

回答

15

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

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

这样,您就能够检索时间戳,因为时代的毫秒数。

+0

谢谢。 作为一个旁注,如果我现在在现有索引上更新我的映射,新记录是否将存储时间戳记存储为旧时间?还是会将旧记录存储起来? – eran 2013-03-28 07:10:41

+10

您将无法在现有类型上更新此映射。 _timestamp映射只能在创建类型时设置。 – imotov 2013-03-28 10:14:32

5

没有必要存储时间戳字段,因为它的确切值是作为一个术语保存的,这也更可能已经存在于RAM中,尤其是在查询时。您可以使用script_value通过其任期访问时间戳:

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

结果值将在自UNIX纪元毫秒表示。 ElasticSearch无法为您做到这一点很猥琐,但是,嘿,没有什么是完美的。

+2

这是一个很好的解决方案,但只有在稍作修改之后:'script_fields'而不是'script_values',并且自1.4.3脚本必须存在于文件中,根据[this](http://www.elasticsearch.org/)引导/ EN/elasticsearch /参考/电流/模块-scripting.html)。 – Juliano 2015-02-20 13:30:43

+2

完全不起作用。必须如上所述将'script_values'更改为'script_fields',并且必须将_doc ['timestamp']'更改为'_doc ['_ timestamp']'。只从存储了_timestamp的类型中返回正确的值,对于其他文件只返回0。 – csauve 2015-05-22 19:23:28