什么是 mapping ?
映射是定义文档及其包含的字段如何存储和索引的过程。
每个文档都是字段的集合,每个字段都有自己的 数据类型。映射数据时,您会创建一个映射定义,其中包含与文档相关的字段列表。映射定义还包括元数据字段,例如 _source自定义如何处理文档的关联元数据的字段。
使用动态映射和显式映射来定义您的数据。每种方法都会根据您在数据旅程中所处的位置提供不同的好处。例如,显式映射您不想使用默认值的字段,或者更好地控制创建哪些字段。然后,您可以允许 Elasticsearch 动态添加其他字段。
为 index 创建 date mapping
官方文档
有时我们需要自动给 index 中的每一个 document 自动添加当前时间戳时,就可以使用 mapping
curl -XPUT localhost:9200/$IndexName -d '{
"mappings": {
"properties": {
"date": {
"type": "date",
"format": "strict_date_optional_time||epoch_second"
}
}
}
}'
format,自定义日期格式,但如果没有format指定,则使用默认值:
“strict_date_optional_time||epoch_millis”
这意味着它将接受带有可选时间戳的日期,这些时间戳符合strict_date_optional_time 或毫秒以来的时代支持的格式。
有时在脚本中需提前创建 mapping,但又不想每次执行脚本的时候都创建 mapping,虽然重复创建不会失败也不会导致创建很多个,为了规范需要提前判断 index 是否有 mapping
if ! curl -si -XGET http://localhost:9200/$IndexName/_mapping?pretty 2> /dev/null |head -1 |grep 20
then
curl -XPUT http://localhost:9200/$IndexName -H 'Content-Type: application/json' -d '{
"mappings": {
"properties": {
"date": {
"type": "date",
"format": "strict_date_optional_time||epoch_second"
}
}
}
}'
fi
查询 index 的 mapping
curl -XGET localhost:9200/$IndexName/_mapping?pretty
{
"$IndexName": {
"mappings": {
"properties": {
"Label": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"Label_Group": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"busyExecutors": {
"type": "long"
},
"date": {
"type": "date",
"format": "strict_date_optional_time||epoch_second"
},
"idleExecutors": {
"type": "long"
},
"totalExecutors": {
"type": "long"
}
}
}
}
}