如何使用默认值 "now" 索引日期字段?
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 中没有这样的功能。至少不是直接的。
但是,您可以做的是创建一个 ingest pipeline that assigns the current datetime from inside a script processor:
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
你的索引时,你会 specify the 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
我需要添加一个日期字段类型,以便文档将当前系统日期时间作为默认值。我正在使用 Elasticsearch 7.5。
PUT /myindex/_mappings
{
"properties": {
"create_date": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss",
"null_value": "now"
}
}
}
Elasticsearch 中没有这样的功能。至少不是直接的。
但是,您可以做的是创建一个 ingest pipeline that assigns the current datetime from inside a script processor:
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
你的索引时,你会 specify the 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