首页 > 编程语言 >SpringBoot中ElaticSearch工具类-附源码

SpringBoot中ElaticSearch工具类-附源码

时间:2022-09-07 22:34:05浏览次数:83  
标签:indexName SpringBoot ElaticSearch param 源码 elasticsearch org import String

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http"))
        );
        return client;
    }
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
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;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ESUtil {

    @Autowired
    @Qualifier(value = "restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * 创建索引
     *
     * @param indexName 索引名称
     * @throws IOException
     */
    public void creatIndex(String indexName) {
        CreateIndexRequest indexRequest = new CreateIndexRequest(indexName);
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        try {
            if (!client.indices().exists(getIndexRequest, RequestOptions.DEFAULT)) {
                CreateIndexResponse indexResponse = client.indices().create(indexRequest, RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除索引
     *
     * @param indexName
     * @return
     */
    public Boolean deleteIndex(String indexName) {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        try {
            AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            return delete.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 添加对象
     *
     * @param indexName 索引名称
     * @param o         对象
     * @param o         id
     * @return
     */
    public String addDoc(String indexName, Object o, String id) {
        IndexRequest request = new IndexRequest(indexName);
        request.id(id);
        request.timeout("6s");
        request.source(JSON.toJSONString(o), XContentType.JSON);
        IndexResponse index = null;
        try {
            index = client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("添加addDoc失败");
        }
        return index.getId();
    }

    /**
     * 获取doc
     *
     * @param indexName 索引名称
     * @param id        docId
     * @return
     */
    public GetResponse getDocByIdAndIndexName(String indexName, String id) {
        GetRequest getRequest = new GetRequest(indexName, id);
        boolean exists = false;
        try {
            exists = client.exists(getRequest, RequestOptions.DEFAULT);
            if (exists) {
                GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
                return documentFields;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除doc
     *
     * @param indexName 索引名称
     * @param id        id
     * @return
     * @throws IOException
     */
    public Boolean deleteDocByIndexNameAndId(String indexName, String id) {
        DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
        DeleteResponse delete = null;
        try {
            delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "OK".equals(delete.status().toString());
    }

    /**
     * 修改doc
     *
     * @param indexName 索引名称
     * @param id        doc id
     * @param doc       对象
     */
    public Boolean updateDocByIndexNameAndId(String indexName, String id, Object doc) {
        UpdateRequest updateRequest = new UpdateRequest(indexName, id);
        updateRequest.timeout("1s");
        updateRequest.doc(JSONObject.toJSONString(doc), XContentType.JSON);
        UpdateResponse update = null;
        try {
            update = client.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "OK".equals(update.status().toString());
    }

    /**
     * 批量添加
     *
     * @param Indexname
     * @param list
     * @return
     */
    public Boolean batchAddDoc(String Indexname, List list) {
        BulkRequest bulkRequest = new BulkRequest();
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest(Indexname)
                    .source(JSONObject.toJSONString(list.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = null;
        try {
            bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "OK".equals(bulk.status().toString());
    }

    /**
     * 普通搜索
     *
     * @param indexName 索引名称
     * @param name      搜索的字段
     * @param keyword   搜索字段的值
     * @param pageNo    开始页码
     * @param pageSize  结束页码
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> searchPage(String indexName, String name, String keyword, Integer pageNo, Integer pageSize) throws IOException {
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 10 : pageSize;
        if (pageNo == null) {
            pageNo = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(name, keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        //返回结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            hit.getSourceAsMap().put("id",hit.getId());
            list.add(hit.getSourceAsMap());
        }
        return list;
    }


    /**
     * 高亮搜索(注意搜索的字段不能过长,不然只会展示一部分)
     *
     * @param indexName 索引名称
     * @param name      搜索的字段
     * @param keyword   搜索字段的值
     * @param pageNo    开始页码
     * @param pageSize  结束页码
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> searchHighPage(String indexName, String name, String keyword, Integer pageNo, Integer pageSize) throws IOException {
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 10 : pageSize;
        if (pageNo <= 1) {
            pageNo = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        //高亮搜索
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(name);
        highlightBuilder.requireFieldMatch(false);// tltie字段里面相同的字段出现多个高亮 关闭
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(name, keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        //返回结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //搜索结果
            //高亮部分
            sourceAsMap.put("id",hit.getId());
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get(name);

            if (title != null) {
                Text[] fragments = title.fragments();
                String newTitle = "";
                for (Text fragment : fragments) {
                    newTitle += fragment;
                }
                sourceAsMap.put(name, newTitle);
            }
            list.add(sourceAsMap);
        }
        return list;
    }


}

亲测好使~

标签:indexName,SpringBoot,ElaticSearch,param,源码,elasticsearch,org,import,String
From: https://www.cnblogs.com/big-keyboard/p/16667542.html

相关文章

  • SpringBoot + Caffeine实现本地缓存(内存缓存)
    1.Caffeine简介  Caffeine是一个基于Java8开发的提供了近乎最佳命中率的高性能的缓存库。借鉴GoogleGuava和ConcurrentLinkedHashMap的经验,实现内存缓存。  缓存和......
  • 大家都能看得懂的源码之 ahooks useVirtualList 封装虚拟滚动列表
    本文是深入浅出ahooks源码系列文章的第十八篇,该系列已整理成文档-地址。觉得还不错,给个star支持一下哈,Thanks。简介提供虚拟化列表能力的Hook,用于解决展示海量数据......
  • springboot集成ehcache
    目录springboot集成ehcache1、增加依赖2、增加ehcache.xml3、增加配置3.1、bootstrap.propertiesxml3.2、启动类增加配置4、工具类操作5、使用springboot集成ehcacheps:......
  • springboot通过注解Resource引用指定配置
    yaml配置文件中增加两个不同环境的配置:java配置文件,参考微信支付的代码:/***@author<ahref="https://github.com/binarywang">BinaryWang</a>*/@Slf4j@Config......
  • springboot的日志配置
    转载:https://blog.csdn.net/tz845195485/article/details/123361895#========================logging日志相关的配置=====================#日志级别trace<debug<inf......
  • SpringBoot解决BigDecimal传到前端后精度丢失问题
    1、局部处理(1)在相应字段上加@JsonFormat@JsonFormat(shape=JsonFormat.Shape.STRING)(2)在相应字段上加@JsonSerialize@JsonSerialize(using=ToStringSerializer.class......
  • springboot集成hibernate-validator
    一、项目搭建1、使用springboot搭建一个web工程建web工程,不使用骨架创建maven的Java工程即可,不需要创建maven的web工程。2、添加父工程坐标和添加web启动器<parent>......
  • Vben Admin 源码学习:状态管理-角色权限
    前言本文将对Vue-Vben-Admin角色权限的状态管理进行源码解读,耐心读完,相信您一定会有所收获!更多系列文章详见专栏......
  • SpringBoot使用自定义注解+AOP+Redis实现接口限流
    为什么要限流系统在设计的时候,我们会有一个系统的预估容量,长时间超过系统能承受的TPS/QPS阈值,系统有可能会被压垮,最终导致整个服务不可用。为了避免这种情况,我们就需要对......
  • SpringBoot常用注解
    SpringBoot常用注解1.@SpringBootApplicationspringBoot的基石,启动类@Configuration应许spring注册额外的bean或者导入其他配置类@EnableAutoConfiguration启用Sp......