映射配置与关系数据库中表的DDL类似,在ES中映射时定义文档的过程,定义了文档包含哪些字段,并对文档字段是否保存、是否索引、是否分词等进行设置。
1、查看映射字段
GET /索引名/_mapping
详情如下:
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118164551468-201884896.png)
2、创建映射字段
创建映射字段语法:
PUT /索引库名/_mapping/类型名称 { "properties": { "字段名": { "type": "类型", "index": true, "store": true, "analyzer": "分词器" } } }
类型名称,类似于数据库中的不同表;字段名,类似于表中的列名;properties下可以指定多个字段,每个字段有很多属性。
属性 |
含义 |
说明 |
type |
字段类型 |
text、long、short、date、integer、object、keyword |
index |
字段是否可被索引 |
true/false |
store |
字段是否可被存储 |
true/false |
analyzer |
分词器 |
ik分词器:ik_max_word或者ik_smart |
text与keyword字段类型的区别:
text |
keyword |
会分词,然后进行索引 |
不进行分词,直接索引 |
支持模糊、精确查询 |
支持模糊、精确查找 |
分词器默认standard,对于中文而言是按字分词 |
支持按字数建立索引,以便节约索引空间 |
支持fields属性,可以在fields中添加keyword子类型,以实现精确检索 |
text的分词规律 |
创建索引字段:
# 创建映射字段 PUT /mapping_index { "mappings": { "properties": { "name": {"type": "text", "store": false}, "age": {"type": "integer", "index": true}, "address": {"type": "text", "analyzer": "standard"} } } }
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118164551014-2096067180.png)
查看创建的映射字段,映射字段属性的默认值,默认不存储且可被索引。
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118164551498-772036026.png)
3、新增映射字段
索引的映射关系创建完成后,添加新的字段映射有两种方式,第一种是删除索引,映射关系调整后再新建索引;第二是在已有的基础上新增。
# 新增一个映射字段 PUT /mapping_index/_mapping { "properties":{ "stuno":{ "type":"keyword" ,"index":false } } }
新增映射字段。
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118164551274-1243746658.png)
4、更新映射字段
已经存在的映射字段无法更新,需要创建新的索引来进行数据迁移。迁移语法格式如下:
POST _reindex { "source":{ "index":"index_source" }, "dest":{ "index":"index_target" } }
老的数据有type的情况,迁移语法格式如下:
POST _reindex { "source":{ "index":"index_source", "type":"account" }, "dest":{ "index":"index_target" } }
4.1、初始化数据
# 初始化数据 POST /mapping_index/_doc/1?pretty=true { "name": "zs", "age": 20, "address": "河南", "stuno": 20220125 } POST /mapping_index/_doc/2?pretty=true { "name": "ls", "age": 18, "address": "杭州", "stuno": 20220126 }
查看数据添加情况:
GET /mapping_index/_search { "query": {"match_all": {}} }
4.2、创建新的索引
# 创建新的索引 PUT /new_mapping_index { "mappings": { "properties": { "name": {"type": "text", "store": false}, "age": {"type": "integer", "index": true}, "address": {"type": "text", "analyzer": "standard"}, "stuno":{"type":"keyword","index":false} } } } # 查询 new_mapping_index 的映射 GET /new_mapping_index/_mapping
详情如下:
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118164937922-915105323.png)
4.3、迁移数据
查询迁移前的 new_mapping_index 索引的文档。
# 查询 new_mapping_index 的文档 GET /new_mapping_index/_search { "query": { "match_all": {} } }
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118165108439-1178229248.png)
数据迁移:
# 迁移数据 POST _reindex { "source":{ "index":"mapping_index" }, "dest":{ "index":"new_mapping_index" } }
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118165108537-1854060895.png)
查询迁移后的 new_mapping_index 索引的文档。
![0](/i/l/?n=24&i=blog/1680081/202401/1680081-20240118165108961-916152394.png)