springboot关于索引和文档的API操作详解

in ELK with 0 comment
package com.wen.wenesapi;

import com.alibaba.fastjson.JSON;
import com.wen.wenesapi.pojo.Question;
import com.wen.wenesapi.utils.ESConst;
import org.apache.catalina.User;
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.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.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * ES 7.4.2 高级客户端测试API
 */
@SpringBootTest
class WenEsApiApplicationTests {

    //面向对象来操作

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

    // 测试索引的创建 Request
    @Test
    void testCreateIndex() throws IOException {
        //1、创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("wen_index");
        //2、客户端执行请求IndicesClient,请求后获得响应
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);

        System.out.println(createIndexResponse);
    }

    //测试获取索引,判断是否存在
    @Test
    void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("wen_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }


    //测试删除索引
    @Test
    void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("wen_index");
        //删除
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

    //测试创建文档
    @Test
    void testAddDocument() throws IOException {
        //创建对象
        Question question = new Question("测试问题", "测试答案");
        //创建请求
        IndexRequest request = new IndexRequest("wen_index");

        //规则 post /wen_index/_doc
        request.timeout("1s");

        //将我们的数据放入请求 json
        request.source(JSON.toJSONString(question), XContentType.JSON);

        //客户端发送请求,获取响应的结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse.toString());
        System.out.println(indexResponse.status());
    }

    //测试获取文档,判断是否存在
    @Test
    void testIsExist() throws IOException {
        GetRequest getRequest = new GetRequest("wen_index", "eop9WnEBrCC7a6lBmEv7");
        //不获取返回的_source的上下文
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        //排序
        getRequest.storedFields("_none_");
        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    //获得文档的信息
    @Test
    void testGetDocument() throws IOException {
        GetRequest getRequest = new GetRequest("wen_index", "eop9WnEBrCC7a6lBmEv7");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString());//打印文档的内容
        System.out.println(getResponse);//返回的内容和命令式一致。
    }

    //更新文档的信息
    @Test
    void testUpdateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("wen_index", "eop9WnEBrCC7a6lBmEv7");
        updateRequest.timeout("1s");

        Question question = new Question("测试答案二", "测试问题二");
        updateRequest.doc(JSON.toJSONString(question), XContentType.JSON);

        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status());
    }

    //删除文档记录
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("wen_index", "eop9WnEBrCC7a6lBmEv7");
        deleteRequest.timeout("1s");

        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }

    //批量插入数据
    @Test
    void testBulkRequest() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        ArrayList<Question> questions = new ArrayList<>();
        questions.add(new Question("问题2", "答案2"));
        questions.add(new Question("问题3", "答案3"));
        questions.add(new Question("问题4", "答案4"));
        questions.add(new Question("问题5", "答案5"));
        questions.add(new Question("问题6", "答案6"));

        //批处理请求
        for (Question question : questions) {
            //批量更新或删除,都可以在此完成
            bulkRequest.add(new IndexRequest("wen_index")
                    .source(JSON.toJSONString(question), XContentType.JSON));
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        //打印是否执行失败,返回false代表成功
        System.out.println(bulkResponse.hasFailures());
    }

    //查询
    //SearchRequest 搜索请求
    //SearchSourceBuilder 搜索条件构造
    //
    @Test
    void testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESConst.ES_QUESTION_INDEX);
        //搜索条件构造
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //查询条件,建议使用 QueryBuilders
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("question", "问");
        sourceBuilder.query(matchQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = searchResponse.getHits();
        System.out.println(JSON.toJSONString(searchHits));
        System.out.println("=====================");
        for (SearchHit searchHit:searchHits.getHits()){
            System.out.println(searchHit.getSourceAsMap());
        }
    }


}
Responses