如何在 ES 7.3v 中检查 ES 文档的创建时间?

Yas*_*don 0 elasticsearch

我想知道我的文档在elasticsearch中的创建时间,是否有任何元字段保存此信息,或者如果不存在那么我该如何实现它。

我每次都会发出更新插入请求,因此无法提供时间。

更新插入请求是:

POST test/_update/document_id
{
"doc": {
 "field1": "value1",
 "field2": "value2",
 "field3": "value3",
 "relationship": {
  "parent": "child"
 }
},
 "doc_as_upsert": "true"
}
Run Code Online (Sandbox Code Playgroud)

使用elasticsearch npm 和以下代码:

esDoc.doc['relationship'] = { name: "test" };
esDoc['doc_as_upsert'] = true;
bulkQueue.add({ update: { _index: ES_INDEX_PREFIX + testId, _id: _id } }, esDoc)
Run Code Online (Sandbox Code Playgroud)

Val*_*Val 5

实现这一目标的一种方法是利用摄取管道_ingest.timestamp并在文档中记录 的值。

首先创建以下摄取管道:

PUT _ingest/pipeline/set_timestamp
{
  "description": "adds the timestamp when a document is indexed",
  "processors": [
    {
      "set": {
        "field": "indexed_at",
        "value": "{{_ingest.timestamp}}"
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

然后,在为新文档建立索引时,只需在请求中引用该管道即可:

PUT tmp/_doc/1?pipeline=set_timestamp
{
  "test": "foo"
}
Run Code Online (Sandbox Code Playgroud)

您的文档将包含一个名为的新字段,indexed_at其中包含索引的确切时间戳:

GET tmp/_doc/1
{
  "test" : "foo",
  "indexed_at" : "2019-10-03T13:19:03.181Z"
}
Run Code Online (Sandbox Code Playgroud)

更新:

由于您将 Update API 与文档更新插入结合使用,因此您无权访问摄取管道。我建议做的是scripted_upsert,像这样:

POST test/_update/document_id
{
 "scripted_upsert":true,
 "script": {
   "source": """
     // update all fields
     ctx._source.putAll(params); 

     // add timestamp the first time
     if (ctx._source.indexed_at == null) {
        def now = Instant.ofEpochMilli(new Date().getTime());
        ZonedDateTime zdt = ZonedDateTime.ofInstant(now, ZoneId.of('Z'));
        ctx._source.indexed_at = zdt.format(DateTimeFormatter.ISO_INSTANT);
     }
   """,
   "params": {
     "field1": "value1",
     "field2": "value2",
     "field3": "value3",
     "relationship": {
       "parent": "child"
     }
   }
 },
 "upsert": {}
}
Run Code Online (Sandbox Code Playgroud)