Java API之增刪改操作
1、項目搭建
Elasticsearch 軟件是由 Java 語言開發的,所以也可以通過 Java API 的方式對 Elasticsearch服務進行訪問。
先 IDEA 開發工具中創建簡單的 java se Maven 項目(模塊也可),如下:

修改 pom 文件,增加 Maven 依賴關系如下:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.8.0</version> </dependency> <!-- elasticsearch 的客戶端 --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.8.0</version> </dependency>
<!-- elasticsearch 依賴 2.x 的 log4j --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency> </dependencies>
2、Elasticsearch 客戶端對象
代碼如下:
import java.io.IOException; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; public class HelloElasticsearch { public static void main(String[] args) throws IOException { // 創建客戶端對象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))); // ... System.out.println("ES客戶端對象:" + client); // 關閉客戶端連接 client.close(); } }
響應如下:

3、索引操作
3.1、創建索引
package org.example; import org.apache.http.HttpHost; 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.RestClient; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class CreateIndex { public static void main(String[] args) throws IOException { // 創建客戶端對象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); // 創建索引 - 請求對象 CreateIndexRequest request = new CreateIndexRequest("user2"); // 發送請求,獲取響應 CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); boolean acknowledged = response.isAcknowledged(); // 響應狀態 System.out.println("操作狀態 = " + acknowledged); // 關閉客戶端連接 client.close(); } }
響應如下:

再次查看索引可以看到已新建了該索引。
3.2、查詢索引
import org.apache.http.HttpHost; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import java.io.IOException; public class SearchIndex { public static void main(String[] args) throws IOException { // 創建客戶端對象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); // 查詢索引 - 請求對象 GetIndexRequest request = new GetIndexRequest("user2"); // 發送請求,獲取響應 GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT); System.out.println("aliases:"+response.getAliases()); System.out.println("mappings:"+response.getMappings()); System.out.println("settings:"+response.getSettings()); client.close(); } }
響應如下:

3.3、刪除索引
import org.apache.http.HttpHost; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class DeleteIndex { public static void main(String[] args) throws IOException { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); // 刪除索引 - 請求對象 DeleteIndexRequest request = new DeleteIndexRequest("user2"); // 發送請求,獲取響應 AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT); // 操作結果 System.out.println("操作結果 : " + response.isAcknowledged()); client.close(); } }
響應如下:

4、文檔操作
由于頻繁使用連接 Elasticsearch 和關閉它的代碼,于是先對它進行重構。注意,項目 jdk 需保證在 1.8 或以上才能使用下面的 lambda 語法。
package org.util; import org.elasticsearch.client.RestHighLevelClient; public interface ElasticsearchTask { void doSomething(RestHighLevelClient client) throws Exception; }
package org.util; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; public class ConnectElasticsearch{ public static void connect(ElasticsearchTask task){ // 創建客戶端對象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); try { task.doSomething(client); // 關閉客戶端連接 client.close(); } catch (Exception e) { e.printStackTrace(); } } }
4.1、新增文檔
先創建一個實體類,如下:
package org.entity; public class User { private String name; private Integer age; private String sex; public String getName() { return name; } public void setName(String name){ this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
新增文檔:
package org.example; import com.fasterxml.jackson.databind.ObjectMapper; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.common.xcontent.XContentType; import org.entity.User; import org.util.ConnectElasticsearch; public class InsertDoc { public static void main(String[] args) { ConnectElasticsearch.connect(client -> { // 新增文檔 - 請求對象 IndexRequest request = new IndexRequest(); // 設置索引及唯一性標識 request.index("user").id("1001"); // 創建數據對象 User user = new User(); user.setName("zhangsan"); user.setAge(30); user.setSex("男"); ObjectMapper objectMapper = new ObjectMapper(); String productJson = objectMapper.writeValueAsString(user); // 添加文檔數據,數據格式為 JSON 格式 request.source(productJson, XContentType.JSON); // 客戶端發送請求,獲取響應對象 IndexResponse response = client.index(request, RequestOptions.DEFAULT); //3.打印結果信息 System.out.println("_index:" + response.getIndex()); System.out.println("_id:" + response.getId()); System.out.println("_result:" + response.getResult()); }); } }
輸出如下:

通過查詢文檔也可以查看到已經成功創建該文檔。
4.2、刪除文檔
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.util.ConnectElasticsearch;
public class DeleteDoc {
public static void main(String[] args) {
ConnectElasticsearch.connect(client -> {
//創建請求對象
DeleteRequest request = new DeleteRequest().index("user").id("1001");
//客戶端發送請求,獲取響應對象
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
//打印信息
System.out.println(response.toString());
});
}
}
輸出如下:

執行過后再次查詢會發現已經無法查詢到該文檔。
4.3、修改文檔
下面修改文檔字段值:
import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.common.xcontent.XContentType; import org.util.ConnectElasticsearch; public class UpdateDoc { public static void main(String[] args) { ConnectElasticsearch.connect(client -> { // 修改文檔 - 請求對象 UpdateRequest request = new UpdateRequest(); // 配置修改參數 request.index("user").id("1001"); // 設置請求體,對數據進行修改 request.doc(XContentType.JSON, "sex", "女"); // 客戶端發送請求,獲取響應對象 UpdateResponse response = client.update(request, RequestOptions.DEFAULT); System.out.println("_index:" + response.getIndex()); System.out.println("_id:" + response.getId()); System.out.println("_result:" + response.getResult()); }); } }
輸出如下:

4.4、批量操作
4.4.1、批量新增
import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.common.xcontent.XContentType; import org.util.ConnectElasticsearch; public class BatchInsertDoc { public static void main(String[] args) { ConnectElasticsearch.connect(client -> { //創建批量新增請求對象 BulkRequest request = new BulkRequest(); request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan")); request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi")); request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu")); //客戶端發送請求,獲取響應對象 BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT); //打印結果信息 System.out.println("took:" + responses.getTook()); System.out.println("items:" + responses.getItems()); }); } }
輸出如下:

4.4.2、批量刪除
import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.client.RequestOptions; import org.util.ConnectElasticsearch; public class BatchDeleteDoc { public static void main(String[] args) { ConnectElasticsearch.connect(client -> { //創建批量刪除請求對象 BulkRequest request = new BulkRequest(); request.add(new DeleteRequest().index("user").id("1001")); request.add(new DeleteRequest().index("user").id("1002")); request.add(new DeleteRequest().index("user").id("1003")); //客戶端發送請求,獲取響應對象 BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT); //打印結果信息 System.out.println("took:" + responses.getTook()); System.out.println("items:" + responses.getItems()); }); } }
輸出如下:


浙公網安備 33010602011771號