springboot2集成elasticsearch7.15.0(RestHighLevelClient)纯代码

springboot2集成elasticsearch7.15.0(RestHighLevelClient)纯代码,第1张

springboot2集成elasticsearch7.15.0(RestHighLevelClient)纯代码 maven坐标

    org.springframework.boot
    spring-boot-starter-data-elasticsearch



    
    7.15.0

配置
package net.test.springbootweb.es;

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


@Configuration
public class ElasticsearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        HttpHost httpHost = HttpHost.create("http://127.0.0.1:9200");
        RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
        return new RestHighLevelClient(restClientBuilder);
    }
}
服务
  • es和ik分词,可以找到以往对应的版本

https://www.elastic.co/cn/downloads/past-releases#elasticsearch
https://github.com/medcl/elasticsearch-analysis-ik/releases

  • ik分词解压到${esPath}/plugins下,压缩包不能放在该目录下,否则启动不起来
  • ${esPath}/bin下启动服务,访问 http://localhost:9200/,出现JSON信息
测试entity类
package net.test.springbootweb.es;

import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.time.LocalDateTime;


@Data
public class EsEntity {
    @Field(type = FieldType.Keyword, analyzer = "ik_smart")
    private String name;
    @Field(type = FieldType.Keyword, analyzer = "ik_max_word")
    private String description;
    private LocalDateTime createTime;

    public EsEntity() {
        this.createTime = LocalDateTime.now();
    }
}
测试索引
package net.test.springbootweb.es;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.GetAliasesResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Set;


@RestController
@RequestMapping("es")
public class ElasticsearchIndexTest {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    
    @RequestMapping("createEsIndex")
    public String createEsIndex(String index) throws IOException {
        //特殊字符直接报错,包含英文逗号(, ", *, \, <, |, ,, >, /, ?)
        if (existsEsIndex(index)) {
            return "index already exists";
        }
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        return JSONObject.toJSonString(createIndexResponse);
    }

    
    @RequestMapping("deleteEsIndex")
    public String deleteEsIndex(String... indices) throws IOException {
        if (notExistsEsIndex(indices)) {
            return "index does not exist";
        }
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indices);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        return JSONObject.toJSonString(delete);
    }

    
    @RequestMapping("getAllEsIndex")
    public Set getAllEsIndex() throws IOException {
        GetAliasesRequest getAliasesRequest = new GetAliasesRequest();
        GetAliasesResponse alias = restHighLevelClient.indices().getAlias(getAliasesRequest, RequestOptions.DEFAULT);
        return alias.getAliases().keySet();
    }

    
    public boolean existsEsIndex(String... indices) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest(indices);
        return restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    }

    
    public boolean notExistsEsIndex(String... indices) throws IOException {
        return !existsEsIndex(indices);
    }
}
测试文档
package net.test.springbootweb.es;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
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.common.xcontent.XContentType;
import org.elasticsearch.core.Timevalue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
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.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("es")
public class ElasticsearchdocumentTest {
    @Autowired
    private ElasticsearchIndexTest elasticsearchIndexTest;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    
    @RequestMapping("createdocument")
    public String createdocument(String index, String name, String description) throws IOException {
        if (elasticsearchIndexTest.notExistsEsIndex(index)) {
            return "index does not exist";
        }
        if (StringUtils.isAnyBlank(name, description)) {
            return "name or description can not be empty";
        }
        EsEntity esEntity = new EsEntity();
        esEntity.setName(name);
        esEntity.setDescription(description);
        IndexRequest indexRequest = new IndexRequest(index);
//        indexRequest.id("111");//可以设置ID,也可以不设置自动生成
        indexRequest.source(JSONObject.toJSonString(esEntity), XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        return "ID=" + response.getId() + ",INDEX=" + response.getIndex();
    }

    
    @RequestMapping("batchCreatedocument")
    public String[] batchCreatedocument(String index, String entityStr) throws IOException {
        if (elasticsearchIndexTest.notExistsEsIndex(index)) {
            return new String[]{"index does not exist"};
        }
        List esEntities = JSONArray.parseArray(entityStr, EsEntity.class);
        BulkRequest bulkRequest = new BulkRequest().timeout(new Timevalue(10, TimeUnit.SECONDS));
        for (EsEntity entity : esEntities) {
            IndexRequest indexRequest = new IndexRequest(index);
            indexRequest.source(JSONObject.toJSonString(entity), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        String[] arr = new String[esEntities.size()];
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        BulkItemResponse[] items = bulk.getItems();
        for (int i = 0; i < items.length; i++) {
            DocWriteResponse response = items[i].getResponse();
            arr[i] = "ID=" + response.getId() + ",INDEX=" + response.getIndex();
        }
        return arr;
    }

    
    @RequestMapping("updatedocument")
    public String updatedocument(String index, String id, String name, String description) throws IOException {
        if (notExistdocument(index, id)) {
            return "INDEX=" + index + ",DOC_ID=" + id + ",data does not exist";
        }
        UpdateRequest updateRequest = new UpdateRequest(index, id);
        //只修改传值(不为null)的字段,值相同不进行修改
        EsEntity esEntity = new EsEntity();
        esEntity.setName(name);
        esEntity.setDescription(description);
        updateRequest.doc(JSONObject.toJSonString(esEntity), XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return JSONObject.toJSonString(update);
    }

    
    @RequestMapping("deletedocument")
    public String deletedocument(String index, String id) throws IOException {
        if (notExistdocument(index, id)) {
            return "INDEX=" + index + ",DOC_ID=" + id + ",data does not exist";
        }
        DeleteRequest deleteRequest = new DeleteRequest(index, id);
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        return JSONObject.toJSonString(delete);
    }

    
    @RequestMapping("batchDeletedocument")
    public String[] batchDeletedocument(String index, String... ids) throws IOException {
        if (elasticsearchIndexTest.notExistsEsIndex(index)) {
            return new String[]{"index does not exist"};
        }
        BulkRequest bulkRequest = new BulkRequest();
        for (String id : ids) {
            DeleteRequest deleteRequest = new DeleteRequest(index, id);
            bulkRequest.add(deleteRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        String[] arr = new String[ids.length];
        BulkItemResponse[] items = bulk.getItems();
        for (int i = 0; i < items.length; i++) {
            arr[i] = JSONObject.toJSonString(items[i].getResponse());
        }
        return arr;
    }

    
    @RequestMapping("getdocument")
    public JSonObject getdocument(String index, String id) throws IOException {
        GetRequest getRequest = new GetRequest(index, id);
        if (notExistdocument(getRequest)) {
            throw new RuntimeException("INDEX=" + index + ",DOC_ID=" + id + ",data does not exist");
        }
        GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        JSonObject obj = JSONObject.parseObject(JSONObject.toJSonString(response.getSource()));
        obj.put("_id", response.getId());
        obj.put("_index", response.getIndex());
        return obj;
    }

    
    @RequestMapping("getAlldocument")
    public JSonArray getAlldocument(@RequestParam(value = "page", defaultValue = "1") int page,
                                    @RequestParam(value = "size", defaultValue = "5") int size,
                                    String... indices) throws IOException {
        CountRequest countRequest = new CountRequest();
        SearchRequest searchRequest = new SearchRequest();
        if (indices != null && indices.length > 0) {
            if (elasticsearchIndexTest.notExistsEsIndex(indices)) {
                throw new RuntimeException("indices does not exists");
            }
            searchRequest.indices(indices);
            countRequest.indices(indices);
        }
        CountResponse countResponse = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
        long count = countResponse.getCount();
        JSonArray array = new JSonArray();
        if (count > 0) {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //分页
            size = size <= 0 ? 5 : size;
            sourceBuilder.from((Math.max(1, page) - 1) * size);
            sourceBuilder.size(size);
//        sourceBuilder.sort("_id", SortOrder.DESC);
            //内容字段自定义排序(有些字段需要加.keyword)
            sourceBuilder.sort(new FieldSortBuilder("createTime").order(SortOrder.DESC));
            searchRequest.source(sourceBuilder);
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = search.getHits().getHits();
            for (SearchHit hit : hits) {
                JSonObject obj = new JSonObject(hit.getSourceAsMap());
                obj.put("_id", hit.getId());
                obj.put("_index", hit.getIndex());
                array.add(obj);
            }
        }
        return array;
    }

    
    @RequestMapping("searchdocument")
    public JSonArray searchdocument(String search, String... indices) throws IOException {
        if (elasticsearchIndexTest.notExistsEsIndex(indices)) {
            throw new RuntimeException("indices does not exists");
        }
        SearchRequest searchRequest = new SearchRequest(indices);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(0);
        sourceBuilder.size(100);
        sourceBuilder.sort(new FieldSortBuilder("createTime").order(SortOrder.DESC));
        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("description");
        highlightBuilder.requireFieldMatch(true);//仅查询此字段时才高亮,默认是false
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        sourceBuilder.highlighter(highlightBuilder);
//        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("name.keyword", search);//精准查询
//        WildcardQueryBuilder queryBuilder = QueryBuilders.wildcardQuery("name.keyword", "*" + search + "*");//模糊搜索
//        MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(search, "key1", "key2", "key3");//多字段查询
        //ik_smart ik_max_word
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("description", search);
        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        JSonArray array = new JSonArray();
        for (SearchHit hit : hits) {
            Map sourceAsMap = hit.getSourceAsMap();
            Map highlightFields = hit.getHighlightFields();
            HighlightField description = highlightFields.get("description");
            if (description != null) {
                //将高亮包含标签的内容容替换普通内容
                StringBuilder newText = new StringBuilder();
                for (Text fragment : description.getFragments()) {
                    newText.append(fragment);
                }
                sourceAsMap.put("description", newText.toString());
            }
            JSonObject obj = new JSonObject(sourceAsMap);
            obj.put("_id", hit.getId());
            obj.put("_index", hit.getIndex());
            array.add(obj);
        }
        return array;
    }

    
    public boolean existdocument(String index, String id) throws IOException {
        GetRequest getRequest = new GetRequest(index, id);
        return restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
    }

    
    public boolean existdocument(GetRequest request) throws IOException {
        return restHighLevelClient.exists(request, RequestOptions.DEFAULT);
    }

    
    public boolean notExistdocument(String index, String id) throws IOException {
        return !existdocument(index, id);
    }

    
    public boolean notExistdocument(GetRequest request) throws IOException {
        return !existdocument(request);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5676321.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存