SpringBoot整合Easy-ES实现对ES操作

Easy-ES 简介

Easy-ES 是一个基于 Elasticsearch 的 Java 客户端库,旨在简化与 Elasticsearch 的交互。它为开发者提供了更易用、更高效的 API,帮助他们快速实现数据的索引、查询、更新和删除等操作。

主要特性

  1. 简化的 API

提供直观友好的接口,降低了使用 Elasticsearch 的学习曲线,使得开发者可以快速上手。

  1. 自动映射支持

根据 Java 对象的字段自动生成 Elasticsearch 索引映射,减少手动配置的繁琐。

  1. 灵活的查询 DSL

支持链式调用构建复杂查询,允许用户轻松构造和执行各种查询。

  1. 批量操作

支持批量处理,可以一次性执行多个文档的增、删、改操作,提高性能。

  1. Spring 集成

与 Spring 框架良好集成,支持依赖注入和自动配置,方便在 Spring 应用中使用。

  1. 多种数据格式支持

支持 JSON 和其他数据格式,便于与不同应用程序进行集成。

  1. 灵活的异常处理

提供了一套统一的异常处理机制,方便开发者捕获和处理错误。

  1. 扩展性强

允许开发人员根据需求自定义功能,适应不同的业务场景。

作用

  1. 数据存储与检索

Easy-ES 使得在 Elasticsearch 中存储和检索数据变得简单高效,适合需要处理海量数据的应用场景。

  1. 实 时搜索能力

利用 Elasticsearch 强大的搜索引擎能力,Easy-ES 可以快速实现实时搜索功能,提升用户体验。

  1. 数据分析

支持复杂的数据查询和分析操作,方便开发者在应用中实现数据挖掘和分析功能。

  1. 简化开发流程

减少了与 Elasticsearch 交互时的代码量和复杂度,加快开发速度,提高生产效率。

如何使用Easy-ES做基本操作

依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- lombok插件依赖 -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- Easy-Es暂不支持SpringBoot3.X,且推荐Elasticsearch版本为7.14.0 -->
    <dependency>
        <groupId>cn.easy-es</groupId>
        <artifactId>easy-es-boot-starter</artifactId>
        <version>1.1.1</version>
        <exclusions>
            <exclusion>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.14.0</version>
    </dependency>

    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.14.0</version>
    </dependency>
</dependencies>

配置

easy-es:
  enable: true
  address : 111.229.0.43:9200
  global-config:
    process_index_mode: manual

启动类

@SpringBootApplication
@EsMapperScan("com.easyes.mapper")
public class EasyEsApplication {

    public static void main(String[] args) {
        SpringApplication.run(EasyEsApplication.class, args);
    }

}

mapper

/**
 * @Author:xsp
 * @Description:
 * @name:DocumentMapper
 * @Date:2024/9/13 10:11
 */
public interface DocumentMapper  extends BaseEsMapper<Document> {

}

service

package com.easyes.service;

import com.easyes.entity.Document;

import java.util.List;

/**
 * @Author:xsp
 * @Description:
 * @name:IiDocumentService
 * @Date:2024/9/13 10:12
 */
public interface IDocumentService{
    /**
     * 查询ES所有数据
     * @return 查询Document结果对象集合
     */
    List<Document> findAllData();

    /**
     * 创建索引
     * @return 结果信息
     * @throws Exception
     */
    String createIndex() throws Exception;

    /**
     * 删除索引
     * @return 结果信息
     */
    String deleteIndex();

    /**
     * ES新增数据
     * @param document 新增数据实体类
     * @return 结果信息
     * @throws Exception
     */
    String addData(Document document) throws Exception;

    /**
     * 根据id删除ES数据
     * @param id 需要删除的数据的id
     * @return
     */
    String deleteDataById(String id);

    /**
     * 修改ES数据
     * @param document 修改数据对象
     */
    String updateData(Document document);

    /**
     * 分词匹配查询content字段
     * @param value 查询内容
     * @return
     */
    List<Document> findMatch(String value);

    /**
     * 根据id查询数据
     * @param id 查询id
     * @return
     */
    Document findById(String id);
}

serviceImpl

package com.easyes.service.impl;

import cn.easyes.common.utils.StringUtils;
import cn.easyes.core.conditions.LambdaEsQueryWrapper;
import com.easyes.entity.Document;
import com.easyes.mapper.DocumentMapper;
import com.easyes.service.IDocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author:xsp
 * @Description:
 * @name:iDocumentServiceImpl
 * @Date:2024/9/13 10:12
 */

@Service
public class DocumentServiceImpl implements IDocumentService {
    @Autowired
    private DocumentMapper documentMapper;

    /**
     * 查询ES所有数据
     * @return 查询Document结果对象集合
     */
    @Override
    public List<Document> findAllData() {
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.matchAllQuery();
        return documentMapper.selectList(wrapper);
    }
    /**
     * 创建索引
     * @return 结果信息
     * @throws Exception
     */
    @Override
    public String createIndex() throws Exception {
        StringBuilder msg = new StringBuilder();
        String indexName = Document.class.getSimpleName().toLowerCase();
        boolean existsIndex = documentMapper.existsIndex(indexName);
        if (existsIndex){
            throw new Exception("Document实体对应索引已存在,删除索引接口:deleteIndex");
        }
        boolean success = documentMapper.createIndex();
        if (success){
            msg.append("Document索引创建成功");
        }else {
            msg.append("索引创建失败");
        }
        return msg.toString();
    }
    /**
     * 删除索引
     * @return 结果信息
     */
    @Override
    public String deleteIndex() {
        StringBuilder msg = new StringBuilder();
        String indexName = Document.class.getSimpleName().toLowerCase();
        if (documentMapper.deleteIndex(indexName)){
            msg.append("删除成功");
        }else {
            msg.append("删除失败");
        }
        return msg.toString();
    }

    /**
     * ES新增数据
     * @param document 新增数据实体类
     * @return 结果信息
     * @throws Exception
     */
    @Override
    public String addData(Document document) throws Exception {
        if (StringUtils.isEmpty(document.getTitle()) || StringUtils.isEmpty(document.getContent())) {
            throw new Exception("请补全title及content数据");
        }
        document.setCreateTime(new Date());
        documentMapper.insert(document);
        return "Added successfully!";
    }

    /**
     * 根据id删除ES数据
     * @param id 需要删除的数据的id
     * @return
     */
    @Override
    public String deleteDataById(String id) {
        documentMapper.deleteById(id);
        return "Success";
    }

    /**
     * 修改ES数据
     * @param document 修改数据对象
     */
    @Override
    public String updateData(Document document) {
        documentMapper.updateById(document);
        return "Success";
    }


    /**
     * 分词匹配查询content字段
     * @param value 查询内容
     * @return
     */
    @Override
    public List<Document> findMatch(String value) {
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.match(Document::getContent,value);
        wrapper.orderByDesc(Document::getCreateTime);
        List<Document> documents = documentMapper.selectList(wrapper);
        return documents;
    }

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @Override
    public Document findById(String id) {
       return null;
    }
}

controller

package com.easyes.controller;

import com.easyes.entity.Document;
import com.easyes.service.IDocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author:xsp
 * @Description:
 * @name:DocumentController
 * @Date:2024/9/13 10:10
 */
@RestController
public class DocumentController {
    @Autowired
    private IDocumentService iDocumentService;
    /**
     * 创建索引
     * @return 结果信息
     * @throws Exception
     */
    @GetMapping("/createIndex")
    public String createIndex() throws Exception {
        return iDocumentService.createIndex();
    }

    /**
     * 删除索引
     * @return 结果信息
     */
    @GetMapping("/deleteIndex")
    public String deleteIndex(){
        return iDocumentService.deleteIndex();
    }

    /**
     * 查询ES所有数据
     * @return 查询Document结果对象集合
     */
    @GetMapping("/findAll")
    public List<Document> findAll(){
        return iDocumentService.findAllData();
    }
    /**
     * 根据id查询数据
     * @param id 查询数据的id
     * @return 查询Document结果对象
     */
    @GetMapping("/findById")
    public Document findById(String id){
        return iDocumentService.findById(id);
    }
    /**
     * ES新增数据
     * @param document 新增数据对象
     * @return 结果信息
     * @throws Exception
     */
    @GetMapping("/add")
    public String addData(@RequestBody Document document) throws Exception {
        return iDocumentService.addData(document);
    }

    /**
     * 修改ES数据
     * @param document 修改数据对象
     */
    @GetMapping("/update")
    public String updateData(@RequestBody Document document){
        return iDocumentService.updateData(document);
    }

    /**
     * 根据id删除ES数据
     * @param id 需要删除的数据的id
     * @return
     */
    @GetMapping("/delete")
    public String deleteData(String id){
        return iDocumentService.deleteDataById(id);
    }

    /**
     * 分词匹配查询content字段
     * @param value 查询内容
     * @return
     */
    @GetMapping("/match")
    public List<Document> findMatch(String value){
        return iDocumentService.findMatch(value);
    }
}

好的,我可以为您提供一些关于Spring Boot整合Easy Elasticsearch的指导。 1. 添加依赖 首先,在`pom.xml`文件中添加Easy ElasticsearchElasticsearch的依赖: ```xml <dependency> <groupId>com.jun</groupId> <artifactId>easy-elasticsearch-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.12.0</version> </dependency> ``` 2. 配置Elasticsearch 在`application.yml`中添加Elasticsearch的配置信息: ```yaml spring: elasticsearch: rest: uris: http://localhost:9200 ``` 3. 创建Elasticsearch的Repository 创建一个继承自`ElasticsearchRepository`的接口,用于定义Elasticsearch操作方法: ```java public interface BookRepository extends ElasticsearchRepository<Book, Long> { List<Book> findBooksByAuthor(String author); } ``` 其中,`Book`是我们要操作的实体类,`Long`是这个实体类的ID类型。 4. 测试Elasticsearch 可以编写一个测试方法来测试Elasticsearch是否成功整合: ```java @SpringBootTest class BookRepositoryTest { @Autowired private BookRepository bookRepository; @Test public void testSave() { Book book = new Book(); book.setId(1L); book.setTitle("Java编程思想"); book.setAuthor("Bruce Eckel"); bookRepository.save(book); } @Test public void testFind() { List<Book> books = bookRepository.findBooksByAuthor("Bruce Eckel"); System.out.println(books); } } ``` 执行测试方法后,如果能够正确输出结果,则说明Easy Elasticsearch已经成功整合到了Spring Boot中。 希望这些步骤能够对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值