簡體   English   中英

如何使用默認值“現在”索引日期字段?

[英]How can I index a date field with the default value of “now”?

我需要添加一個日期字段類型,以便文檔將當前系統日期時間作為默認值。 我正在使用 Elasticsearch 7.5。

PUT /myindex/_mappings
{
     "properties": {    
       "create_date": {
         "type": "date",
         "format": "yyyy-MM-dd HH:mm:ss",
         "null_value": "now"
       }
     }
}

Elasticsearch 中沒有這樣的功能。 至少不是直接的。

但是,您可以做的是創建一個攝取管道,從腳本處理器內部分配當前日期時間:

PUT _ingest/pipeline/auto_now_add
{
  "description": "Assigns the current date if not yet present",
  "processors": [
    {
      "script": {
        "source": """
          // don't overwrite if present
          if (ctx['create_date'] == null) {
            ctx['create_date'] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
          }
        """
      }
    }
  ]
}

之后,當您PUT索引時,您將指定default_pipeline

PUT myindex
{
  "settings": {
    "index": {
      "default_pipeline": "auto_now_add"     <---
    }
  },
  "mappings": {
    "properties": {
      "create_date": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss"
      }
    }
  }
}

然后,當您插入缺少create_date的文檔時:

PUT myindex/_doc/1
{
  "abc": "def"
}

Elasticsearch 將自動添加當前時間戳。 驗證:

POST myindex/_search

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM