前言

我看了一大堆博客和资料大多是说这个spring的bug, 然后通过一个.json的配置文件去加载,我也是真的笑了, 本来注解就是方便开发,取消配置文件的功能, 结果解决方案却是本末倒置, 这里我奉献出最正确的解决方案

一. 准备实例代码

这是实体类代码,及其注解

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;  
}

这是创建索引的代码

boolean index = elasticsearchresttemplate.createindex(esuser.class);

我们会发现,当执行后, 虽然执行成功, 但是我们去查看索引信息的时候发现没有mapping信息

二. 解决方案

1.在createindex方法后加putmapping方法

boolean index = elasticsearchresttemplate.createindex(esuser.class);
elasticsearchresttemplate.putmapping(esuser.class);

问题解决,查看mapping信息就有了

2.更新版本(注: 版本更新对应要更新es版本到7.8以上,不建议!!)

项目启动的时候,自动创建索引,无需手动调用api创建!!!

三. 解决思路(源码部分,以下只是笔者解决过程)

笔者通过查看elasticsearcresttemplate的源码才发现

@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);
	}

创建索引前会通过getmappingcontext方法获取mappingcontext字段, 但是这个字段怎么赋值呢?

没有头绪!!!!!

笔者又转念一想, 我们直接思考下, 我们找到@field字段在哪里被解析, 这不就知道读取@field的类和设置mappingcontext的方法了!!!!

妙 啊!!!!!!

原来是

mappingbuilder这个类对@field进行解析, 后来进去发现@mapping解析.json,也就是网上的方法解析方法也在里面, 哈哈殊途同归, 对外提供的方法为:

看注释, 我就知道离真相不远了,继续查看调用链, 真相大白!!!下面方法我就不多做解释了

原来是这个putmapping这个方法啊,找了你好久!!!!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。