Java操作ElasticSearch的實(shí)例詳解
簡(jiǎn)介
Elasticsearch 是一個(gè)分布式的搜索和分析引擎,廣泛用于全文搜索、日志分析等場(chǎng)景。本文將介紹如何在 Java 應(yīng)用中使用 Elasticsearch 客戶端來(lái)連接和操作 Elasticsearch 集群。
環(huán)境準(zhǔn)備
1. 安裝 Elasticsearch
首先,確保你的環(huán)境中已經(jīng)安裝了 Elasticsearch??梢詮???Elasticsearch 官方網(wǎng)站??下載最新版本的 Elasticsearch,并按照官方文檔進(jìn)行安裝和啟動(dòng)。
2. 添加依賴
在你的 Java 項(xiàng)目中,需要添加 Elasticsearch 的客戶端依賴。如果你使用的是 Maven,可以在 ??pom.xml?? 文件中添加以下依賴:
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.10.2</version> </dependency>
連接 Elasticsearch
1. 創(chuàng)建客戶端
使用 ??RestHighLevelClient?? 類(lèi)來(lái)創(chuàng)建一個(gè)連接到 Elasticsearch 集群的客戶端。
import org.elasticsearch.client.RestHighLevelClient; import org.apache.http.HttpHost; public class ElasticsearchClient { public static RestHighLevelClient createClient() { return new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http") ) ); } }
2. 關(guān)閉客戶端
在完成所有操作后,記得關(guān)閉客戶端以釋放資源。
try { client.close(); } catch (IOException e) { e.printStackTrace(); }
基本操作
1. 創(chuàng)建索引
創(chuàng)建一個(gè)新的索引,并指定一些設(shè)置和映射。
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.common.xcontent.XContentType; public class IndexOperations { public static void createIndex(RestHighLevelClient client) throws IOException { CreateIndexRequest request = new CreateIndexRequest("test_index"); request.mapping("{\n" + " \"properties\": {\n" + " \"title\": {\n" + " \"type\": \"text\"\n" + " },\n" + " \"content\": {\n" + " \"type\": \"text\"\n" + " }\n" + " }\n" + "}", XContentType.JSON); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); System.out.println("Index created: " + response.isAcknowledged()); } }
2. 插入數(shù)據(jù)
向索引中插入一條文檔。
import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.common.xcontent.XContentType; public class DocumentOperations { public static void indexDocument(RestHighLevelClient client) throws IOException { String jsonString = "{" + "\"title\":\"Elasticsearch基礎(chǔ)教程\"," + "\"content\":\"Elasticsearch是一個(gè)分布式搜索和分析引擎\"}"; IndexRequest request = new IndexRequest("test_index").source(jsonString, XContentType.JSON); IndexResponse response = client.index(request, RequestOptions.DEFAULT); System.out.println("Document indexed with ID: " + response.getId()); } }
3. 查詢數(shù)據(jù)
從索引中查詢文檔。
import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; public class SearchOperations { public static void getDocument(RestHighLevelClient client) throws IOException { GetRequest request = new GetRequest("test_index", "1"); GetResponse response = client.get(request, RequestOptions.DEFAULT); if (response.isExists()) { System.out.println("Document found: " + response.getSourceAsString()); } else { System.out.println("Document not found."); } } }
通過(guò)上述步驟,你可以在 Java 應(yīng)用中輕松地連接和操作 Elasticsearch 集群。本文介紹了如何創(chuàng)建客戶端、創(chuàng)建索引、插入文檔和查詢文檔。這些基本操作為更復(fù)雜的使用場(chǎng)景奠定了基礎(chǔ)。
以上就是使用 Java 操作 Elasticsearch 的一個(gè)簡(jiǎn)單示例。希望對(duì)你有幫助!當(dāng)然可以!Elasticsearch 是一個(gè)分布式的搜索和分析引擎,廣泛用于全文搜索、日志分析、實(shí)時(shí)應(yīng)用監(jiān)控等場(chǎng)景。
下面是一個(gè)使用 Java 操作 Elasticsearch 的示例代碼,包括連接到 ES 集群、創(chuàng)建索引、插入文檔、查詢文檔等基本操作。
環(huán)境準(zhǔn)備
添加依賴:在你的 Maven 項(xiàng)目的 ??pom.xml?? 文件中添加 Elasticsearch 客戶端依賴。
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.10.2</version> </dependency>
配置 Elasticsearch:確保你有一個(gè)運(yùn)行中的 Elasticsearch 實(shí)例。你可以使用 Docker 快速啟動(dòng)一個(gè):
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.10.2
示例代碼
以下是一個(gè)完整的 Java 示例代碼,展示了如何連接到 Elasticsearch 集群、創(chuàng)建索引、插入文檔和查詢文檔。
import org.apache.http.HttpHost; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ElasticsearchExample { public static void main(String[] args) { // 創(chuàng)建 RestHighLevelClient 客戶端 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http") ) ); try { // 創(chuàng)建索引 createIndex(client); // 插入文檔 insertDocument(client); // 查詢文檔 searchDocument(client); } catch (IOException e) { e.printStackTrace(); } finally { // 關(guān)閉客戶端 try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void createIndex(RestHighLevelClient client) throws IOException { // 創(chuàng)建索引請(qǐng)求 Map<String, Object> mappings = new HashMap<>(); mappings.put("properties", Map.of( "title", Map.of("type", "text"), "content", Map.of("type", "text") )); String mappingJson = XContentType.JSON.toString(mappings); IndexRequest indexRequest = new IndexRequest("my_index") .source(mappingJson, XContentType.JSON); // 執(zhí)行請(qǐng)求 IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); System.out.println("Index created: " + indexResponse.getResult()); } private static void insertDocument(RestHighLevelClient client) throws IOException { // 創(chuàng)建文檔 Map<String, Object> document = new HashMap<>(); document.put("title", "Elasticsearch Example"); document.put("content", "This is an example of using Elasticsearch with Java."); // 創(chuàng)建索引請(qǐng)求 IndexRequest indexRequest = new IndexRequest("my_index") .id("1") .source(document); // 執(zhí)行請(qǐng)求 IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); System.out.println("Document inserted: " + indexResponse.getResult()); } private static void searchDocument(RestHighLevelClient client) throws IOException { // 創(chuàng)建搜索請(qǐng)求 SearchRequest searchRequest = new SearchRequest("my_index"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("title", "Elasticsearch")); searchRequest.source(searchSourceBuilder); // 執(zhí)行請(qǐng)求 SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); // 處理響應(yīng) for (SearchHit hit : searchResponse.getHits().getHits()) { System.out.println("Document found: " + hit.getSourceAsString()); } } }
代碼說(shuō)明
- 創(chuàng)建客戶端:使用 ??RestHighLevelClient?? 連接到 Elasticsearch 集群。
- 創(chuàng)建索引:定義索引的映射并創(chuàng)建索引。
- 插入文檔:創(chuàng)建一個(gè)文檔并將其插入到指定的索引中。
- 查詢文檔:使用匹配查詢(??matchQuery??)來(lái)搜索包含特定關(guān)鍵字的文檔。
運(yùn)行代碼
確保你的 Elasticsearch 實(shí)例正在運(yùn)行,然后運(yùn)行上述 Java 程序。你應(yīng)該會(huì)看到索引創(chuàng)建、文檔插入和查詢結(jié)果的輸出。
希望這個(gè)示例對(duì)你有幫助!如果有任何問(wèn)題或需要進(jìn)一步的幫助,請(qǐng)隨時(shí)告訴我。當(dāng)然可以!Elasticsearch 是一個(gè)分布式的搜索和分析引擎,廣泛用于全文搜索、日志分析、實(shí)時(shí)應(yīng)用監(jiān)控等場(chǎng)景。在 Java 應(yīng)用中操作 Elasticsearch 通常需要使用官方提供的客戶端庫(kù),如 ??elasticsearch-rest-high-level-client??(現(xiàn)已停止更新)或更現(xiàn)代的 ??elasticsearch-java?? 客戶端。
以下是一個(gè)詳細(xì)的步驟和示例代碼,展示如何在 Java 中使用 ??elasticsearch-java?? 客戶端來(lái)操作 Elasticsearch 實(shí)例:
1. 添加依賴
首先,在你的 ??pom.xml?? 文件中添加 Elasticsearch 客戶端的依賴。這里以 Maven 為例:
<dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.6.2</version> <!-- 請(qǐng)根據(jù)實(shí)際情況選擇合適的版本 --> </dependency>
2. 創(chuàng)建客戶端
創(chuàng)建一個(gè) Elasticsearch 客戶端實(shí)例,用于與 Elasticsearch 集群進(jìn)行通信。
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; public class ElasticsearchClientExample { public static ElasticsearchClient createClient() { // 創(chuàng)建 Rest 客戶端 RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200, "http") ).build(); // 創(chuàng)建 Elasticsearch 客戶端 ElasticsearchTransport transport = new RestClientTransport( restClient, new JacksonJsonpMapper() ); return new ElasticsearchClient(transport); } }
3. 索引文檔
接下來(lái),我們演示如何索引(插入)一個(gè)文檔到 Elasticsearch 中。
import co.elastic.clients.elasticsearch.core.IndexResponse; import co.elastic.clients.elasticsearch.core.IndexRequest; import co.elastic.clients.elasticsearch.core.IndexResponse.Result; import com.fasterxml.jackson.databind.ObjectMapper; public class IndexDocumentExample { public static void main(String[] args) throws Exception { ElasticsearchClient client = ElasticsearchClientExample.createClient(); // 創(chuàng)建一個(gè)文檔對(duì)象 MyDocument document = new MyDocument(); document.setId(1); document.setTitle("Elasticsearch Java Client Example"); document.setContent("This is an example of using the Elasticsearch Java client."); // 使用 ObjectMapper 將對(duì)象轉(zhuǎn)換為 JSON 字符串 ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(document); // 創(chuàng)建索引請(qǐng)求 IndexRequest<MyDocument> request = new IndexRequest.Builder<MyDocument>() .index("my_index") .id(String.valueOf(document.getId())) .document(document) .build(); // 執(zhí)行索引請(qǐng)求 IndexResponse response = client.index(request); // 檢查響應(yīng)結(jié)果 if (response.result() == Result.Created) { System.out.println("Document indexed successfully."); } else { System.out.println("Failed to index document."); } // 關(guān)閉客戶端 client.close(); } } class MyDocument { private int id; private String title; private String content; // Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
4. 查詢文檔
接下來(lái),我們演示如何查詢 Elasticsearch 中的文檔。
import co.elastic.clients.elasticsearch.core.SearchRequest; import co.elastic.clients.elasticsearch.core.SearchResponse; import co.elastic.clients.elasticsearch.core.search.Hit; public class SearchDocumentExample { public static void main(String[] args) throws Exception { ElasticsearchClient client = ElasticsearchClientExample.createClient(); // 創(chuàng)建查詢請(qǐng)求 SearchRequest request = new SearchRequest.Builder() .index("my_index") .query(q -> q.match(m -> m.field("title").query("Elasticsearch"))) .build(); // 執(zhí)行查詢請(qǐng)求 SearchResponse<MyDocument> response = client.search(request, MyDocument.class); // 處理查詢結(jié)果 for (Hit<MyDocument> hit : response.hits().hits()) { MyDocument document = hit.source(); System.out.println("Found document: " + document.getTitle()); } // 關(guān)閉客戶端 client.close(); } }
5. 刪除文檔
最后,我們演示如何刪除 Elasticsearch 中的文檔。
import co.elastic.clients.elasticsearch.core.DeleteRequest; import co.elastic.clients.elasticsearch.core.DeleteResponse; import co.elastic.clients.elasticsearch.core.DeleteResponse.Result; public class DeleteDocumentExample { public static void main(String[] args) throws Exception { ElasticsearchClient client = ElasticsearchClientExample.createClient(); // 創(chuàng)建刪除請(qǐng)求 DeleteRequest request = new DeleteRequest.Builder() .index("my_index") .id("1") .build(); // 執(zhí)行刪除請(qǐng)求 DeleteResponse response = client.delete(request); // 檢查響應(yīng)結(jié)果 if (response.result() == Result.Deleted) { System.out.println("Document deleted successfully."); } else { System.out.println("Failed to delete document."); } // 關(guān)閉客戶端 client.close(); } }
總結(jié)
本文代碼展示了如何在 Java 中使用 ??elasticsearch-java?? 客戶端進(jìn)行基本的 CRUD 操作。你可以根據(jù)實(shí)際需求擴(kuò)展這些示例,例如處理更復(fù)雜的查詢、批量操作等
以上就是Java操作ElasticSearch的實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于Java操作ElasticSearch的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
新浪開(kāi)源輕量級(jí)分布式RPC框架motan簡(jiǎn)單示例解析
這篇文章主要為大家介紹了新浪開(kāi)源輕量級(jí)分布式RPC框架motan的簡(jiǎn)單示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03Java服務(wù)端架構(gòu)之微服務(wù)與單體服務(wù)的權(quán)衡方式
本文比較了Java微服務(wù)與單體服務(wù)的優(yōu)缺點(diǎn),并提供了相應(yīng)的示例代碼,微服務(wù)架構(gòu)具有可擴(kuò)展性、技術(shù)多樣性等優(yōu)勢(shì),但復(fù)雜性和網(wǎng)絡(luò)延遲是缺點(diǎn),單體服務(wù)架構(gòu)簡(jiǎn)單易部署,但擴(kuò)展性差,選擇哪種架構(gòu)應(yīng)根據(jù)項(xiàng)目需求和團(tuán)隊(duì)能力2025-03-03springmvc @ResponseStatus和ResponseEntity的使用
這篇文章主要介紹了springmvc @ResponseStatus和ResponseEntity的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07spring中自動(dòng)注入注解的實(shí)現(xiàn)方式
在Spring框架中,AutowiredAnnotationBeanPostProcessor負(fù)責(zé)處理@Autowired和@Value注解,實(shí)現(xiàn)依賴注入,首先通過(guò)TypeMappedAnnotations獲取注解,并根據(jù)注解屬性構(gòu)建InjectionMetadata,存入緩存2024-09-09SpringCloud的Gateway網(wǎng)關(guān)詳解
這篇文章主要介紹了SpringCloud的Gateway網(wǎng)關(guān)詳解,Gateway 是 Spring Cloud 官方推出的一個(gè)基于 Spring 5、Spring Boot 2 和 Project Reactor 的 API 網(wǎng)關(guān)實(shí)現(xiàn),本文將介紹 Spring Cloud Gateway 的基本概念、核心組件以及如何配置和使用它,需要的朋友可以參考下2023-09-09Java中Lombok的@Builder注解注意事項(xiàng)
這篇文章主要介紹了Java中Lombok的@Builder注解注意事項(xiàng),使用Lombok也會(huì)造成很多問(wèn)題,尤其@Builder 有個(gè)很大的坑,已經(jīng)見(jiàn)過(guò)好幾次由于使用@Builder注解導(dǎo)致默認(rèn)值失效的問(wèn)題,如果測(cè)試時(shí)沒(méi)有在意這個(gè)問(wèn)題,就很容易引發(fā)線上問(wèn)題,需要的朋友可以參考下2023-12-12java把excel內(nèi)容上傳到mysql實(shí)例代碼
這篇文章主要介紹了java把excel內(nèi)容上傳到mysql實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01maven在settings.xml和pom.xml中指定jdk版本編譯的方法
在開(kāi)發(fā)Java應(yīng)用時(shí),通常需要指定要使用的Java版本,下面這篇文章主要給大家介紹了關(guān)于maven在settings.xm和pom.xml中指定jdk版本編譯的方法,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-05-05