解决ES5.x中@Field注解之IK分词不能用的问题(重建索引)

一、概述

环境:ElasticSearch版本5.6.3,SpringBoot 2.0.2.RELEASE,索引myIndex

问题描述:使用@Field注解给实体类指定ik分词解析器(ik_smart/ik_max_word),测试分词功能,发现并不能达到预期的效果,查看mapping,并没有自动生成ik配置。

二、解决方案(重建索引)

由于ElasticSearch索引一旦建立,就无法动态修改其字段的映射类型,为了不影响线上的访问,需要无缝切换到新的索引上。使用 ElasticSearch 提供的 reindex api 来迁移数据,创建新的索引

1. 创建新的索引

PUT /myIndex_v2

2. 设置新索引的mapping

PUT /myIndex_v2/_mapping/myIndex_v2

{
  "properties": {
    "title": {
      "type": "text",
      "analyzer": "ik_smart",
      "search_analyzer": "ik_smart",
      "fields": {
        "keyword": {
        "type": "keyword",
        "ignore_above": 256
        }
      }
    },
    "content": {
      "type": "text",
      "fields": {
        "keyword": {
        "type": "keyword",
        "ignore_above": 256
        }
      }
    },
    "createTime": {
      "type": "long"
    }
  }
}

  

3. 同步数据

使用 reindex 将原来的索引重建到新的索引上

POST /_reindex

{
    "source": {
        "index": "myIndex"
    },
    "dest": {
        "index": "myIndex_v2"
    }
}        

  

4. 查看数据是否已同步到新的索引上

GET /myIndex_v2/_search

5. 使用别名,切换索引(同时删除原索引myIndex)

POST /_aliases

{
    "actions": [
        {
            "add": {
            "index": "myIndex_v2",
            "alias": "myIndex"
            }
        },
        {
            "remove_index": {
            "index": "myIndex"
            }
        }
    ]
}                    

  大功告成,现在可以同时使用myIndex和myIndex_v2搜索数据

参考:https://javasgl.github.io/elastic-search-reindex/

   https://javasgl.github.io/use-alias-migrate-index/

posted @ 2018-10-22 17:33  时间-海  阅读(3671)  评论(0编辑  收藏  举报