es-java-api

api 类

package com.api;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
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.client.indices.GetIndexResponse;
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.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ApiService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     */
    @SneakyThrows
    public CreateIndexResponse createIndex(String index) {
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return response;
    }


    /**
     * 查询索引
     */
    @SneakyThrows
    public GetIndexResponse queryIndex(String index) {
        GetIndexRequest request = new GetIndexRequest(index);
        GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
        return response;
    }


    /**
     * 删除索引
     */
    @SneakyThrows
    public AcknowledgedResponse removeIndex(String index) {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        return response;
    }


    /**
     * 添加文档
     */
    @SneakyThrows
    public IndexResponse addDocument(String index, String id, Object o) {
        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.id(id);
        indexRequest.timeout(TimeValue.timeValueSeconds(1));
        indexRequest.source(JSON.toJSONString(o), XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        return response;
    }

    /**
     * 删除文档
     */
    @SneakyThrows
    public DeleteResponse removeDocument(String index, String id) {
        DeleteRequest deleteRequest = new DeleteRequest(index, id);
        deleteRequest.id(id);
        deleteRequest.timeout(TimeValue.timeValueSeconds(1));
        DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        return response;
    }

    /**
     * 更新文档
     */
    @SneakyThrows
    public UpdateResponse updateDocument(String index, String id, Object o) {
        UpdateRequest updateRequest = new UpdateRequest(index, id);
        updateRequest.timeout(TimeValue.timeValueSeconds(1));
        updateRequest.doc(JSON.toJSONString(o),XContentType.JSON);
        UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return response;
    }

    /**
     * 查询文档是否存在
     */
    @SneakyThrows
    public boolean existsDocument(String index, String id) {
        GetRequest request = new GetRequest(index, id);
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");
        boolean response = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
        return response;
    }

    /**
     * 查询文档信息
     */
    @SneakyThrows
    public GetResponse queryDocument(String index, String id) {
        GetRequest request = new GetRequest(index, id);
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        return response;
    }

    /**
     * 批量插入文档信息
     */
    @SneakyThrows
    public BulkResponse bulkDocument(String index, List<Object> list) {
        BulkRequest bulkRequest = new BulkRequest(index);
        bulkRequest.timeout(TimeValue.timeValueSeconds(10));
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest(index)
                    .source(JSON.toJSONString(list.get(i)),XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return bulk;
    }

    /**
     * 检索文档文档信息
     * SearchRequest 搜索请求
     * SearchSourceBuilder 构造搜索条件
     * TermQueryBuilder Term查询
     * MatchQueryBuilder 分词器优化查询
     * HighlightBuilder 高亮查询
     */
    @SneakyThrows
    public SearchResponse searchDocument(String index, String key,String value) {
        //搜索请求
        SearchRequest searchRequest = new SearchRequest(index);
        //搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(0);
        sourceBuilder.size(10);
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(key, value);
        matchQueryBuilder.analyzer("ik_smart");
        sourceBuilder.query(matchQueryBuilder);
        sourceBuilder.timeout(TimeValue.timeValueSeconds(100));
        searchRequest.source(sourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        return search;
    }
}

测试类

package com.es.api;

import com.alibaba.fastjson.JSON;
import com.api.ApiService;
import com.dao.Student;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;

@SpringBootTest
class EsApiApplicationTests {
    @Autowired
    ApiService apiService;

    @Test
    void testCreateIndex() {
        CreateIndexResponse indexResponse = apiService.createIndex("jd");
        System.out.println(JSON.toJSONString(indexResponse));
    }
    @Test
    void testQueryIndex() {
        GetIndexResponse queryIndex = apiService.queryIndex("test");
        System.out.println(queryIndex.getSettings());
    }
    @Test
    void testDeleteIndex() {
        AcknowledgedResponse removeIndex = apiService.removeIndex("test");
        System.out.println(JSON.toJSONString(removeIndex));
    }

    @Test
    void testAddDoc() {
        Student student = new Student("张三",1);
        IndexResponse addDocument = apiService.addDocument("test","1",student);
        System.out.println(JSON.toJSONString(addDocument));

    }

    @Test
    void testUpdateDoc() {
        Student student = new Student("张三2",1);
        UpdateResponse updateDocument = apiService.updateDocument("test","1",student);
        System.out.println(JSON.toJSONString(updateDocument));

    }

    @Test
    void existsUpdateDoc() {
        Student student = new Student("张三2",1);
        boolean existsDocument = apiService.existsDocument("test","1");
        System.out.println(JSON.toJSONString(existsDocument));

    }

    @Test
    void deleteUpdateDoc() {
        DeleteResponse removeDocument = apiService.removeDocument("test","1");
        System.out.println(JSON.toJSONString(removeDocument));

    }
    @Test
    void queryUpdateDoc() {
        GetResponse queryDocument = apiService.queryDocument("test","1");
        System.out.println(queryDocument.getSourceAsString());
    }


    @Test
    void seqrchUpdateDoc() {
        //为啥会这样呢?张三为啥查不到?
        SearchResponse queryDocument = apiService.searchDocument("test","name","张三");不可以匹配到
        SearchResponse queryDocument2 = apiService.searchDocument("test","name","张");//可以匹配到
        SearchResponse queryDocument3 = apiService.searchDocument("test","name","三");//可以匹配到
        System.out.println(queryDocument);
        System.out.println(queryDocument2);
        System.out.println(queryDocument3);
    }

    @Test
    public void testBult()throws Throwable{
        Student student = new Student("张三",1);
        Student student2 = new Student("张三2",2);
        ArrayList<Object> list = new ArrayList<>();
        list.add(student);
        list.add(student2);
        BulkResponse bulkResponse = apiService.bulkDocument("test", list);
        System.out.println(bulkResponse.hasFailures());
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值