elasticsearch报错索引已存在IndexAlreadyExistsException
IndexAlreadyExistsException[[symbol] already exists
原因可能如下:
1. 该索引已存在,重复创建。
2. 向已存在的索引中添加自定义filter/analyzer。
3. 分词器反复创建:先用standard分词器建的index,然后使用ik分词器又建索引出现这个错误,相当于对已有的index修改mapping,同样之前用standard建的索引,现在换成用ik分词器搜也搜不出来RestHighLevelClient的TermQuery。
4. 事先没有创建mapping.
下面是es映射介绍。
1 映射的相关概念
1.1 什么是映射
(1) 映射(mapping): 定义index的元数据, 指定要索引并存储的文档的字段类型.
需要注意的是: 检索时用到的分析策略, 要和建立索引时的分析策略相同, 否则将导致数据不准确.
(2) ES对不同的类型有不同的存储和检索策略.
1.2 映射的组成
每个index都有一 个type, 每个type对应一个mapping.
每个mapping都由下述部分组成:
1.3 元字段
每个文档都有与之关联的元数据 —— ES内部为所有的文档配备的field, 都是以下划线_开头的内置字段.
1.4 字段的类型
Elasticsearch中每个field都对应一至多个数据类型.
2 如何配置mapping
2.1 创建mapping
(1) 必读说明:
① 创建mapping时, 可以指定每个field是否需要:
② :每个type对应的mapping的JSON串, 包括properties, metadata(_id, _source, _type) , settings(analyzer) , 其他settings(如include_in_all)
(2) 创建mapping的示例:
需求: 创建名为website的索引, 包含一个user类型. user类型中禁用元字段_all.
PUT website { "mappings": { "user": { // 这就是一个root object "_all": { "enabled": false }, // 禁用_all字段 "properties": { "user_id": { "type": "text" }, "name": { "type": "text", "analyzer": "english" }, "age": { "type": "integer" }, "sex": { "type": "keyword" }, "birthday": { "type": "date", "format": "strict_date_optional_time||epoch_millis" }, "address": { "type": "text", "index": false // 不分词 } } } } }
2.2 更新mapping
(1) 必读说明:
映射一旦创建完成, 就不允许修改:
—— Elasticsearch对文档的分析、存储、检索等过程, 都是严格按照mapping中的配置进行的. 如果允许后期修改mapping, 在检索时对索引的处理将存在不一致的情况, 导致数据检索行为不准确.
只能在创建index的时候手动配置mapping, 或者新增field mapping, 但是不能update field mapping.
(2) 更新mapping出现异常:
修改已经创建好的mapping
PUT website { "mappings": { "user": { "properties": { "author_id": { "type": "text" } } } } }
抛出如下错误 —— 索引已经存在的异常:
{ "error": { "root_cause": [ { "type": "resource_already_exists_exception", "reason": "index [website/mVYk4-a7RMOZbkcCp2avfw] already exists", "index_uuid": "mVYk4-a7RMOZbkcCp2avfw", "index": "website" } ], "type": "resource_already_exists_exception", "reason": "index [website/mVYk4-a7RMOZbkcCp2avfw] already exists", "index_uuid": "mVYk4-a7RMOZbkcCp2avfw", "index": "website" }, "status": 400 }
(3) 向mapping中添加新type:
向已有mapping中添加字段及其映射信息:
PUT website/_mapping/user // 修改user类型的_mapping, 注意API的顺序 { "properties": { "new_field": { "type": "text", "index": false } } }
2.3 查看mapping
(1) 查看mapping的API:
GET website/_mapping