elasticsearch快速应用于SpringBoot

这篇具有很好参考价值的文章主要介绍了elasticsearch快速应用于SpringBoot。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

第一步:导入maven依赖

        <!--接入ES-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>

第二步:配置配置类


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfig {


    @Value("${spring.es.addrs.host}")
    private String url;
    @Value("${spring.es.addrs.port}")
    private Integer port;
    @Value("${spring.es.username}")
    private String username;
    @Value("${spring.es.password}")
    private String password;

    @Bean
    @Qualifier("restHighLevelClient")
    public RestHighLevelClient restHighLevelClient(){
        //需要用户名和密码的认证
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(url, port, "http"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                        return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
        return new RestHighLevelClient(restClientBuilder);
    }
}

第三步:工具类准备


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author reshui
 * @Description es工具类
 * @Date 2023/9/04
 * @Version 1.0
 */
@Slf4j
@Component
public class EsHandler<T> {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    public SearchHit[] search(String indexName, SearchSourceBuilder builder) throws IOException{
        SearchRequest request = new SearchRequest(indexName).source(builder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //SearchHits提供有关所有匹配的全局信息,例如总命中数或最高分数:
        SearchHits hits = response.getHits();
        return hits.getHits();
    }

    public <T> List<T> search(String indexName, SearchSourceBuilder builder,Class<T> clazz,String highlightField) throws IOException{
        SearchRequest request = new SearchRequest(indexName).source(builder);
        long start = System.currentTimeMillis();
        log.info("es 查询开始 ==== index:{} {}",indexName,builder.toString());
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        long end = System.currentTimeMillis();
        log.info("es 查询结束 ==== 命中:{} 耗时:{}",response.getHits().getTotalHits().value,end - start);
        //SearchHits提供有关所有匹配的全局信息,例如总命中数或最高分数:
        SearchHits hits = response.getHits();
        return parseSearchHits(hits.getHits(),clazz,highlightField);
    }

    public long count(String indexName, SearchSourceBuilder builder) throws IOException{
        CountRequest countRequest = new CountRequest(indexName);
        countRequest.source(builder);
        long start = System.currentTimeMillis();
        log.info("es count开始 ==== index:{} {}",indexName,builder.toString());
        CountResponse response = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
        long end = System.currentTimeMillis();
        log.info("es count结束 ==== 总量:{} 耗时:{}",response.getCount(),end - start);
        return response.getCount();
    }

    public boolean deleteByIds(String indexName, List<Integer> list) throws IOException{
        //创建批量操作请求
        BulkRequest request = new BulkRequest();
        for (Integer id : list) {
            request.add(new DeleteRequest().index(indexName).id(id.toString()));
        }
        //根据id批量删除es数据
        long start = System.currentTimeMillis();
        log.info("es 删除开始 ==== index:{} 数量:{}",indexName,list.size());
        BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        long end = System.currentTimeMillis();
        log.info("es 删除结束 ==== 耗时:{}",end - start);
        return true;
    }

    public boolean updateBulk(String indexName, List<T> list) throws IOException{
        //创建批量操作请求
        BulkRequest request = new BulkRequest();
        for (T t : list) {
            Map<String, Object> map = BeanUtil.beanToMap(t);
            Object id = map.get("id");
            if (id != null){
                request.add(new UpdateRequest().index(indexName).id(map.get("id").toString()).doc(map).docAsUpsert(true));
            }else {
                request.add(new UpdateRequest().index(indexName).doc(map).docAsUpsert(true));
            }
        }
        //根据id批量删除es数据
        long start = System.currentTimeMillis();
        log.info("es 批量更新开始 ==== index:{} 数量:{}",indexName,list.size());
        BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        long end = System.currentTimeMillis();
        log.info("es 批量更新结束 ==== 耗时:{}",end - start);
        return true;
    }

    public <T> List<T> parseSearchHits(SearchHit[] hits, Class<T> clazz, String highlightField) throws IOException{
        List<T> list = new ArrayList<>();
        if (hits == null || hits.length == 0){
            return list;
        }
        for (SearchHit hit : hits) {
            //获取到结果的map集合
            Map<String, Object> map = hit.getSourceAsMap();
            //设置高亮
            if (!StringUtils.isEmpty(highlightField)){
                //获取到高亮字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                //将高亮字段的具体内容取出来
                HighlightField str = highlightFields.get(highlightField);
                if (str != null) {
                    //得到高亮的字符串内容
                    Text[] fragments = str.fragments();
                    String highlight = "";
                    for (Text fragment : fragments) {
                        highlight += fragment;
                    }
                    //将原本没有高亮的结果集合中的title换为由高亮的
                    map.put(highlightField,highlight);
                }
            }

            //将map集合转换为实体类
            T t = JSON.parseObject(JSON.toJSONString(map), clazz);
            list.add(t);
        }
        return list;
    }


}

第四步:创建索引

    public boolean createMapping() {
        boolean flag = false;
        try {
            GetIndexRequest indexRequest = new GetIndexRequest(TEST_INDEX);
            boolean exists = client.indices().exists(indexRequest, RequestOptions.DEFAULT);
            if (exists) {
                return true;
            }

            //创建mapping
            XContentBuilder mappings = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("id").field("type", "long").field("store", true).endObject()

                    .startObject("classIds").field("type", "long").field("store", true).endObject()
                    .startObject("classLevels").field("type", "text").field("store", true).endObject()
                    .startObject("title").field("type", "text").field("store", true).endObject()
                    .endObject()
                    .endObject();

            //设置setting
            XContentBuilder settings = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("index").field("max_result_window", 100000).endObject()
                    .endObject();

            //创建索引
            CreateIndexRequest request = new CreateIndexRequest(TEST_INDEX);
            request.mapping(mappings);
            request.settings(settings);
            client.indices().create(request, RequestOptions.DEFAULT);
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

第五步:简单的使用方法测试

import com.eebbk.task.handler.EsHandler;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author reshui
 * @date 2023/9/4
 **/
@Slf4j
@SpringBootTest
public class EsHandlerTest {

    @Resource
    private EsHandler esHandler;

    private String indexName = "test_index";

    @Test
    void contextLoads() throws IOException {

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title").field("tag");
        highlightBuilder.preTags("<span style=\"color: red\">");
        highlightBuilder.postTags("</span>");
        SearchSourceBuilder builder = new SearchSourceBuilder().highlighter(highlightBuilder).from(1).size(100);
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("title","*"+"地球的运动"+"*"));
        List<PropertyVo> result = esHandler.search(indexName, builder.query(boolQueryBuilder), PropertyVo.class, title);

        System.out.println(result);
    }
}

文章来源地址https://www.toymoban.com/news/detail-694821.html

到了这里,关于elasticsearch快速应用于SpringBoot的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Data Elasticsearch - 在Spring应用中操作Elasticsearch数据库

    Spring Data Elasticsearch为文档的存储,查询,排序和统计提供了一个高度抽象的模板。使用Spring Data ElasticSearch来操作Elasticsearch,可以较大程度的减少我们的代码量,提高我们的开发效率。 要使用Elasticsearch我们需要引入如下依赖: 还需要在配置文件中增加如下配置 类比于MyBat

    2024年02月14日
    浏览(37)
  • spring boot集成Elasticsearch-SpringBoot(25)

      搜索引擎(search engine )通常意义上是指:根据特定策略,运用特定的爬虫程序从互联网上搜集信息,然后对信息进行处理后,为用户提供检索服务,将检索到的相关信息展示给用户的系统。   而我们讲解的是捜索的索引和检索,不涉及爬虫程序的内容爬取。大部分公司

    2023年04月09日
    浏览(95)
  • Springboot --- 整合spring-data-jpa和spring-data-elasticsearch

    SpringBoot: 整合Ldap. SpringBoot: 整合Spring Data JPA. SpringBoot: 整合Elasticsearch. SpringBoot: 整合spring-data-jpa和spring-data-elasticsearch. SpringBoot: 整合thymeleaf. SpringBoot: 注入第三方jar包. SpringBoot: 整合Redis. SpringBoot: 整合slf4j打印日志. SpringBoot: 整合定时任务,自动执行方法. SpringBoot: 配置多数据源

    2023年04月25日
    浏览(48)
  • Spring Boot快速入门:构建简单的Web应用

      Spring Boot是一个用于简化Spring应用程序开发的框架,它通过提供开箱即用的配置和一组常用的功能,使得构建高效、可维护的应用变得非常容易。在本篇博客中,我们将一步步地介绍如何快速入门Spring Boot,并构建一个简单的Web应用。 步骤1:准备开发环境 Java Development

    2024年02月07日
    浏览(48)
  • 入门Spring Boot:快速构建Java应用的利器

    Spring Boot是由Pivotal团队开发的开源框架,它基于Spring框架,旨在简化Java应用程序的开发过程。它提供了一种约定大于配置的方式,通过自动配置和起步依赖(Starter Dependencies)来消除繁琐的配置,从而使开发者能够更快地构建独立、可执行的、生产级的Spring应用。 与传统的

    2024年02月07日
    浏览(39)
  • Elasticsearch 7.6 - Springboot应用基础操作篇

    上文已经教了大家最基本的操作了,那我们在java代码里面要如何实现呢?本文的目的就是教大家在springboot框架下实现上文的API操作,也就是CURD! 首先我们要知道ES的API都是 HTTP请求!!!! ,所以什么语言都可以操作,就是发送请求和处理返回而已嘛,只是说现在这种封装

    2024年02月10日
    浏览(24)
  • “深入解析Spring Boot:快速开发Java应用的利器“

    标题:深入解析Spring Boot:快速开发Java应用的利器 摘要:Spring Boot是一个开发Java应用的利器,它简化了Spring应用的配置和部署过程,提供了快速构建和开发Java应用的能力。本文将深入解析Spring Boot的核心特性和优势,并通过示例代码来展示如何使用Spring Boot进行快速应用开发

    2024年02月16日
    浏览(36)
  • 快速入门:使用 Spring Boot 构建 Web 应用程序

    本文将讨论以下主题: 安装 Java JDK、Gradle 或 Maven 和 Eclipse 或 IntelliJ IDEA 创建一个新的 Spring Boot 项目 运行 Spring Boot 应用程序 编写一个简单的 Web 应用程序 打包应用程序以用于生产环境 通过这些主题,您将能够开始使用 Spring Boot 并创建自己的 Web 应用程序。 Spring Boot是一个

    2024年02月07日
    浏览(62)
  • SpringBoot 实现 elasticsearch 索引操作(RestHighLevelClient 的应用)

    RestHighLevelClient 是 Elasticsearch 官方提供的Java高级客户端,用于与 Elasticsearch 集群进行交互和执行各种操作。 主要特点和功能如下 : 强类型 :RestHighLevelClient 提供了强类型的 API,可以在编码过程中获得更好的类型安全性和 IDE 支持。 兼容性 :RestHighLevelClient 是 Elasticsearch 官方

    2024年02月11日
    浏览(33)
  • 使用Spring AI让你的Spring Boot应用快速拥有生成式AI能力

    之前分享了关于Spring新项目 Spring AI 的介绍视频。视频里演示了关于使用Spring AI将Open AI的能力整合到Spring应用中的操作,但有不少读者提到是否有博客形式的学习内容。所以,本文就将具体介绍如何使用 Spring AI 快速让您的Spring应用拥有生成式AI的强大能力。 第一步:使用你

    2024年02月03日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包