2013-03-27 87 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