springboot3.x集成elasticsearch

/ 后端 / 没有评论 / 912浏览

pom

springboot版本为3.2.2

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

配置文件

spring:
  elasticsearch:
    uris: es-cn-xxx.public.elasticsearch.aliyuncs.com:9200
    username: elastic
    password: xxxx
    connection-timeout: 3s
    socket-timeout: 30s
    socketKeepAlive: true

实体类

@Document(indexName = "course_index")
public class CourseNameVO {

    @Id
    private Integer id;
    @Field(type = FieldType.Text, searchAnalyzer = "ik_smart")
    private String courseName;
    @Field(type = FieldType.Text, searchAnalyzer = "ik_max_word")
    private String desc;

    public CourseNameVO() {
    }

    public CourseNameVO(Integer id, String courseName, String desc) {
        this.id = id;
        this.courseName = courseName;
        this.desc = desc;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "CourseNameVO{" +
                "id=" + id +
                ", courseName='" + courseName + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

测试用例

package com.boot.boottest;

import co.elastic.clients.elasticsearch._types.query_dsl.CombinedFieldsOperator;
import co.elastic.clients.elasticsearch._types.query_dsl.CombinedFieldsQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.MultiMatchQuery;
import com.boot.boottest.entity.CourseNameVO;
import com.boot.boottest.sqlTest.CourseNameSql;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;

import java.util.List;

@SpringBootTest
class BootTestApplicationTests {

    @Resource
    ElasticsearchTemplate elasticsearchTemplate;

    //创建索引
    @Test
    void addIndex() {
        IndexOperations indexOperations = elasticsearchTemplate.indexOps(CourseNameVO.class);
        if (indexOperations.exists()) {
            System.out.println("已存在");
        } else {
            boolean b = indexOperations.create();
            System.out.println("创建成功");
        }
    }

    //删除索引
    @Test
    void deleteIndex() {
        IndexOperations indexOperations = elasticsearchTemplate.indexOps(CourseNameVO.class);
        if (indexOperations.exists()) {
            indexOperations.delete();
            System.out.println("已删除");
        } else {
            System.out.println("不存在");
        }
    }

    //查看索引
    @Test
    void selectIndex() {
        IndexOperations indexOperations = elasticsearchTemplate.indexOps(CourseNameVO.class);
        System.out.println(indexOperations.getMapping());
    }

    //插入数据
    @Test
    void add() {
        elasticsearchTemplate.save(CourseNameSql.courseNameVOList, IndexCoordinates.of("course_index"));
    }

    //查看总数
    @Test
    void count() {
        long course_index = elasticsearchTemplate.count(Query.findAll(), CourseNameVO.class, IndexCoordinates.of("course_index"));
        System.out.println(course_index);
    }

    @Test
    void queryById() {
        CourseNameVO courseNameVO = elasticsearchTemplate.get("14", CourseNameVO.class, IndexCoordinates.of("course_index"));
        if (courseNameVO != null) {
            System.out.println(courseNameVO);
        }
    }

    //查询所有数据,不分页
    @Test
    void queryAll() {
        Query all = Query.findAll();
        all.setPageable(Pageable.unpaged());
        SearchHits<CourseNameVO> search = elasticsearchTemplate.search(all, CourseNameVO.class);
        search.getSearchHits().forEach(s -> {
            CourseNameVO content = s.getContent();
            System.out.println(content);
        });
    }

    //查询所有数据,分页,并根据id降序排列
    @Test
    void queryPage() {
        Query all = Query.findAll();
        all.setPageable(PageRequest.of(0, 10, Sort.by("id").descending()));
        SearchHits<CourseNameVO> search = elasticsearchTemplate.search(all, CourseNameVO.class);
        search.getSearchHits().forEach(s -> {
            CourseNameVO content = s.getContent();
            System.out.println(content);
        });
    }

    //根据课程名模糊查询,并高亮
    @Test
    void queryName() {
        MatchQuery build = new MatchQuery.Builder().field("courseName").query("王芳课").build();
        co.elastic.clients.elasticsearch._types.query_dsl.Query query = new co.elastic.clients.elasticsearch._types.query_dsl.Query(build);

        Highlight highlight = new Highlight(List.of(new HighlightField("courseName")));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, CourseNameVO.class);

        NativeQuery nativeQuery = NativeQuery.builder().withQuery(query).build();
        nativeQuery.setPageable(Pageable.unpaged());
        nativeQuery.setHighlightQuery(highlightQuery);

        SearchHits<CourseNameVO> search = elasticsearchTemplate.search(nativeQuery, CourseNameVO.class);
        search.getSearchHits().forEach(s -> {
            List<String> courseName = s.getHighlightField("courseName");
            courseName.forEach(System.out::println);
            CourseNameVO content = s.getContent();
            System.out.println(content);
            System.out.println();
        });
    }

    //课程名和备注同时模糊查询关键词,并高亮
    @Test
    void queryNameAndDesc() {

        MultiMatchQuery build1 = new MultiMatchQuery.Builder().fields("courseName", "desc").query("王芳开学了").build();
        co.elastic.clients.elasticsearch._types.query_dsl.Query query = new co.elastic.clients.elasticsearch._types.query_dsl.Query(build1);

        NativeQuery nativeQuery = NativeQuery.builder()
                .withQuery(query)
                .build();

        Highlight highlight = new Highlight(List.of(new HighlightField("courseName"), new HighlightField("desc")));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, CourseNameVO.class);
        nativeQuery.setPageable(Pageable.unpaged());
        nativeQuery.setHighlightQuery(highlightQuery);

        SearchHits<CourseNameVO> search = elasticsearchTemplate.search(nativeQuery, CourseNameVO.class);
        search.getSearchHits().forEach(s -> {
            s.getHighlightField("courseName").forEach(System.out::println);
            s.getHighlightField("desc").forEach(System.out::println);
            CourseNameVO content = s.getContent();
            System.out.println(content);
            System.out.println();
        });
    }


    //课程名和备注分别模糊查询
    @Test
    void queryNameAndDesc2() {

        CombinedFieldsQuery build1 = new CombinedFieldsQuery.Builder()
                .fields("courseName").query("王芳")
                .operator(CombinedFieldsOperator.Or)
                .fields("desc").query("开学")
                .build();
        co.elastic.clients.elasticsearch._types.query_dsl.Query query = new co.elastic.clients.elasticsearch._types.query_dsl.Query(build1);


        NativeQuery nativeQuery = NativeQuery.builder()
                .withQuery(query)
                .build();

        Highlight highlight = new Highlight(List.of(new HighlightField("courseName"), new HighlightField("desc")));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, CourseNameVO.class);
        nativeQuery.setPageable(Pageable.unpaged());
        nativeQuery.setHighlightQuery(highlightQuery);

        SearchHits<CourseNameVO> search = elasticsearchTemplate.search(nativeQuery, CourseNameVO.class);
        search.getSearchHits().forEach(s -> {
            s.getHighlightField("courseName").forEach(System.out::println);
            s.getHighlightField("desc").forEach(System.out::println);
            CourseNameVO content = s.getContent();
            System.out.println(content);
            System.out.println();
        });
    }
}