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 和關閉它的程式碼,於是先對它進行重構。
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.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.3、查詢文件
4.4、刪除文件