SoFunction
Updated on 2025-04-17

ElasticSearch custom annotation addition, deletion and modification methods

Import dependencies

<!--Provides with Elasticsearch Interactive high-level client,Easy to Java Use in the application Elasticsearch Functions。-->
<dependency>
    <groupId></groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
<!-- Spring Boot The starter,Simplified with Elasticsearch Integration -->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- High performance JSON Processing library,For JSON parsing and generation -->
<dependency>
    <groupId></groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version> <!-- Please use the latest version -->
</dependency>
<!-- Simplify by annotation Java Code,Automatically generated getter、setter、构造函数等Code,减少样板Code的编写 -->
<dependency>
    <groupId></groupId>
    <artifactId>lombok</artifactId>
</dependency>

Import the ElasticSearchUtil tool

@Component
@Slf4j
public class ElasticSearchUtil {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
      * Get the object id
      *
      * @param data
      * @return
      */
    private String getObjectId(Object data) {
        String idValue = null;
        try {
            String idName = "id";
            //Get all fields under the Object class            Field[] declaredFields = ().getDeclaredFields();
            //Loop traversal            for (Field field : declaredFields) {
                //Get the annotation instance of 'IdIndex' on the field                IdIndex annotation = ();
                //If not empty                if (annotation != null) {
                    // Assign the idName in the annotation to the variable idName                    idName = ();
                    //End the loop                    break;
                }
            }
            //Look for a field named idName and return a Field object representing this field            Field declaredField = ().getDeclaredField(idName);
            //Set the access permissions of the object            (true);
            idValue = (data).toString();
            (" >>>>>> idValue:{}", idValue);
        } catch (Exception e) {
            (());
        }
        return idValue;
    }

    /**
      * Create an index
      *
      * @return
      * @params index
      */
    public String createIndex(Object data) throws Exception {
        //Search the index name according to the entity annotation        DocumentIndex annotation = ().getAnnotation();
        String indexName = ();

        //The index already exists, no need to create an index        if (isIndexExist(indexName)) return indexName;

        //1. Create an index request        CreateIndexRequest request = new CreateIndexRequest(indexName);

        //Create basic configuration         builder = ().put("index.max_result_window", ());//1 billion data        ("index.number_of_shards", ()) // Number of shards                .put("index.number_of_replicas", ()); // Number of copies        (builder);//Basic configuration of index documents
        //mapping structure        JSONObject mapping = new JSONObject();
        JSONObject props = new JSONObject();
        ("properties", props);

        Class<?> aClass = ();
        //();
        //();
        //Get all private attributes of the object        Field[] declaredFields = ();
        for (Field field : declaredFields) {
            Class type = ();
            String name = ();
            JSONObject prop = new JSONObject();
            PropertyIndex propIndex = ();
            if (propIndex != null) {//Custom attributes and various configurations                if (() != null && !"".equals(())) {
                    name = ();
                }
                (name, prop);//The index field name can be specified through annotation                ("type", ());
                ("index", true);//Default true                if ("text".equals(())) {
                    ("analyzer", ());//"analyzer": "ik_max_word",
                    ("search_analyzer", ());//"search_analyzer": "ik_smart"
                }
                if (!()) { //Set non-index                    ("index", false);
                }
            } else { //Default processing                (name, prop);
                if (() instanceof String) {
                    ("type", "keyword");
                } else if (() instanceof Date) {
                    ("type", "date");
                    ("format", "yyyy-MM-dd HH:mm:ss");//"format": "yyyy-MM-dd HH:mm:ss"
                } else if (() instanceof Integer) {
                    ("type", "integer");
                } else if (() instanceof Long) {
                    ("type", "long");
                } else {
                    ("type", "text");
                    ("analyzer", "ik_smart");//"analyzer": "ik_max_word",
                    ("search_analyzer", "ik_smart");//"search_analyzer": "ik_smart"
                }
            }

        }

        String jsonString = ();
        ("jsonString: " + jsonString);
        ("_doc", jsonString, );

        //2. Execute client request        CreateIndexResponse createIndexResponse = ()
                .create(request, );

        return indexName;
    }

    /**
      * Determine whether the index exists
      *
      * @param index
      * @return
      */
    public boolean isIndexExist(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        boolean exists = ().exists(request, );
        return exists;
    }

    /**
      * Delete the index
      *
      * @param index
      * @return
      */
    public boolean deleteIndex(String index) throws IOException {
        if (!isIndexExist(index)) {
            ("Index is not exits!");
            return false;
        }
        DeleteIndexRequest request = new DeleteIndexRequest(index);
         delete = ()
                .delete(request, );
        return ();
    }

    /**
      * Write data
      */
    public boolean insertData(Object data, String indexName) {
        try {
            IndexRequest request = new IndexRequest(indexName).id(getObjectId(data)).source((data), );
            (request, );
        } catch (Exception e) {
            (" >>>>>>> insertData error: {}", ());
            ();
        }
        return true;
    }

    /**
      * Bulk write data
      */
    public boolean batchInsert(List<Object> datas) {
        //Parameter verification        if ((datas)) return false;

        DocumentIndex annotation = (0).getClass().getAnnotation();
        String indexName = ();

        try {
            BulkRequest bulkRequest = new BulkRequest();

            (data -> {
                (new IndexRequest(indexName).id(getObjectId(data))
                        .source((data), ));
            });

            (bulkRequest, );
        } catch (Exception e) {
            (" >>>>>>> insertData error: {}", ());
            ();
        }
        return true;
    }

    /**
      * Update data, you can directly modify the index structure
      */
    public boolean batchUpdate(List<Object> datas) {

        if ((datas)) return false;

        DocumentIndex annotation = (0).getClass().getAnnotation();
        String indexName = ();
        try {
            BulkRequest bulkRequest = new BulkRequest();

            (data -> {
                (new UpdateRequest(indexName, "doc", getObjectId(data)).doc((data)));
            });

            (bulkRequest, );
        } catch (Exception e) {
            (" >>>>>>> insertData error: {}", ());
            ();
        }

        return true;
    }

    /**
      * Revise
      *
      * @param data
      * @return
      */
    public boolean updateData(Object data) {
        try {
            //Get the index name            String indexName = ().getAnnotation().indexName();
            //Create a modification request            UpdateRequest updateRequest = new UpdateRequest(indexName, "_doc", getObjectId(data)).doc((data), );
            (updateRequest, );
        } catch (IOException e) {
            (" >>>>>>> updateData error: {}", ());
            ();
        }
        return true;
    }

    /**
      * Delete data
      */
    public boolean delete(String indexName, String id) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest(indexName, "_doc", id);
            (deleteRequest, );
        } catch (Exception e) {
            (" delete Exception:{}", ());
            ();
        }
        return true;
    }

}

Import config

@Configuration
public class InitRestHighLevelClient  {

    @Value("${:IP}")
    private String hostname;

    @Value("${:port}")
    private int port;

    /**
      * Initialize the RestHighLevelClient object
      *
      * @return
      */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                (new HttpHost(hostname, port, "http"))
        );
        return client;
    }
}

Annotation class DocumentIndex

/**
 * @Author:GuoYangsheng
 * @Description:
 * @name:DocumentIndex
 * @Date:2024/9/12 16:43
 */
@Target()//Specify annotations can be applied to classes, interfaces, or enumerations@Retention()//It can be accessed and read through the reflection mechanismpublic @interface DocumentIndex {

    //Specify the name of the index.  Default is an empty string, indicating that it is not specified    String indexName() default "";

    //The maximum number of documents that are indexed by default is 10,000    int maxSize() default 10000;

    //Specify the number of shards for the index. The default is 3. Sharding can improve the performance and scalability of the index.    int shards() default 3;

    //Specify the number of replicas for the index. The default is 1 replica. It can improve data reliability and query performance.    int replicas() default 1;
}

Annotation class IdIndex

/**
 * @Author:GuoYangsheng
 * @Description:
 * @name:IdIndex
 * @Date:2024/9/12 16:50
 */
@Target()//Specify that 'IdIndex' can be applied to fields in the class@Retention()//It can be accessed and read through the reflection mechanismpublic @interface IdIndex {
    //Specify the attribute identifier name as 'id'    String idName() default "id";
}

Annotation class PropertyIndex

/**
 * @Author:GuoYangsheng
 * @Description:
 * @name:PropertyIndex
 * @Date:2024/9/12 16:58
 */

import ;
import ;
import ;
import ;

/**
  * ES index field annotation
  */
@Target()//Specify that 'IdIndex' can be applied to fields in the class@Retention()//It can be accessed and read through the reflection mechanismpublic @interface PropertyIndex {
    // Used to specify the name of the field in the Elasticsearch index    String name() default "";
    //Specify the data type of the field    String type() default "keyword";
    //Specify the word parterator for the field    String analyzer() default "ik_smart";
    //Is it possible to create an index    boolean index() default true;
    //Specify the word parter for search    String searchAnalyzer() default "ik_smart";
    //Specify whether to ignore the index of this field    boolean ignore() default true;
}

controller

/**
 * @Author:GuoYangsheng
 * @Description:
 * @name:SysDeptController
 * @Date:2024/9/12 20:26
 */
@RestController
@RequestMapping("/sysDept")
public class SysDeptController {
    @Autowired
    private SysDeptService sysDeptService;

    /**
      * Create an index
      *
      * @param sysDept
      * @return
      */
    @GetMapping("/createIndex")
    public void createIndex(SysDept sysDept) {
        (sysDept);
    }

    /**
      * Save
      *
      * @param sysDept
      */
    @PostMapping("/save")
    public Boolean save(@RequestBody SysDept sysDept) {
        return (sysDept);
    }

    /**
      * Delete data
      *
      * @param indexName
      * @param id
      * @return
      */
    @DeleteMapping("/deleteById")
    public Boolean deleteById(String indexName, String id) {
        return (indexName, id);
    }

    /**
      * Modify data
      *
      * @param sysDept
      * @return
      */
    @PutMapping("/updateSysDept")
    public Boolean updateSysDept(@RequestBody SysDept sysDept) {
        return (sysDept);
    }
}

service

/**
 * @Author:GuoYangsheng
 * @Description:
 * @name:SysDeptService
 * @Date:2024/9/12 20:26
 */
public interface SysDeptService {
    /**
      * Create an index
      *
      * @param sysDept
      */
    void createIndex(SysDept sysDept);

    /**
      * Save
      *
      * @param sysDept
      */
    Boolean save(SysDept sysDept);


    /**
      * Delete data
      *
      * @param indexName
      * @param id
      * @return
      */
    Boolean deleteById(String indexName, String id);

    /**
      * Modify data
      *
      * @param sysDept
      * @return
      */
    Boolean updateSysDept(SysDept sysDept);
}

Implementation layer: Just call the tool-like method directly

/**
 * @Author:GuoYangsheng
 * @Description:
 * @name:SysDeptServiceImpl
 * @Date:2024/9/12 20:26
 */
@Service
public class SysDeptServiceImpl implements SysDeptService {
    @Resource
    private ElasticSearchUtil elasticSearchUtil;

    /**
      * Create an index
      *
      * @param sysDept
      */
    @Override
    public void createIndex(SysDept sysDept) {
        try {
            (sysDept);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
      * Save
      *
      * @param sysDept
      */
    @Override
    public Boolean save(SysDept sysDept) {
        return (sysDept);
    }


    /**
      * Delete data
      *
      * @param indexName
      * @param id
      * @return
      */
    @Override
    public Boolean deleteById(String indexName, String id) {

        return (indexName, id);
    }

    /**
      * Modify data
      *
      * @param sysDept
      * @return
      */
    @Override
    public Boolean updateSysDept(SysDept sysDept) {

        return (sysDept);
    }
}

Check the effects in the Elastic development tool, or download the Apipost tool to test it

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.