ES的Java API
- Transport Client:TransportClient不推薦使用,而推薦使用Java High Level REST Client,並將在Elasticsearch 8.0中刪除。
- JAVA REST Client
- Java Low Level REST Client:低級別的REST客戶端,通過http與集群交互,用戶需自己編組請求JSON串,及解析響應JSON串。兼容所有ES版本
- Java High Level REST Client:高級別的REST客戶端,基於低級別的REST客戶端,增加了編組請求JSON串、解析響應JSON串等相關api。使用的版本需要保持和ES服務端的版本一致,否則會有版本問題。同時要求JDK版本最少為1.8
基於SpringBoot和Java High Level REST Client實現CRUD
添加依賴
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
<!-- es版本需要和安裝es版本一致-->
<es.version>7.12.1</es.version>
<fastjson.version>1.2.70</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--es -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--測試-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
添加配置類
@Configuration
public class ElasticSearchClientConfig {
// 相較xml<bean id="方法名" class="返回值">
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.232.128", 9200, "http")));
}
}
新增實體類
//此處需要繼承Serializable,不然在實體類轉json會失敗
@Data
@AllArgsConstructor
public class User implements Serializable {
private String name;
private int age;
}
索引的CURD
package com.example.demo.test;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
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.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;
/**
*
* @version 1.0
* @ClassName IndexTest
* @Description 對索引的CURD client.indices():獲取關於indexClient,來得到對index操作的權力
* @date 2021/5/27 14:33
*/
@SpringBootTest
public class IndexTest {
@Autowired
@Qualifier("restHighLevelClient") //指定注入的bean
private RestHighLevelClient restHighLevelClient;
/**
* 創建索引,重復創建會拋出相關異常
* */
@Test
public void contextLoadTest() throws IOException {
CreateIndexRequest my_index = new CreateIndexRequest("my_index");
System.out.println(restHighLevelClient);
CreateIndexResponse indexResponse = restHighLevelClient.indices().create(my_index, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
}
/**
* 查詢索引是否存在
*/
@Test
public void existRequest() throws IOException {
GetIndexRequest my_index = new GetIndexRequest("my_index");
System.out.println(my_index.toString());
boolean exists = restHighLevelClient.indices().exists(my_index, RequestOptions.DEFAULT);
System.out.println(exists);
}
/**
*
* 刪除索引,索引不存在會拋出相關異常
* */
@Test
public void deleteRequest() throws IOException {
DeleteIndexRequest my_index = new DeleteIndexRequest("my_index");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(my_index, RequestOptions.DEFAULT);
System.out.println(delete.toString());
}
}
DOC的CRUD
package com.example.demo.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
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.common.xcontent.XContentType;
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;
/**
*
* @version 1.0
* @ClassName DocTest
* @Description 對文檔的CRUD
* @date 2021/5/27 14:52
*/
@SpringBootTest
public class DocTest {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient restHighLevelClient;
/**
* 添加doc,當指定id的數據存在時,則會變成全量update,卻字段會導致數據丟失
*/
@Test
public void addDocTest() throws IOException {
//創建請求連接
IndexRequest request = new IndexRequest("my_index");
//創建要添加的信息
User user = new User("孫悟空", 700);
//通過客戶端對基本信息進行添加
//自定義id
request.id("1");
//請求超時時間
request.timeout("10s");
//將請求的數據放到request中,並指定消息類型為json
request.source(JSON.toJSONString(user), XContentType.JSON);
//通過客戶端傳遞請求
IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(index.toString());
System.out.println(index.status());
}
/**
* 修改doc,(上面的創建其實是可以智能的在有數據的情況下是更新數據,但是是全量的更新,缺字段會導致數據丟失)
*/
@Test
public void updateDoc() throws IOException {
//修改指定id的doc數據,此時如果id不存在會拋出未找到的異常
UpdateRequest updateRequest = new UpdateRequest("my_index", "1");
updateRequest.timeout("5s");
User user = new User("豬八戒", 300);
updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
//獲取修改之后的結果
updateRequest.fetchSource(true);
UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update.toString());
System.out.println(update.getIndex());
System.out.println(update.getGetResult());
System.out.println(update.status());
}
/**
* 刪除doc
*
*/
@Test
public void deleteDoc() throws IOException {
//創建刪除請求,指定索引和刪除id
DeleteRequest deleteRequest = new DeleteRequest("my_index", "1");
DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.status());
System.out.println(delete.toString());
}
}