1.1 什么是映射
(1) 映射(mapping): 定义index的元数据, 指定要索引并存储的文档的字段类型.
也就是说映射决定了Elasticsearch在建立倒排索引、进行检索时对文档采取的相关策略, 如数字类型、日期类型、文本类型等等.
需要注意的是: 检索时用到的分析策略, 要和建立索引时的分析策略相同, 否则将导致数据不准确.
1.2 映射的组成
每个index都有一个type, 每个type对应一个mapping.
在Elasticsearch 6.X版本开始, 1个index只能有1个type.
2.2 更新mapping
(1) 必读说明:
-
映射一旦创建完成, 就不允许修改:
—— Elasticsearch对文档的分析、存储、检索等过程, 都是严格按照mapping中的配置进行的. 如果允许后期修改mapping, 在检索时对索引的处理将存在不一致的情况, 导致数据检索行为不准确.
-
只能在创建index的时候手动配置mapping, 或者新增field mapping, 但是不能update field mapping.
(2)更新mapping出现异常:
-
修改已经创建好的mapping
PUT website { "mappings": { "user": { "properties": { "author_id": { "type": "text" } } } } }
-
抛出如下错误 —— 索引已经存在的异常:
{ "error": { "root_cause": [ { "type": "resource_already_exists_exception", "reason": "index [website/mVYk4-a7RMOZbkcCp2avfw] already exists", "index_uuid": "mVYk4-a7RMOZbkcCp2avfw", "index": "website" } ], "type": "resource_already_exists_exception", "reason": "index [website/mVYk4-a7RMOZbkcCp2avfw] already exists", "index_uuid": "mVYk4-a7RMOZbkcCp2avfw", "index": "website" }, "status": 400 }
(3) 向已有mapping中添加字段及其映射信息:
PUT website/_mapping/user // 修改user类型的_mapping, 注意API的顺序
{
"properties": {
"new_field": {
"type": "text",
"index": false
}
}
}
2.3 查看mapping
(1) 查看mapping的API:
GET website/_mapping
(2) 查看的结果信息如下:
{
"website" : {
"mappings" : {
"user" : {
"_all" : {
"enabled" : false // 禁用元字段_all
},
"properties" : {
"address" : {
"type" : "text",
"index" : false // 不索引
},
"age" : {
"type" : "integer"
},
"birthday" : {
"type" : "date"
},
"name" : {
"type" : "text",
"analyzer" : "english"
},
"new_field" : { // 后期添加的新字段
"type" : "text",
"index" : false // 不索引
},
"sex" : {
"type" : "keyword"
},
"user_id" : {
"type" : "text"
}
}
}
}
}
}