Live2D

SpringBoot集成ElaticSearch工具类-附源码

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;
    }


}

亲测好使~

posted @ 2022-09-07 22:26  键盘命  阅读(76)  评论(0编辑  收藏  举报