spring boot 3使用 elasticsearch 提供搜索建议的实例详解

 更新时间:2023年08月29日 17:02:53   作者:北漂的菜小白  
这篇文章主要介绍了spring boot3使用elasticsearch提供搜索建议,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

业务场景

用户输入内容,快速返回建议,示例效果如下

技术选型

  • spring boot 3
  • elasticsearch server 7.17.4
  • spring data elasticsearch 5.0.1
  • elasticsearch-java-api 8.5.3

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 测试结果如下

在这里插入图片描述

在这里插入图片描述

到此这篇关于spring boot 3使用 elasticsearch 提供搜索建议的文章就介绍到这了,更多相关spring boot elasticsearch搜索建议内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • struts2自定义MVC框架

    struts2自定义MVC框架

    这篇文章主要为大家详细介绍了struts2如何自定义MVC框架,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • Java中关于OAuth2.0的原理分析

    Java中关于OAuth2.0的原理分析

    这篇文章主要介绍了Java中关于OAuth2.0的原理分析,OAuth是一个关于授权的开放网络标准,允许用户授权第三 方应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,需要的朋友可以参考下
    2023-09-09
  • Java利用poi读取Excel详解实现

    Java利用poi读取Excel详解实现

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为简洁版的模糊实现
    2022-07-07
  • Java实现简单画画画板

    Java实现简单画画画板

    这篇文章主要为大家详细介绍了Java实现简单画画画板,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-06-06
  • 基于Flyway实现简化Spring Boot项目部署

    基于Flyway实现简化Spring Boot项目部署

    这篇文章主要介绍了基于Flyway实现简化Spring Boot项目部署,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • SpringBoot自动配置之自定义starter的实现代码

    SpringBoot自动配置之自定义starter的实现代码

    这篇文章主要介绍了SpringBoot自动配置之自定义starter的实现代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-10-10
  • 浅析对java枚举类型的认识

    浅析对java枚举类型的认识

    在本文里我们给大家分享了关于对java枚举类型的认识和相关知识点内容,有需要的朋友们跟着学习参考下。
    2019-03-03
  • Java经典排序算法之快速排序代码实例

    Java经典排序算法之快速排序代码实例

    这篇文章主要介绍了Java经典排序算法之快速排序代码实例,快速排序实现的思想是指通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,需要的朋友可以参考下
    2023-10-10
  • SpringBoot+RabbitMQ实现消息可靠传输详解

    SpringBoot+RabbitMQ实现消息可靠传输详解

    消息的可靠传输是面试必问的问题之一,保证消息的可靠传输主要在生产端开启 comfirm 模式,RabbitMQ 开启持久化,消费端关闭自动 ack 模式。本文将详解SpringBoot整合RabbitMQ如何实现消息可靠传输,需要的可以参考一下
    2022-05-05
  • 基于Java将Excel科学计数法解析成数字

    基于Java将Excel科学计数法解析成数字

    这篇文章主要介绍了基于Java将Excel科学计数法解析成数字,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09

最新评论