spring-data-elasticsearch @Field注解 spring-data-elasticsearch @Field注解无效的完美解决方案

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring-data-elasticsearch @Field注解 spring-data-elasticsearch @Field注解无效的完美解决方案

晴天小哥哥   2021-07-26 我要评论
想了解spring-data-elasticsearch @Field注解无效的完美解决方案的相关内容吗,晴天小哥哥在本文为您仔细讲解spring-data-elasticsearch @Field注解的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring-data-elasticsearch,@Field注解无效,下面大家一起来学习吧。

前言

我看了一大堆博客和资料大多是说这个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这个方法啊,找了你好久!!!!

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们