Springboot和Es整合

news2025/2/21 8:40:14

说明:本文章主要是简单整合和简单增删改查。

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.example</groupId>
    <artifactId>EsDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

        <!-- swagger -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.9</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

    </dependencies>

</project>

2.application.yml

spring:
  elasticsearch:
    rest:
      uris: http://192.168.18.154:9200

3.App.java

package org.example;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

4.SwaggerConfig.java

package org.example.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 李庆伟
 */
@ConditionalOnWebApplication
@Configuration
@EnableSwagger2WebMvc
@EnableKnife4j
public class SwaggerConfig {

    /**
     * Swagger2的配置文件,这里可以配置Swagger2的一些基本的内容,比如扫描的包等等
     * []
     * @return {@link Docket}
     * @throws
     * @author 李庆伟
     */
    @Bean
    public Docket createRestApi() {
        //设置请求在父类方法中,如果在本类方法中设置请求头,则覆盖父类方法
        List<Parameter> pars = makeHeader();
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                //多包扫描
                .apis(RequestHandlerSelectors.basePackage(makeScanOne()))
                        //.or(RequestHandlerSelectors.basePackage(makeScanTwo()))
                        //.or(RequestHandlerSelectors.basePackage(makeScanThree())))
                //.apis(RequestHandlerSelectors.basePackage(App8300.class.getPackage().getName()))
                .build()
                .globalOperationParameters(pars)
                .apiInfo(apiInfo());
    }

    /**
     * swagger封装请求头
     * [pars]
     * @return {@link List< Parameter>}
     * @throws
     * @author 李庆伟
     */
    public List<Parameter> makeHeader(){
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder token = new ParameterBuilder();
        token.name("Authorization").description("Authorization")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false).build();
        pars.add(token.build());

        ParameterBuilder languageCode = new ParameterBuilder();
        languageCode.name("languageCode").description("languageCode")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false).build();
        pars.add(languageCode.build());

        return pars;
    }

    public String makeScanOne(){
        return "org.example.controller";
    }



    /**
     * 构建API文档的详细信息函数
     * @return
     */
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(makeApiName())
                .version("1.0")
                .build();
    }

    public String makeApiName(){
        return "文档服务接口-API";
    }


}

5.EsBook.java

package org.example.entity;



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.Date;

@Data
@Document(indexName = "es_book_index",type = "xiyouji")
//indexName相当于数据库   type相当于表  实体属性相当于表的字段
public class EsBook {


    @Id
    private String id;//章节

    @Field(store = true, type = FieldType.Keyword)
    private String title;//章节名称

    @Field(store = true, type = FieldType.Keyword)
    private String code;//章节编码

}

6.IndexController.java

package org.example.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.entity.EsBook;
import org.example.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/index")
@Api(value = "索引_相当于数据库", tags = "索引_相当于数据库")
public class IndexController {


    @Autowired
    private IndexService indexService;

    /**
     * 添加
     * @return {@link }
     * @throws
     * @author
     * @date
     */
    @PostMapping(value = "/add")
    @ApiOperation(value = "添加", notes = "添加", produces = "application/json")
    public String add(EsBook esBook) {
        indexService.add(esBook);
        return "ok";
    }

    /**
     * 修改
     * @return {@link }
     * @throws
     * @author
     * @date
     */
    @PostMapping(value = "/update")
    @ApiOperation(value = "修改", notes = "修改", produces = "application/json")
    public String update(EsBook esBook) {
        indexService.update(esBook);
        return "ok";
    }

    /**
     * 查询
     * @return {@link }
     * @throws
     * @author
     * @date
     */
    @PostMapping(value = "/query")
    @ApiOperation(value = "查询", notes = "查询", produces = "application/json")
    public List<EsBook> findQuery(EsBook esBook) {
        List<EsBook> list = indexService.findListByQuery(esBook);
        return list;
    }

    /**
     * 分页
     * @return {@link }
     * @throws
     * @author
     * @date
     */
    @PostMapping(value = "/findByPage")
    @ApiOperation(value = "分页查询", notes = "分页查询", produces = "application/json")
    public Page<EsBook> findByPage(@ApiParam(required = true, value = "pageNo") @RequestParam(value = "pageNo", required = true) Integer pageNo,
                                   @ApiParam(required = true, value = "pageSize") @RequestParam(value = "pageSize", required = true) Integer pageSize,
                                   @ApiParam(required = false, value = "title") @RequestParam(value = "title", required = false) String title) {
        Page<EsBook> list = indexService.findByPage(pageNo, pageSize, title);
        return list;
    }

    /**
     * 详情
     * @return {@link }
     * @throws
     * @author
     * @date
     */
    @PostMapping(value = "/show")
    @ApiOperation(value = "详情", notes = "详情", produces = "application/json")
    public EsBook show(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {
        EsBook es = indexService.get(id);
        return es;
    }

    /**
     * 删除
     * @return {@link }
     * @throws
     * @author
     * @date
     */
    @PostMapping(value = "/delete")
    @ApiOperation(value = "删除", notes = "删除", produces = "application/json")
    public String delete(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {
        indexService.delete(id);
        return "ok";
    }

}

7.IndexService.java

package org.example.service;

import org.example.entity.EsBook;
import org.springframework.data.domain.Page;

import java.util.List;

public interface IndexService {


    void add(EsBook esBook);

    void delete(String id);

    void update(EsBook esBook);

    List<EsBook> findListByQuery(EsBook esBook);

    EsBook get(String id);

    Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title);
}

8.IndexServiceImpl.java

package org.example.service.impl;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.example.entity.EsBook;
import org.example.mapper.EsBookMapper;
import org.example.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
public class IndexServiceImpl implements IndexService {


    @Autowired
    private EsBookMapper esBookMapper;

    @Override
    public void add(EsBook esBook) {
        esBook.setId(UUID.randomUUID().toString().replace("-", ""));
        esBookMapper.save(esBook);
    }

    @Override
    public void update(EsBook esBook) {
        esBookMapper.save(esBook);
    }

    @Override
    public List<EsBook> findListByQuery(EsBook esBook) {
        List<EsBook> list = new ArrayList<>();

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("title", esBook.getTitle()));

        Iterable<EsBook> it = esBookMapper.search(queryBuilder);
        it.forEach(e->list.add(e));
        return list;
    }

    @Override
    public EsBook get(String id) {
        try {
            return esBookMapper.findById(id).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
               // .withQuery(QueryBuilders.matchPhraseQuery("name", kw))
                .withPageable(PageRequest.of(pageNo, pageSize))
                .build();
        return esBookMapper.search(searchQuery);
    }

    @Override
    public void delete(String id) {
        EsBook esBook = new EsBook();
        esBook.setId(id);
        esBookMapper.delete(esBook);
    }


}

9.EsBookMapper.java

package org.example.mapper;

import org.example.entity.EsBook;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface EsBookMapper extends ElasticsearchRepository<EsBook,String> {



}

总结一下,记录一点点。。。。。。。。。。。。。。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2277488.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

阀井可燃气体监测仪,开启地下管网安全新篇章-旭华智能

在城市的脉络中&#xff0c;地下管网犹如隐秘的动脉&#xff0c;支撑着现代生活的运转。而在这庞大网络的关键节点上&#xff0c;阀井扮演着不可或缺的角色。然而&#xff0c;由于其密闭性和复杂性&#xff0c;阀井内部一旦发生可燃气体泄漏&#xff0c;将对公共安全构成严重威…

C#中通道(Channels)的应用之(生产者-消费者模式)

一.生产者-消费者模式概述 生产者-消费者模式是一种经典的设计模式&#xff0c;它将数据的生成&#xff08;生产者&#xff09;和处理&#xff08;消费者&#xff09;分离到不同的模块或线程中。这种模式的核心在于一个共享的缓冲区&#xff0c;生产者将数据放入缓冲区&#x…

4.寻找两个正序数组的中位数--力扣

给定两个大小分别为 m 和 n 的正序&#xff08;从小到大&#xff09;数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。 算法的时间复杂度应该为 O(log (mn)) 。 示例 1&#xff1a; 输入&#xff1a;nums1 [1,3], nums2 [2] 输出&#xff1a;2.00000 解释&…

2Spark Core

2Spark Core 1.RDD 详解1) 为什么要有 RDD?2) RDD 是什么?3) RDD 主要属性 2.RDD-API1) RDD 的创建方式2) RDD 的算子分类3) Transformation 转换算子4) Action 动作算子 3. RDD 的持久化/缓存4. RDD 容错机制 Checkpoint5. RDD 依赖关系1) 宽窄依赖2) 为什么要设计宽窄依赖 …

面试题刷题

i 或 i 基础几个9&#xff08;评价系统的指标&#xff09; Arrays.aslist 的bug 方法做了重写 这样就能使用了 list的迭代器 不能使用list.remove方法。需要使用迭代器的remove方法 正确操作 Hashcode hashcode是object对象的方法 是一个native方法 hashcode冲突案例和hashcod…

编译pytorch——cuda-toolkit-nvcc

链接 https://blog.csdn.net/wjinjie/article/details/108997692https://docs.nvidia.com/cuda/cuda-installation-guide-linux/#switching-between-driver-module-flavorshttps://forums.developer.nvidia.com/t/can-not-load-nvidia-drivers-on-ubuntu-22-10/239750https://…

Linux网络_套接字_UDP网络_TCP网络

一.UDP网络 1.socket()创建套接字 #include<sys/socket.h> int socket(int domain, int type, int protocol);domain (地址族): AF_INET网络 AF_UNIX本地 AF_INET&#xff1a;IPv4 地址族&#xff0c;适用于 IPv4 协议。用于网络通信AF_INET6&#xff1a;IPv6 地址族&a…

【Go】Go Gorm 详解

1. 概念 Gorm 官网&#xff1a;https://gorm.io/zh_CN/docs/ Gorm&#xff1a;The fantastic ORM library for Golang aims to be developer friendly&#xff0c;这是官网的介绍&#xff0c;简单来说 Gorm 就是一款高性能的 Golang ORM 库&#xff0c;便于开发人员提高效率 那…

51单片机 AT24C02(I2C总线)

存储器 随机存储 RAM 只读存储 ROM AT24C02芯片 是一种可以实现掉电不丢失的存储器&#xff0c;可用于保存单片机运行时想要永久保存的数据信息 存储材质&#xff1a;E2PROM 通讯接口&#xff1a;I2C总线 容量&#xff1a;256字节 I2C总线 一种通用的数据总线 两根通信线…

再见IT!

再见IT 学了三年半前端&#xff0c;今天可能真的要和我最爱的前端说拜拜了&#xff01;没办法大局为重&#xff01; 在这个AI乱飞和短视频风口的时代&#xff0c;只能说当下学习任何一个技术远比2020年学习起来要简单的多。往后技术的发展无疑是飞速的&#xff0c;智能的&…

【开源免费】基于Vue和SpringBoot的人口老龄化社区服务与管理平台(附论文)

本文项目编号 T 140 &#xff0c;文末自助获取源码 \color{red}{T140&#xff0c;文末自助获取源码} T140&#xff0c;文末自助获取源码 目录 一、系统介绍二、数据库设计三、配套教程3.1 启动教程3.2 讲解视频3.3 二次开发教程 四、功能截图五、文案资料5.1 选题背景5.2 国内…

回归预测 | MATLAB实SVM支持向量机多输入单输出回归预测

效果一览 基本介绍 回归预测 | MATLAB实SVM支持向量机多输入单输出回归预测 …………训练集误差指标………… 1.均方差(MSE)&#xff1a;166116.6814 2.根均方差(RMSE)&#xff1a;407.5741 3.平均绝对误差&#xff08;MAE&#xff09;&#xff1a;302.5888 4.平均相对百分误…

系统学习算法:专题四 前缀和

题目一&#xff1a; 算法原理&#xff1a; 这道题是一维前缀和的模板题&#xff0c;通过这道题我们可以了解什么是前缀和 题意很简单&#xff0c;就是先输入数组个数和查询次数&#xff0c;然后将数组的值放进数组&#xff0c;每次查询给2个数&#xff0c;第一个是起点&#x…

智能科技与共情能力加持,哈曼重新定义驾乘体验

2025年1月6日&#xff0c;拉斯维加斯&#xff0c;2025年国际消费电子展——想象一下&#xff0c;当您步入一辆汽车&#xff0c;它不仅能响应您的指令&#xff0c;更能理解您的需求、适应您的偏好&#xff0c;并为您创造一个独特且专属的交互环境。作为汽车科技领域的知名企业和…

[java基础-集合篇]LinkedBlockingQueue源码解析

关联较强的上一篇&#xff1a;[java基础-集合篇]有界阻塞队列ArrayBlockingQueue源码解析-CSDN博客 总的来说。LinkedBlockingQueue 是一个基于链表节点的自定大小的线程安全的阻塞队列。遵循FIFO&#xff0c;结构上一端进一端出的单向队列。 源码注释 翻译 An optionally-boun…

从论文到实践:Stable Diffusion模型一键生成高质量AI绘画

&#x1f3e1;作者主页&#xff1a;点击&#xff01; &#x1f916;编程探索专栏&#xff1a;点击&#xff01; ⏰️创作时间&#xff1a;2024年12月24日10点02分 神秘男子影, 秘而不宣藏。 泣意深不见, 男子自持重, 子夜独自沉。 AI绘画一键生成美图-变成画家 本地部…

业务幂等性技术架构体系之消息幂等深入剖析

在系统中当使用消息队列时&#xff0c;无论做哪种技术选型&#xff0c;有很多问题是无论如何也不能忽视的&#xff0c;如&#xff1a;消息必达、消息幂等等。本文以典型的RabbitMQ为例&#xff0c;讲解如何保证消息幂等的可实施解决方案&#xff0c;其他MQ选型均可参考。 一、…

【2024年华为OD机试】 (B卷,100分)- 跳房子I(Java JS PythonC/C++)

一、问题描述 题目描述 跳房子&#xff0c;也叫跳飞机&#xff0c;是一种世界性的儿童游戏。 游戏参与者需要分多个回合按顺序跳到第1格直到房子的最后一格。 跳房子的过程中&#xff0c;可以向前跳&#xff0c;也可以向后跳。 假设房子的总格数是count&#xff0c;小红每…

鸿蒙打包发布

HarmonyOS应用/元服务发布&#xff08;打包发布&#xff09; https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V13/ide-publish-app-V13?catalogVersionV13 密钥&#xff1a;包含非对称加密中使用的公钥和私钥&#xff0c;存储在密钥库文件中&#xff0c;格式…

JAVA:在IDEA引入本地jar包的方法(不读取maven目录jar包)

问题&#xff1a; 有时maven使用的jar包版本是最新版&#xff0c;但项目需要的是旧版本&#xff0c;每次重新install会自动将mavan的jar包覆盖到项目的lib目录中&#xff0c;导致项目报错。 解决&#xff1a; 在IDEA中手动配置该jar包对应的目录。 点击菜单File->Projec…