Elasticsearch(六)-映射&数据迁移
首先我们需要知道ES7以后的一个改动:
ES7 及以上移除了 type 的概念。
关系型数据库中两个数据表是独立的,即使他们里面有相同名称的列也不影响使用,但ES中不是这样的。 elasticsearch 是基于 Lucene 开发的搜索引擎,而 ES 中不同type下名称相同的 filed 最终在 Lucene 中的处理方式是一样的。
两个不同 type 下的两个 user_name,在ES同一个索引下其实被认为是同一个 filed,你必须在两个不同的 type 中定义相同的 filed 映射。否则,不同 type 中的相同字段名称就会在处理中出现冲突的情况,导致 Lucene 处理效率下降。
去掉type就是为了提高 ES 处理数据的效率。
Elasticsearch 7.x:
URL中的 type 参数为可选。比如,索引一个文档不再要求提供文档类型。
Elasticsearch 8.x:
不再支持URL中的type参数。
1)字段类型
核心类型字符串(string)
text,keyword
数字类型(Numeric)
long, integer, short, byte, double, float, half_float, scaled_float
日期类型(Date)
date
布尔类型(Boolean)
boolean
二进制类型(Binary)
binary
复合类型数组类型(Array)
Array 支持不针对特定的数据类型
对象类型(Object)
object 用于单个JSON对象的对象
嵌套类型(Nested)
nested 用于JSON对象的数组
地理类型(Geo)地理坐标(Geo-point)
geo_point 纬度/经度坐标
地理圆形(Geo-shape)
geo_shape 用于多边形等复杂形状
特定类型IP 类型(IP)
ip 用于描述 IPv4 和 IPv6 地址
补全类型(Completion)
completion 提供自动完成提示
令牌计数类型(Token count)
token_count 用来统计字符串中词条的数量
附件类型(attachment)
参考 mapper-attachments 插件,支持将附件例如Microsoft Office格式,open document格式,ePub,HTML等索引为 attachment 数据类型。
抽取类型(Percolator)
接受来自领域特定语言(query-dsl)的查询
2)映射
映射是定义文档及其包含的字段的存储和索引方式的过程。
哪些字符串字段应视为全文字段。
哪些字段包含数字,日期或地理位置。
日期值的格式。
自定义规则,用于控制动态添加字段的映射 。
3)使用
查看 mapping 信息:
GET bank/_mapping
创建索引并指定映射:
PUT /my-index
{
"mappings": {//映射规则
"properties": {
"age": { "type": "integer" },
"email": { "type": "keyword" },//keyword不会进行全文检索
"name": { "type": "text" }//text保存的时候进行分词,搜索的时候进行全文检索
}
}
}
如果不设置mapping信息,那么ES会根据你的值自动设置相应的类型。
添加新的字段映射PUT /my-index/_mapping
{
"properties": {
"employee-id": {
"type": "keyword",
"index": false//索引选项控制是否对字段值建立索引。 它接受true或false,默认为true。未索引的字段不可查询。也就是控制这个字段是否参与检索。
}
}
}
更新映射
对于已经存在的映射字段,我们不能更新。更新必须创建新的索引进行数据迁移。
4)数据迁移
先创建出 twitter 的正确映射。然后使用如下方式进行数据迁移:
#7.x 之后的写法
POST _reindex//固定写法
{
"source": {//老索引
"index": "twitter"
},
"dest": {//目标索引
"index": "new_twitter"
}
}
#7.x之前的带 type 的写法
将旧索引的 type 下的数据进行迁移
POST _reindex//固定写法
{
"source": {
"index": "twitter", //老索引
"type": "twitter", //老类型
},
"dest": {//目标索引
"index": "new_twitter"
}
}
举例:
将bank索引下,account类型的数据进行迁移。
创建一个新的索引:PUT /newbank
{
"mappings": {
"properties": {
"account_number": {
"type": "long"
},
"address": {
"type": "text"
},
"age": {
"type": "integer"
},
"balance": {
"type": "long"
},
"city": {
"type": "keyword"
},
"email": {
"type": "keyword"
},
"employer": {
"type": "keyword"
},
"firstname": {
"type": "text"
},
"gender": {
"type": "keyword"
},
"lastname": {
"type": "text"
},
"state": {
"type": "keyword"
}
}
}
}
数据迁移:
POST _reindex
{
"source": {
"index": "bank",
"type": "account"
},
"dest": {
"index": "newbank"
}
}
查看迁移后的结果:
GET newbank/_search