spring-data-elasticsearch @Field注解無效的完美解決方案
前言
我看了一大堆博客和資料大多是說這個spring的bug, 然后通過一個.json的配置文件去加載,我也是真的笑了, 本來注解就是方便開發(fā),取消配置文件的功能, 結果解決方案卻是本末倒置, 這里我奉獻出最正確的解決方案
一. 準備實例代碼
這是實體類代碼,及其注解
package com.gupao.springbootdemo.bean;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.util.List;
/**
* 功能描述:ES的用戶
*
* @Author: zhouzhou
* @Date: 2020/7/30$ 9:57$
*/
@Data
@Document(indexName = "es_user")
public class ESUser {
@Id
private Long id;
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Integer)
private Integer age;
@Field(type = FieldType.Keyword)
private List<String> tags;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String desc;
}
這是創(chuàng)建索引的代碼
boolean index = elasticsearchRestTemplate.createIndex(ESUser.class);
我們會發(fā)現(xiàn),當執(zhí)行后, 雖然執(zhí)行成功, 但是我們去查看索引信息的時候發(fā)現(xiàn)沒有mapping信息
二. 解決方案
1.在createIndex方法后加putMapping方法
boolean index = elasticsearchRestTemplate.createIndex(ESUser.class); elasticsearchRestTemplate.putMapping(ESUser.class);
問題解決,查看mapping信息就有了

2.更新版本(注: 版本更新對應要更新es版本到7.8以上,不建議!!)

項目啟動的時候,自動創(chuàng)建索引,無需手動調用API創(chuàng)建!!!
三. 解決思路(源碼部分,以下只是筆者解決過程)
筆者通過查看elasticsearcRestTemplate的源碼才發(fā)現(xiàn)
@Override
public ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz) {
Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " + clazz.getSimpleName()
+ " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
return elasticsearchConverter.getMappingContext().getRequiredPersistentEntity(clazz);
}
創(chuàng)建索引前會通過getMappingContext方法獲取mappingContext字段, 但是這個字段怎么賦值呢?
沒有頭緒!!!!!
筆者又轉念一想, 我們直接思考下, 我們找到@Field字段在哪里被解析, 這不就知道讀取@Field的類和設置mappingContext的方法了!!!!
妙 啊!!!!!!

原來是
MappingBuilder這個類對@Field進行解析, 后來進去發(fā)現(xiàn)@Mapping解析.json,也就是網上的方法解析方法也在里面, 哈哈殊途同歸, 對外提供的方法為:

看注釋, 我就知道離真相不遠了,繼續(xù)查看調用鏈, 真相大白!!!下面方法我就不多做解釋了


原來是這個putMapping這個方法啊,找了你好久!!!!
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring框架基于AOP實現(xiàn)簡單日志管理步驟解析
這篇文章主要介紹了Spring框架基于AOP實現(xiàn)簡單日志管理步驟解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
PostMan傳@RequestParam修飾的數(shù)組方式
這篇文章主要介紹了PostMan傳@RequestParam修飾的數(shù)組方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
java中計算字符串長度的方法及u4E00與u9FBB的認識
字符串采用unicode編碼的方式時,計算字符串長度的方法找出UNICODE編碼中的漢字的代表的范圍“\u4E00” 到“\u9FBB”之間感興趣的朋友可以參考本文,或許對你有所幫助2013-01-01
Java 8 Stream.distinct() 列表去重的操作
這篇文章主要介紹了Java 8 Stream.distinct() 列表去重的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

