Elasticsearch中怎么对mapping进行修改

2023-05-16,

Elasticsearch中怎么对mapping进行修改,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

旧索引信息如下:

index:test_v1

type:item

alias:item_alias

mapping:

{
  "properties": {
    "itemId": {
      "type": "long"
    },
    "itemName": {
      "type": "text",
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_smart"
    }
  }
}

添加字段:

使用最新的mapping直接调用putMapping接口

PUT http://xxx.xxx.xxx.xxx:9200/goods_info/_mapping
{
  "properties": {
    "itemId": {
      "type": "long"
    },
    "itemName": {
      "type": "text",
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_smart"
    },
    "brandName": {
      "type": "text",
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_smart"
    }
  }
}

修改字段:

      由于Elasticsearch底层使用了lucene的原因,不支持对mapping的修改,可使用索引重建的方式,步骤如下:

1,使用正确的mapping新建索引和类型

     如需要将旧索引的itemId字段改为keyword类型,则执行以下请求:

创建index:

PUT /test_v2

设置mapping:

POST /test_v2/item/_mapping

{

  "properties": {
    "itemId": {
      "type": "keyword"
    },
    "itemName": {
      "type": "text",
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_smart"
    }
  }
}

2,使用reindex api将旧索引数据导入新索引

索引重建后可使用reindex命令迁移数据,如将test_v1数据迁移至test_v2请求如下:

POST _reindex

{
  "source": {
    "index": "test_v1",
    "type": "item"
  },
  "dest": {
    "index": "test_v2",
    "type": "item"
  }
}

3,为新索引添加别名

      为索引添加别名后,在程序代码中可以使用固定别名查询动态的索引名称,然后进行查询,如此索引重建则不会引起程序的变动

添加别名请求:

POST /_aliases

{
    "actions": [
        { "add": {
            "alias": "item_alias",
            "index": "test_v2"
        }}
    ]
}

将旧索引别名迁移到新索引请求:
  

POST /_aliases

{
    "actions" : [
        { "remove" : { "index" : "test_v1", "alias" : "item_alias" } },
        { "add" : { "index" : "test_v2", "alias" : "item_alias" } }
    ]
}

看完上述内容,你们掌握Elasticsearch中怎么对mapping进行修改的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注本站行业资讯频道,感谢各位的阅读!

《Elasticsearch中怎么对mapping进行修改.doc》

下载本文的Word格式文档,以方便收藏与打印。