文章目录
一、定义
映射(mapping)即是模式定义(schema definition)。一个映射定义了字段类型,每个字段的数据类型,以及字段被 Elasticsearch 处理的方式。映射还用于设置关联到类型上的元数据。
可以说,映射就是对索引库中索引的字段名称及其数据类型进行定义,类似于 mysql 中的表结构信息。
映射可以分为动态映射和显式映射。
1.1、动态映射 (dynamic mapping)
在关系数据库中,需要事先创建数据库,然后在该数据库实例下创建数据表,然后才能在该数据表中插入数据。而 ElasticSearch中 不需要事先定义映射(Mapping),文档写入 ElasticSearch 时,会根据文档字段自动识别类型,这种机制称之为动态映射。
# 动态映射:如果 mapping 没有创建,elasticsearch 将会根据写入的数据的 key 自行创建相应的 mapping,并写入数据
curl -H "Content-Type: application/json" -XPUT localhost:9200/sports/basketball/123 -d '
{
"date": "2018-05-20",
"title": "Cavaliers",
"content": "They are real Cavaliers tonigiht",
"author_id": 520
}'
# 可以使用 _mapping 查询索引的 mapping
curl -XGET localhost:9200/sports/basketball/_mapping?pretty
# 返回结果
{
"sports" : {
"mappings" : {
"basketball" : {
"properties" : {
"author_id" : {
"type" : "long"
},
"content" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"date" : {
"type" : "date"
},
"title" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
}
1.2、显式映射(explicit mappings)
在 ElasticSearch 中也可以事先定义好映射,包含文档的各个字段及其类型等,这种方式称之为显式映射。
# 静态映射,手动设置
curl -H "Content-Type: application/json" -XPUT localhost:9200/books?pretty -d '
{
"settings": {
"number_of_shards": 3,
"number_of_replicas"