RestClient操作文档

本文介绍了如何在SpringBoot项目中使用RestHighLevelClient进行Elasticsearch的CRUD操作,包括初始化客户端、插入、查询、更新和删除文档,以及批量导入数据。

初始化RestClient

@Autowired
    private RestHighLevelClient client;
 @BeforeEach
    void setUp(){
        client = new RestHighLevelClient(RestClient.builder(
                // 这里可以是多个 如果有多个es集群
                HttpHost.create("http://192.168.88.135:9200")
        ));
    }
    @AfterEach
    void setDown(){
        try {
            client.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

新增数据

void testInsert() throws IOException {
		// mybatisplus 查询到表中的数据 
        Hotel hotel = iHotelService.getById(609372L);
        // 转换成与索引库字段相对应的实体类
        HotelDoc hd = new HotelDoc(hotel);
        // POST /hotel/_doc/609372
        IndexRequest request = new IndexRequest("hotel").id(hd.getId()+"");
        // 创建将对象转成JSON对象
        request.source(JSON.toJSONString(hd),XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }

查询文档

 @Test
    void getDocument() throws IOException {
        // GET /hotel/_doc/609372
        GetRequest request = new GetRequest("hotel","609372");
        // 发送请求并得到响应
        GetResponse res = client.get(request, RequestOptions.DEFAULT);
        // 将 _source里面内容转换成字符串
        String sourceAsString = res.getSourceAsString();
        // JSON解析成对象
        HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
        System.out.println(hotelDoc);
    }

更新文档

 @Test
    void updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("hotel","609372");
        //民治街道梅龙路与民旺路交汇处
        request.doc(
                // 他这里是以逗号隔开 逗号的左右为一个键值对
                "address","民治街道梅龙路与民旺路交汇处",
                "price","498"
        );
        client.update(request,RequestOptions.DEFAULT);
    }

删除文档

@Test
    void deleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("hotel","609372");
        client.delete(request,RequestOptions.DEFAULT);
    }

批量导入文档数据

 @Test
    void bulkDocument() throws IOException {
        List<Hotel> list = iHotelService.list();
        BulkRequest request = new BulkRequest();
        for (Hotel hotel : list) {
            HotelDoc hd = new HotelDoc(hotel);
            request.add(new IndexRequest("hotel").id(hd.getId()+"")
                    .source(JSON.toJSONString(hd),XContentType.JSON));
        }
        client.bulk(request,RequestOptions.DEFAULT);
    }
使用RestClient操作Elasticsearch主要分为以下步骤: ### 1. 引入依赖 需要引入es的RestHighLevelClient依赖,示例代码如下: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency> ``` 因为SpringBoot默认的ES版本是7.6.2,所以需要覆盖默认的ES版本,示例代码如下: ```xml <properties> <java.version>1.8</java.version> <elasticsearch.version>7.12.1</elasticsearch.version> </properties> ``` ### 2. 初始化RestHighLevelClient 在elasticsearch提供的API中,与elasticsearch一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立与elasticsearch的连接。示例代码如下: ```java import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; public class ElasticsearchClientConfig { public static RestHighLevelClient getRestHighLevelClient() { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"))); return client; } } ``` ### 3. 进行具体操作 以下是一些常见操作的示例: #### 创建索引 ```java import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class CreateIndexExample { public static void main(String[] args) throws IOException { RestHighLevelClient client = ElasticsearchClientConfig.getRestHighLevelClient(); CreateIndexRequest request = new CreateIndexRequest("my_index"); CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); boolean acknowledged = createIndexResponse.isAcknowledged(); System.out.println("Index created: " + acknowledged); client.close(); } } ``` #### 添加文档 ```java import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class AddDocumentExample { public static void main(String[] args) throws IOException { RestHighLevelClient client = ElasticsearchClientConfig.getRestHighLevelClient(); Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("message", "Hello Elasticsearch!"); IndexRequest request = new IndexRequest("my_index") .id("1") .source(jsonMap, XContentType.JSON); IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); System.out.println("Document added: " + indexResponse.getId()); client.close(); } } ``` #### 查询文档 ```java import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class GetDocumentExample { public static void main(String[] args) throws IOException { RestHighLevelClient client = ElasticsearchClientConfig.getRestHighLevelClient(); GetRequest getRequest = new GetRequest("my_index", "1"); GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); if (getResponse.isExists()) { String sourceAsString = getResponse.getSourceAsString(); System.out.println("Document content: " + sourceAsString); } else { System.out.println("Document not found"); } client.close(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值