• ElasticSearch(四)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 tags;
        @Field(type = FieldType.Text, analyzer = “ik_max_word”)
        private String desc;

      }

    • 这是创建索引的代码

          boolean index = elasticsearchRestTemplate.createIndex(ESUser.class);
      
      • 1

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

    二. 解决方案

    • 1.(在createIndex方法后加putMapping方法)

          boolean index = elasticsearchRestTemplate.createIndex(ESUser.class);
          elasticsearchRestTemplate.putMapping(ESUser.class);
      
      • 1
      • 2

    问题解决, 查看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);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

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

    没有头绪!!!

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

    妙 啊!!!

    原来是

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

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

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

    Done!

  • 相关阅读:
    Scala核心-编译解释
    HONEYWELL 05701-A-0325控制脉冲模块
    Cadence OrCAD Capture 层次化设计单模块多次复用功能说明与效果演示
    SQL创建新的输出字段
    流量控制&可靠传输机制&停止-等待协议
    java毕业设计项目选题springboot汉赛汽车租赁平台
    Vue2(一):Vue介绍、模板语法、数据绑定、el和data的两种写法、MVVM、数据代理、事件
    求先序遍历序列中第(1<=k<=二叉树中结点个数)个结点的值
    vue3 的组件通信以及ref的使用
    基于51单片机步进电机节拍步数正反转LCD1602显示( proteus仿真+程序+原理图+设计报告+讲解视频)
  • 原文地址:https://blog.csdn.net/m0_67392182/article/details/126359839