栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

SpringBoot ElasticSearch常用API

SpringBoot ElasticSearch常用API

ElasticSearch常用API

ElasticSearch常用API

ElasticSearch常用API
package com.chuang.until;

import com.alibaba.fastjson.JSON;
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.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.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.Timevalue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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


@Component
public class ESUtil {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    //创建索引
    public Boolean CreatemyIndex(String index) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }
    //判断一个索引是否存在
    public Boolean ExistIndex(String index) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest(index);
        return restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    }
    //删除索引
    public Boolean DeleteIndex(String index) throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        return delete.isAcknowledged();
    }
    //添加文档
    public RestStatus Adddocument(String index, String id, Object object) throws IOException {
        //索引创建规则 put /index/_doc/id
//        CreatemyIndex("sunchuang-index");
        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.id(id);
        indexRequest.timeout(Timevalue.timevalueSeconds(2));
        indexRequest.source(JSON.toJSONString(object), XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        RestStatus status = indexResponse.status();
        return status;   //Created 、update
    }
    // 判断文档是否存在 get /index/doc/1
    public  boolean documentIsExists(String index,String id) throws IOException {
        GetRequest getRequest = new GetRequest(index, id);
        //不获取返回的_source的上下文
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        return restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
    }
    //获取文档文本内容
    public Map Getdocument(String index,String id)throws IOException {
        GetRequest getRequest = new GetRequest(index, id);
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        return documentFields.getSource();
    }
    //获取索引下全部内容
    public GetResponse GetAlldocument(String index, String id)throws IOException {
        GetRequest getRequest = new GetRequest(index, id);
        return restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
    }

    //更新文档信息
    public RestStatus Updatedocument(String index, String id, Object updateobject) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(index, id);
        updateRequest.timeout("2s");
        updateRequest.doc(JSON.toJSONString(updateobject),XContentType.JSON);
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return updateResponse.status();
    }

    //删除文档记录
    public RestStatus Deletedocument(String index, String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(index,id);
        deleteRequest.timeout("1s");
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        return delete.status();
    }

    //批量操作
    public RestStatus BulkInsertdocument(ArrayList bulklist, String index) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("120s");
        for (int i = 0; i < bulklist.size(); i++) {
            bulkRequest.add(new IndexRequest(index)
                    .id(""+(i+1))
                    .source(JSON.toJSONString(bulklist.get(i)),XContentType.JSON)
            );
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return bulkResponse.status();
    }
    //自定义查询操作
    public ArrayList> SearchReques() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        QueryBuilder queryBuilder = new QueryBuilder();
        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("name", "chuang");
//        MatchAllQueryBuilder allQueryBuilder = QueryBuilders.matchAllQuery(); 搜索全部
//        高亮搜索
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//关闭多个高亮 仅仅title高亮
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        searchSourceBuilder.highlighter(highlightBuilder);
        //分页查询
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.from();
        searchSourceBuilder.size();
        searchSourceBuilder.timeout(new Timevalue(60, TimeUnit.SECONDS));
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        String jsonString = JSON.toJSonString(searchResponse.getHits());
        ArrayList> resultlist  = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
//            searchResponse.getHits().getHits()  待测试
            //解析高亮字段
            Map highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            //正常数据
            Map sourceAsMap = hit.getSourceAsMap();
            //与正常值置换
            if(title!=null){
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title",n_title);
            }

            resultlist.add(sourceAsMap);
            System.out.println(sourceAsMap);

        }
        return resultlist;
    }
}
package com.chuang.config;

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 ESClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.88.129", 9200, "http")
                )
        );
        System.out.println(client);
        return client;
    }

}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/746464.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号