Elasticsearch Java 客户端:完全指南
Elasticsearch 是一个基于 Lucene 的强大分布式搜索和分析引擎。为了从 Java 应用程序与之交互,官方提供了一个客户端,它提供了用于索引、搜索和数据管理的便捷 API。本文将详细介绍 Elasticsearch Java 客户端的安装、配置和主要功能,并提供实用的代码示例。
什么是 Elasticsearch Java 客户端?
Elasticsearch Java 客户端是一个官方库,旨在从 Java 应用程序与 Elasticsearch 集群进行交互。它支持两种主要方式:
- 低级 REST 客户端 — 直接使用 HTTP 请求的低级客户端。提供完全控制,但需要手动构建 JSON。
- 高级 REST 客户端 — 高级封装,为常见操作(索引、搜索、更新)提供面向对象的 API。推荐用于大多数项目。
从 Elasticsearch 7.0 开始,建议使用高级 REST 客户端,因为它更方便、更安全。
安装与连接
要将客户端添加到 Java (Maven) 项目,请在 pom.xml 文件中添加以下依赖:
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.17.0</version></dependency>如果您使用 Gradle,请添加以下行:
implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.17.0'添加依赖后,创建客户端实例:
import org.elasticsearch.client.RestHighLevelClient;import org.elasticsearch.client.RestClient;import org.apache.http.HttpHost;
public class ElasticsearchClientExample { public static void main(String[] args) { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http")) ); // 您的 Elasticsearch 操作代码 try { client.close(); } catch (IOException e) { e.printStackTrace(); } }}客户端基本操作
创建索引
在开始处理数据之前,需要创建一个索引(类似于 SQL 中的数据库)。示例:
import org.elasticsearch.client.indices.CreateIndexRequest;import org.elasticsearch.client.indices.CreateIndexResponse;import org.elasticsearch.client.RequestOptions;
public void createIndex(RestHighLevelClient client, String indexName) throws IOException { CreateIndexRequest request = new CreateIndexRequest(indexName); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); System.out.println("索引已创建: " + response.isAcknowledged());}索引文档
Elasticsearch 中的文档是 JSON 对象。要添加文档,请使用 IndexRequest:
import org.elasticsearch.action.index.IndexRequest;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.common.xcontent.XContentType;import java.util.HashMap;import java.util.Map;
public void indexDocument(RestHighLevelClient client, String indexName) throws IOException { Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("title", "Elasticsearch Java 客户端"); jsonMap.put("content", "从 Java 使用 Elasticsearch 的详细说明。"); jsonMap.put("views", 150);
IndexRequest request = new IndexRequest(indexName) .id("1") .source(jsonMap);
IndexResponse respon