spring boot 3使用 elasticsearch 提供搜索建议

news/2024/7/7 5:46:56 标签: spring boot, elasticsearch, 搜索引擎

业务场景

用户输入内容,快速返回建议,示例效果如下
在这里插入图片描述

技术选型

pom.xml

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

yml

spring:
  elasticsearch:
    uris: http://127.0.0.1:9200
  data:
    elasticsearch:
      repositories:
        enabled: true

实体类

为了启动时候自己创建相关的index,以及存储搜索内容


import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.core.suggest.Completion;

/**
 * 业务搜索建议
 * @author chunyang.leng
 * @date 2023-08-21 14:24
 */
@Document(indexName = "biz_suggest")
public class BizSuggestDocument {

    @Id
    private Long id;

    /**
     * 标题,可以用于纠错,不参与搜索建议
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String name;

    /**
     * 自动补全标题,搜索建议使用的对象
     */
    @CompletionField(analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private Completion completionName;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Completion getCompletionName() {
        return completionName;
    }

    public void setCompletionName(Completion completionName) {
        this.completionName = completionName;
    }
}

搜索结果对象


/**
 * 搜索建议返回对象
 * @author chunyang.leng
 * @date 2023-08-21 19:02
 */
public class SuggestVO {
    /**
     * 数据id
     */
    private Long id;

    /**
     * 内容
     */
    private String text;

    public Long getId() {
        return id;
    }

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

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

搜索业务层

  • 数据导入时候,因为有数据格式要求,必须使用实体类进行写入

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggester;
import co.elastic.clients.elasticsearch.core.search.Suggester;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import co.elastic.clients.elasticsearch.core.search.TermSuggester;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author chunyang.leng
 * @date 2023-08-18 18:29
 */
@Component
public class SuggestionServiceImpl implements SuggestionService {
    /**
     * 搜索建议 key
     */
    private static final String SUGGEST_TAG = "suggest_query";

    /**
     * 纠错key
     */
    private static final String TERM_TAG = "suggest_team";
    @Autowired
    private ElasticsearchClient elasticsearchClient;

    /**
     * 根据 关键词,返回搜索建议
     *
     * @param match 搜索关键词
     * @return 搜索建议,10条
     */
    @Override
    public List<SuggestVO> suggest(String match) throws IOException {
        SearchRequest completionSuggestSearchRequest = new SearchRequest
            .Builder()
            .suggest(
                new Suggester
                    .Builder()
                    .suggesters(SUGGEST_TAG, builder -> builder.prefix(match)
                        .completion(new CompletionSuggester
                            .Builder()
                            .field("completionName")
                            .size(10)
                            .build()
                        )
                    )
                    .build())
            .build();

        SearchResponse<BizSuggestDocument> completionSuggestSearch = elasticsearchClient.search(completionSuggestSearchRequest, BizSuggestDocument.class);

        Map<String, List<Suggestion<BizSuggestDocument>>> suggest = completionSuggestSearch.suggest();

        List<Suggestion<BizSuggestDocument>> suggestions = suggest.get(SUGGEST_TAG);

        return suggestions
            .parallelStream()
            .flatMap(x -> x.completion()
                .options()
                .stream()
                .map(o -> {
                      // 原始数据对象,如果有需要,可以对其进行操作
                    BizSuggestDocument source = o.source();
                    
                   
                    String text = o.text();
                    String idValue = o.id();
                    Long id = Long.valueOf(idValue);
                    SuggestVO vo = new SuggestVO();
                    vo.setId(id);
                    vo.setText(text);
                    return vo;
                }))
            .collect(Collectors.toList());
    }
}

导入数据


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.suggest.Completion;

/**
 * @author chunyang.leng
 * @date 2023-08-21 18:09
 */
@SpringBootTest
public class EsTest {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void test() {
        BizSuggestDocument document = new BizSuggestDocument();
        document.setId(1L);
        document.setName("飞翔的世界");

        String[] s = "你的世界1.0,我的世界2.0".split(",");
        Completion completion = new Completion(s);
        completion.setWeight(10);
        document.setCompletionName(completion);
        elasticsearchTemplate.save(document);


        BizSuggestDocument document2 = new BizSuggestDocument();
        document2.setId(2L);
        document2.setName("路人甲乙丙");

        String[] s2 = "你的滑板鞋1.0,我的滑板鞋2.0".split(",");
        Completion completion1 = new Completion(s2);
        completion1.setWeight(5);
        document2.setCompletionName(completion1);
        elasticsearchTemplate.save(document2);
    }
}

POSTMAN 测试结果如下

在这里插入图片描述
在这里插入图片描述


http://www.niftyadmin.cn/n/4956743.html

相关文章

【leetcode】20.有效的括号

题目分析&#xff1a; 给定的字符串s可能为空串&#xff0c;空串返回false&#xff0c;不为空串时进行以下操作 遍历字符串&#xff0c;左括号 ( 、 [ 、 { 压栈&#xff0c;右括号与此时的栈顶元素对比匹配 1️⃣匹配&#xff0c;则栈顶元素出栈&#xff0c;继续遍历字符串 2️…

smartsofthelp 5.0 最干净,最简单,最方便,最全面的开发辅助优化工具,最值得推荐的程序员开发工具

下载地址&#xff1a;百度网盘 请输入提取码 model &#xff1a; /// <summary> /// Model实体层 /// </summary> namespace Smart.Model { /// <summary> /// 数据实体层 city /// </summary> [Serializable] public partial …

对类加载过程的通俗理解

开局一张图 一般来说&#xff0c;类加载分为&#xff1a;加载、验证、准备、解析、初始化 5个步骤。 各阶段略叙 1、加载 将.class文件加载进内存 2、验证 判断.class文件的格式是否正确 3、准备 为类的静态变量分配内存并设置初始值。只有b、c会在此阶段进行处理。 //…

《Linux运维总结:Centos7.6之OpenSSH7.4p1升级版本至9.4p1》

Centos通过yum升级OpenSSH 在官方支持更新的CentOS版本&#xff0c;如果出现漏洞&#xff0c;都会通过更新版本来修复漏洞。这时候直接使用yum update就可以升级版本。 yum -y update openssh 但是&#xff0c;CentOS更新需要有一段时间&#xff0c;不能在漏洞刚出来的时候就有…

Linux —— 进程间通信(管道)

目录 一&#xff0c;进程间通信 二&#xff0c;管道 匿名管道 命名管道 一&#xff0c;进程间通信 进程间通信&#xff08;IPC&#xff0c;InterProcess Communication&#xff09;&#xff0c;即在不同进程之间进行信息的传播或交换&#xff1b;由于一般进程用户地址空间是…

微星笔记本暑促好货多多,开学季选购看这里!

随着即将到来的学期的临近&#xff0c;学生族如何选择一款称手的笔记本&#xff0c;就提上了日程。各种产品定位取向&#xff0c;各种价格范围&#xff0c;如果没有明确自己的需求和预算&#xff0c;就有点不知所措了~OK&#xff0c;今天就让我们从需求&预算出发&#xff0…

Redis中的有序集合及其底层跳表

前言 本文着重介绍Redis中的有序集合的底层实现中的跳表 有序集合 Sorted Set Redis中的Sorted Set 是一个有序的无重复值的集合&#xff0c;他底层是使用压缩列表和跳表实现的&#xff0c;和Java中的HashMap底层数据结构&#xff08;1.8&#xff09;链表红黑树异曲同工之妙…

Shell 编程:探索 Shell 的基本概念与用法

目录 Shell 简介 Shell 脚本 Shell 脚本运行 Shell 变量 1、创建变量和赋值 2、引用变量 3、修改变量的值 4、只读变量 5、删除变量 6、环境变量 Shell 字符串操作 1、拼接字符串 2、字符串长度 3、字符串截取 Shell 数组 1、创建数组 2、访问数组元素 shell …