• 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!

  • 相关阅读:
    【新手入门】Github与Git使用教程
    【bug 记录】yolov5_C_demo 部署在 rv1126
    ARTS打卡第四周之删除链表倒数第几个节点、gdb start命令、扩散模型、如何学习分享
    ctfshow-web2(SQL注入)
    简易的安卓天气app(二)——适配器、每小时数据展示
    性能优化:线程快照获取与分析
    IK学习笔记(2)——TwoBones IK
    计算机网络原理 谢希仁(第8版)第五章习题答案
    【FFH】如何在鸿蒙系统上进行抓包测试
    android 如何混淆以及排查混淆后不明Bug
  • 原文地址:https://blog.csdn.net/m0_67392182/article/details/126359839