高效的ElasticSearch Java API - my-elasticsearch-starter

ES Java Api有很多种,本文主要是基于Spring Boot进行封装的,为什么选择Spring Boot,可以看往期文章 Elasticsearch入门必读指南:到底选择哪个ES版本更合适 。 Spring Boot现在也是Java生态中主流的开发框架使用最广泛,综上没有理由不使用,所以本文及提供的starter也以此为基础。

一、背景

虽然spring-boot-starter-data-elasticsearch已经对原生的ES Api进行了封装,但使用起来还是不够高效。ES作为一个搜索引擎中间件,一个企业内业很多业务团队都可能会使用到,封装一个通用的ES Starter供业务团队使用非常有必要。 通过该Starter可以降低业务团队接入及使用成本,也方便后续ES的统一升级管理。

二、高效的my-elasticsearch-starter

my-elasticsearch-starter是基于Spring Boot Starter规范进行封装,基于Spring Boot的应用都可以快速引入使用。

该Starter在Github上开源,地址如下 :GitHub - caizi12/my-elasticsearch-starter: elasticsearch starter

如果不方便访问的话,也可以下载压缩包

my-elasticsearch-starter.zip

my-elasticsearch-starter 对ES Api进行了封装,提供了更加简洁高效的API出来,对于有一点开发经验的来说使用该Starter可能10分钟就可以完成ES的接入及基本的Demo的开发。以下介绍整体Starter的使用方式。

2.1 使用方式

使用时可以先把代码Deploy到公司的私有仓库中,然后应用程序中依赖使用,如果没有私有仓库可以把代码copy到应用中使用。

2.1.1、应用添加依赖

<dependency>
  <groupId>com.my.es</groupId>
  <artifactId>elasticsearch-starter</artifactId>
  <version>1.0.0-SNAPSHOT</version>     
</dependency>

2.1.2、应用添加ES链接配置

以下是properties格式,如果是Yml格式自行调整即可

#es链接地址
spring.elasticsearch.uris=http://localhost:9200

#es账号密码,根据实际填写
spring.elasticsearch.username=elastic
spring.elasticsearch.password=123456
#可省配置:连接es集群超时参数,默认毫秒
spring.elasticsearch.connection-timeout=300
spring.elasticsearch.read-timeout=300

以上两步完成后应用就已经接入了ES,接下来直接开发业务代码即可

3、ES API Demo,高效完成一个学生ES Demo

3.1 定义索引对象

定义一个学生索引对象,方便在代码中开发使用

java 复制代码
package com.my.es.test.model;

import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * 
 * 学生索引
 * @authro nantian
 * @date 2022-09-28 15:34
 */
@Data
@AllArgsConstructor
@Document(indexName = "index_student")
//分片设置,一般不建议代码中创建索引,在Kibana中进行管理比较合适
//@Setting(shards = 5,replicas = 1)
@NoArgsConstructor
public class Student {
    //索引主键
    @Id
    private long id;

    @Field(type = FieldType.Keyword)
    private String name;

    @Field(type = FieldType.Keyword)
    private String text;

    //@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart")
    @Field(type = FieldType.Keyword)
    private String desc;

    //@Field(type = FieldType.Text,analyzer = "ik_smart")
    @Field(type = FieldType.Keyword)
    private String title;

    @Field(type = FieldType.Integer)
    private Integer age;

    @Field(type = FieldType.Date)
    private Date date;

    //版本号,可以解决数据冲突问题
    @Version
    private Long version;
}

3.2 增删改查

java 复制代码
@SpringBootTest
public class MyEsServiceTest {
    @Autowired
    private MyEsService myEsService;

    //删除索引 
    @Test
    public void delIndex() {
        boolean result = myEsService.deleteIndexIfExist(Student.class);
        Assert.assertTrue(result);
    }


   //更新索引结构
    @Test
    public void updateMapping() {
        boolean result = myEsService.updateIndexMapping(Student.class);
        Assert.assertTrue(result);
    }

    //创建学生索引 
    @Test
    public void createIndex() {
        boolean exist = myEsService.existIndex(Student.class);
        boolean result = false;
        if (!exist) {
            result = myEsService.createIndexIfNotExist(Student.class);
        } else {
            System.out.println("index exist:" + Student.class.getName());
        }
        Assert.assertTrue(result);
    }


   //添加一个学生数据到索引中
    @Test
    public void addIndexDoc() {
        Student student = new Student(1000, "张三", "测试索引添加", "哈哈", "三年二班刘", 10, new Date(), null);
        String documentId = myEsService.addIndexDoc(student);
        System.out.println("addIndexDoc result:" + documentId);
        Assert.assertNotNull(documentId);
    }

    //更新一个学生数据
    @Test
    public void updateDoc() throws JsonProcessingException {
        Student student = new Student();
        student.setId(1000);
        student.setAge(30);
        student.setText("lisi");
        UpdateResponse.Result result = myEsService.updateDoc(student);
        System.out.println("update result:" + JSONObject.toJSONString(result));
     
    }

   //删除一个学生数据
    @Test
    public void delIndexDoc() {
        String result = myEsService.delIndexDoc("3007", Student.class);
        System.out.println("delIndexDoc:" + Student.class.getName());
    }

    //根据学生ID查询
    @Test
    public void getByIdStudent() {
        Student student = myEsService.findById("1000", Student.class);
        System.out.println(JSONObject.toJSONString(student));
    }
}

以上展示的一是一些基本用法,在源码中还有更多的用法,比如批量保存、更新、删除、查询等操作。整体使用起来非常简单,和使用Mybatis是不是感觉很像。

整个Starter具体实现原理大家可以看看代码,还算是比较简单,部分API主要用到了一些反射机制,浪费一点性能带来高效的开发体验还是很值得的,有兴趣的可以留言交流。

相关推荐
loss_rose7776 分钟前
【场景题】秒杀系统设计以及解决方案
java
java_heartLake16 分钟前
设计模式之解释器模式
java·设计模式·解释器模式
风清扬_jd31 分钟前
Chromium 硬件加速开关c++
java·前端·c++
哎呦没32 分钟前
Spring Boot框架在医院管理中的应用
java·spring boot·后端
苓诣32 分钟前
Java Vector类
java·数据结构
络71 小时前
Spring14——案例:利用AOP环绕通知计算业务层接口执行效率
java·后端·spring·mybatis·aop
天上掉下来个程小白1 小时前
分层解耦-02.分层解耦(IOC-DI引入)
java·springboot·依赖注入·控制反转
极客先躯2 小时前
高级java每日一道面试题-2024年10月2日-分布式篇-什么是FLP 不可能性定理?
java·分布式·分布式篇·容错策略·不可能性定理·补偿机制
2401_857622662 小时前
SpringBoot精华:打造高效美容院管理系统
java·前端·spring boot
克鲁德战士2 小时前
【Nacos架构 & 原理】内核设计之Nacos一致性协议
java·架构