2020-03-18 spring-data-elasticsearch 如何使用注解配置自动索引映射

关于使用 spring-data-elasticsearch 提供的注解来配置索引映射,来网上有很多文章,可能在老版本上可以运行,我没有在老版本上测试。但在 v7.6.1 上,这些方法都不能工作了。
目前的spring-boot-2.2.5.RELEASE + spring-data-elasticsearch 提供的 @Ducument、@Field、@FieldType,可以用来在文档对象上通过注解自动生成索引映射,但存在明显的严重BUG,只能适用于特地场景。下面会通过例子逐一说明。如果有需求,还是手动创建索引来的比较实在。
下面就详细介绍。

1. 通过 elasticsearchTemplate.putMapping配置。

网上提到的一种方法:、
给 elasticsearchTemplate 对象使用如下方法注入具体索引的映射:

    @BeforeEach
    void setUp() throws Exception {
        assertNotNull(this.esRestTemplate);
        this.esRestTemplate.putMapping(Question.class);

在文档对象上使用注解:

@Mapping(mappingPath = "Question.json")
@Document(indexName = "question")
public class Question implements Serializable {

在 /src/main/resoursces/Question.json中配置索引的映射:

{
  "mapping": {
      "properties": {
        "category": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "formulas": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "id": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "question": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_max_word",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "questionNo": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_max_word",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    }
}

事实证明不行。会报如下错误:

MapperParsingException[Root mapping definition has unsupported parameters:  [mapping : {properties={category={type=text, analyzer=ik_max_word, search_analyzer=ik_max_word, fields={keyword={type=keyword, ignore_above=256}}}, formulas={type=text, analyzer=ik_max_word, search_analyzer=ik_max_word, fields={keyword={type=keyword, ignore_above=256}}}, id={type=text, fields={keyword={type=keyword, ignore_above=256}}}, question={type=text, analyzer=ik_max_word, search_analyzer=ik_max_word, fields={keyword={type=keyword, ignore_above=256}}}, questionNo={type=text, analyzer=ik_max_word, search_analyzer=ik_max_word, fields={keyword={type=keyword, ignore_above=256}}}}}]]
    at org.elasticsearch.index.mapper.DocumentMapperParser.checkNoRemainingFields(DocumentMapperParser.java:148)
    at org.elasticsearch.index.mapper.DocumentMapperParser.parse(DocumentMapperParser.java:136)
    at org.elasticsearch.index.mapper.DocumentMapperParser.parse(DocumentMapperParser.java:88)
    at org.elasticsearch.index.mapper.MapperService.parse(MapperService.java:674)
    at org.elasticsearch.cluster.metadata.MetaDataMappingService$PutMappingExecutor.applyRequest(MetaDataMappingService.java:279)

存在的问题我还没有来得及去查,后面有时间再说。

2 通过 @Document 和 @Field、@MultiField、@InnerField 配置

通过反复实验,证实在最新的 spring-boot-2.2.5.RELEASE + elasticsearch@7.6.1的组合,特定情况下的注解配置存在严重BUG,但基本可用。
下面分别介绍可以成功的场景,和会导致失败的场景。

2.1. 不使用 FieldType.Auto,只使用 FieldType.Keyword、FieldType.Text) 并正确配置

这种情况下,可以正确生成索引映射。
文档注解如下:

@Document(indexName = "question")
public class Question implements Serializable {

    @Id
    @Field(type= FieldType.Keyword)
    private String id;
    
    /**
     * 题号
     */
    @Field(type=FieldType.Text)
    private String questionNo;
    
    /**
     * 题目类型
     */
    @MultiField(
            mainField = @Field(type=FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart"), 
            otherFields = @InnerField(suffix = "keyword", type=FieldType.Keyword))
    private String category;
    
    /**
     * 题目
     */
    @Field(type=FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String question;
    
    /**
     * 从题目中提出取来的公式列表。
     */
    @Field(type = FieldType.Keyword)
    private List<String> formulas;

可以看到自动生成的映射如下:

{
  "mapping": {
    "question": {
      "properties": {
        "category": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          },
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart"
        },
        "formulas": {
          "type": "keyword"
        },
        "id": {
          "type": "keyword"
        },
        "question": {
          "type": "text",
          "analyzer": "ik_max_word",
          "search_analyzer": "ik_smart"
        },
        "questionNo": {
          "type": "text"
        }
      }
    }
  }
}

可以看到,自动生成的映射有如下特点:

  • 映射配置为 FieldType.Keyword 的,映射为 keyword
        "formulas": {
         "type": "keyword"
       },
       "id": {
         "type": "keyword"
       },
  • 映射配置为 FieldType.Text 且没有指定分析器的,将映射为使用默认分析器

比如

   @Field(type=FieldType.Text)
   private String questionNo;

生成的映射是:

       "questionNo": {
         "type": "text"
       }
  • 映射配置为 FieldType.Text 且指定了分析器的,使用指定的分析器配置

比如

   @Field(type=FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
   private String question;

生成的映射是:

       "question": {
         "type": "text",
         "analyzer": "ik_max_word",
         "search_analyzer": "ik_smart"
       },
  • 映射配置为@MultiField 的,会映射为多字段,并使用对应的分析器。、

所谓多字段,是说同一个字段同时建立多种索引,比如 text 和 keyword。注意,不能用 FieldType.Auto,会导致映射出错。具体参看 2.2.2
应当用 @MultiField 和 @InnerField 结合使用:

   @MultiField(
           mainField = @Field(type=FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart"), 
           otherFields = @InnerField(suffix = "keyword", type=FieldType.Keyword))
   private String category;

生成的映射是:

       "category": {
         "type": "text",
         "fields": {
           "keyword": {
             "type": "keyword"
           }
         },
         "analyzer": "ik_max_word",
         "search_analyzer": "ik_smart"
       },
  • 如果映射为 FeildType.Keyword 还指定分析器,自动生成的映射会出错,效果和映射为 FeildType.Auto 一样。具体参看 2.2

2.2. 只要使用了 @Field(type=FieldType.Auto),自动索引映射就会出错。

在spring-data-elasticsearch 提供的注解 FieldType.Auto 本来代表了 对应字段应当同时支持类型 FieldType 和 FieldType.Keyword,但只要有一个属性使用了注解 FieldType.Auto ,会导致配置的分析器丢失,且其他属性无论配置什么类型,都会变成 FieldType.Auto

在文档上直接配置文档类型:

@Document(indexName = "question")
public class Question implements Serializable {

    @Id
    @Field(type= FieldType.Keyword)
    private String id;
    
    /**
     * 题号
     */
    @Field(type=FieldType.Text)
    private String questionNo;
    
    /**
     * 题目类型
     */
    @Field(type=FieldType.Auto, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String category;
    
    /**
     * 题目
     */
    @Field(type=FieldType.Auto, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String question;
    
    /**
     * 从题目中提出取来的公式列表。
     */
    @Field(type = FieldType.Auto)
    private List<String> formulas;

可以看到自动生成的索引映射如下:

{
  "mapping": {
    "question": {
      "properties": {
        "category": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "formulas": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "id": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "question": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "questionNo": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    }
  }
}

可以看到,这种混合使用FieldType.Auto/Keyword/Text的配置存在两个问题:

  • 只要有一个属性使用了 FieldType.Auto,不管其他属性配置的是 FieldType.Auto,还是 FieldType.Keyword,还是 FieldType.Text,最后都是同时映射了 text 和 keyword,也就是 FieldType.Auto 的效果。
  • 不管你有没有指定,或者指定的 analyzer 和 searchAnalyzer 是什么,最后都丢失了分析器映射。

这显然是 spring-data-elasticsearch 的BUG。关于这个问题,我在网上搜索到了好多类似的问题反馈。

2.3. 给属性配置 @Field(type=FieldType.Keyword) 指定了分析器,也会导致自动索引映射出错。

显然,FieldType.Keyword 是不能有分析器的,因为它的含义本来就是不使用分析器而是作为一个整体来索引。如果给一个属性指定为类型 FieldType.Kyeword 还同时指定了分析器,那么自动索引映射就会出错,其效果同使用了 FieldType.Auto 一样。
比如,我们给文档对象使用如下配置:

@Document(indexName = "question")
public class Question implements Serializable {

    @Id
    @Field(type= FieldType.Keyword)
    private String id;
    
    /**
     * 题号
     */
    @Field(type=FieldType.Text)
    private String questionNo;
    
    /**
     * 题目类型
     */
    @Field(type=FieldType.Auto, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String category;
    
    /**
     * 题目
     */
    @Field(type=FieldType.Auto, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String question;
    
    /**
     * 从题目中提出取来的公式列表。
     */
    @Field(type = FieldType.Keyword, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private List<String> formulas;

其自动生成的索引映射是:

{
  "mapping": {
    "question": {
      "properties": {
        "category": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "formulas": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "id": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "question": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "questionNo": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    }
  }
}

显然省生成的映射出错了。其效果和有属性配置了 FieldType.Auto 一样:

  • 不管你配置了什么类型,都变成 FieldType.Auto 了。
  • 指定的解析器都丢失了。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,997评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,603评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,359评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,309评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,346评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,258评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,122评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,970评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,403评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,596评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,769评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,464评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,075评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,705评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,848评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,831评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,678评论 2 354

推荐阅读更多精彩内容