利用JavaRestClient依赖使用java操作索引库

cyknote / 2024-03-11 / 原文

引入依赖

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.12.1</version>
        </dependency>

这里可能会出现这种情况,我导入的是7.12.1的版本,但有两个maven依赖的版本并不是我们想要的7.12.1。

这是因为我们继承了spring-boot-starter-parent父工程,他的版本控制中限制了这两项的依赖的版本,所以我们需要再配置下图中的版本

下列代码为利用JavaRestClient对ES进行的CRUD操作

lsty为自己取得索引库名

package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

@SpringBootTest
public class HotelIndexTest {

    private RestHighLevelClient client;

    @Autowired
    private IHotelService hotelService;

    //创建索引库
    @Test
    void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("lsty");
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    //删除索引库
    @Test
    void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("lsty");
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

    //查询索引库是否存在
    @Test
    void ExistsIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("lsty");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }


    //向索引库添加文档
    @Test
    void testAddDocument() throws IOException {
        Hotel hotel = hotelService.getById(61083);//从数据库读取数据罢了,不重要
        
        HotelDoc hotelDoc = new HotelDoc(hotel);
        IndexRequest request = new IndexRequest("lsty").id(hotelDoc.getId().toString());
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

    //删除文档
    @Test
    void testGetDocumentById() throws IOException {
        GetRequest request = new GetRequest("lsty","61083");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        String json = response.getSourceAsString();
        System.out.println(json);
    }

    //更新文档(也可以直接用添加文档全面覆盖)
    @Test
    void testUpdateDocumentById() throws IOException {
        UpdateRequest request = new UpdateRequest("lsty","61083");
        request.doc(
                "price","182",
                "starName","三钻"
        );
        client.update(request,RequestOptions.DEFAULT);
    }

    //删除文档
    @Test
    void testDeleteDocumentById() throws IOException {
        DeleteRequest request = new DeleteRequest("lsty","61083");
        client.delete(request,RequestOptions.DEFAULT);
    }

    //批量操作文档
    @Test
    void testBulk() throws IOException {
        List<Hotel> list = hotelService.list(); //从数据库读取数据,不重要
        
        BulkRequest request = new BulkRequest();
        for (Hotel hotel:list){
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.add(new IndexRequest("lsty").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON));
        }
        client.bulk(request,RequestOptions.DEFAULT);
    }

    //与ES创建链接
    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.230.100:9200")
        ));
    }

    //断开与ES的链接
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }


}