Elasticsearch修改mapping
Elasticsearch修改mapping
背景:
ES不支持直接修改mapping,修改mapping实质上是重建索引,为了实现平滑过渡,需要一开始给用到的索引起别名,平常使用的是索引的别名,只需要修改别名对应的索引就可以实现平滑过度了。
实现:
重新构建索引:
-
给原来的索引
old_index
设置一个别名my_index
(这一步在需要修改之前就已经操作,编辑程序用的是别名):curl -XPOST localhost:9200/_aliases -d ' { "actions": [ { "add": { "alias": "my_index", "index": "old_index" }} ] }
-
重新创建一个新的索引
new_index
,配置需要的字段属性
curl -XPUT localhost:9200/new_index
{
"mappings": {
"doc": {
"properties": {
"id": {
"type": "long"
},
"user_id": {
"type": "long"
}
}
}
},
"settings": {
"index": {
"number_of_shards": "5",
"number_of_replicas": "1"
}
}
}
-
数据迁移
curl-XPOST localhost:9200/_reindex { "source": { "index": "old_index" }, "dest": { "index": "new_index" } }
-
新索引设置别名为
my_index
,同时删除别名对旧索引的指向
curl -XPOST localhost:9200/_aliases -d '
{
"actions": [
{ "remove": {
"alias": "my_index",
"index": "old_index"
}},
{ "add": {
"alias": "my_index",
"index": "new_index"
}}
]
} '
- 删除旧索引(可以不删除,可随时切换)
curl -XDELETE localhost:9200/old_index
除此之外,还有几个其他的方法也可以更改mapping。
- 修改程序,添加字段。
就是说,你可以在mapping中增加一个新的字段,然后你对新的字段进行访问统计搜索。这个就要修改两个地方,一个是修改mapping增加字段,还有就是修改你的程序,把字段改成新的字段。
- 更改字段类型为multi_field。
multi_field允许为一个字段设置多个数据类型。应用multi_field的一个最典型的场景是:一个类型定义为analyed,这个字段可以被搜索到,一个类型定义为不分词,这个字段用于排序。
任何字段都可以被更新为multi_field(类型为object和nested的类型除外)。假设现在有一个字段,名字叫created,类型现在为string。
{ "created": { "type": "string"} }
我们可以将它增加一种类型,使他既能被当做字符串又能当做日期型。
curl -XPUT localhost:9200/my_index/my_type/_mapping -d '
{
"my_type": {
"properties": {
"created": {
"type": "multi_field",
"fields": {
"created": { "type": "string" },
"date": { "type": "date" }
}
}
}
}
}
'