在 Java 中封装 ElasticSearch(ES)数据库操作(ES版本之间变动挺大的,别轻易换版本),可以使得与 ES 的交互更加简洁和易于维护。通过封装常见的操作,如插入文档、查询、更新和删除等,我们可以创建一个高效的工具类来简化开发流程。以下是一个简单的 ES 操作工具类的封装示例。
1. 添加 Elasticsearch 依赖
首先,确保在项目中添加了 Elasticsearch 的 Java 客户端依赖。以下是 Maven 依赖配置:
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.10.0</version> <!-- 请根据版本需求修改 -->
</dependency>
2. Elasticsearch 操作封装工具类
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.search.query.QuerySearchResponse;
import org.elasticsearch.search.query.SearchRequest;
import org.elasticsearch.search.query.SearchResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;public class ElasticSearchUtil {private static final String ES_HOST = "localhost"; // ES 集群地址private static final int ES_PORT = 9200; // 默认端口号private static RestHighLevelClient client;// 静态初始化:创建 Elasticsearch 客户端static {client = new RestHighLevelClient(RestClient.builder(new HttpHost(ES_HOST, ES_PORT, "http")));}// 获取 Elasticsearch 客户端public static RestHighLevelClient getClient() {return client;}// 关闭 Elasticsearch 客户端连接public static void close() throws IOException {if (client != null) {client.close();}}// 插入文档public static void indexDocument(String index, String id, String jsonData) {IndexRequest request = new IndexRequest(index).id(id).source(jsonData);try {client.index(request, RequestOptions.DEFAULT);System.out.println("Document indexed successfully.");} catch (IOException e) {System.err.println("Failed to index document: " + e.getMessage());}}// 更新文档public static void updateDocument(String index, String id, String jsonData) {UpdateRequest request = new UpdateRequest(index, id).doc(jsonData);try {client.update(request, RequestOptions.DEFAULT);System.out.println("Document updated successfully.");} catch (IOException e) {System.err.println("Failed to update document: " + e.getMessage());}}// 查询文档public static List<String> searchDocuments(String index, String field, String value) {SearchRequest searchRequest = new SearchRequest(index);SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchQuery(field, value));searchRequest.source(sourceBuilder);List<String> results = new ArrayList<>();try {SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);SearchHit[] hits = searchResponse.getHits().getHits();for (SearchHit hit : hits) {results.add(hit.getSourceAsString());}} catch (IOException e) {System.err.println("Failed to search documents: " + e.getMessage());}return results;}// 删除文档public static void deleteDocument(String index, String id) {try {client.delete(new DeleteRequest(index, id), RequestOptions.DEFAULT);System.out.println("Document deleted successfully.");} catch (IOException e) {System.err.println("Failed to delete document: " + e.getMessage());}}public static void main(String[] args) throws IOException {// 插入文档示例String jsonData = "{\"name\":\"John\",\"age\":30}";indexDocument("users", "1", jsonData);// 查询文档示例List<String> documents = searchDocuments("users", "name", "John");for (String doc : documents) {System.out.println(doc);}// 更新文档示例String updatedData = "{\"name\":\"John\",\"age\":31}";updateDocument("users", "1", updatedData);// 删除文档示例deleteDocument("users", "1");// 关闭 Elasticsearch 客户端close();}
}
3. 功能说明
1. 客户端初始化与关闭
RestHighLevelClient
用于与 Elasticsearch 进行交互。client = new RestHighLevelClient(...)
:初始化客户端连接。client.close()
:关闭客户端连接,释放资源。
2. 插入文档:
public static void indexDocument(String index, String id, String jsonData) {IndexRequest request = new IndexRequest(index).id(id).source(jsonData);try {client.index(request, RequestOptions.DEFAULT);System.out.println("Document indexed successfully.");} catch (IOException e) {System.err.println("Failed to index document: " + e.getMessage());}
}
IndexRequest
用于向指定索引中插入文档。source(jsonData)
:文档内容以 JSON 格式传入。
3. 更新文档:
public static void updateDocument(String index, String id, String jsonData) {UpdateRequest request = new UpdateRequest(index, id).doc(jsonData);try {client.update(request, RequestOptions.DEFAULT);System.out.println("Document updated successfully.");} catch (IOException e) {System.err.println("Failed to update document: " + e.getMessage());}
}
UpdateRequest
用于更新指定 ID 的文档。
4. 查询文档:
public static List<String> searchDocuments(String index, String field, String value) {SearchRequest searchRequest = new SearchRequest(index);SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchQuery(field, value));searchRequest.source(sourceBuilder);List<String> results = new ArrayList<>();try {SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);SearchHit[] hits = searchResponse.getHits().getHits();for (SearchHit hit : hits) {results.add(hit.getSourceAsString());}} catch (IOException e) {System.err.println("Failed to search documents: " + e.getMessage());}return results;
}
SearchRequest
和SearchSourceBuilder
用于构建查询请求。QueryBuilders.matchQuery()
用于构建匹配查询。
5. 删除文档:
public static void deleteDocument(String index, String id) {try {client.delete(new DeleteRequest(index, id), RequestOptions.DEFAULT);System.out.println("Document deleted successfully.");} catch (IOException e) {System.err.println("Failed to delete document: " + e.getMessage());}
}
DeleteRequest
用于删除指定 ID 的文档。
4. 如何使用该工具类
- 插入文档:使用
indexDocument()
方法,将 JSON 数据插入指定的 Elasticsearch 索引中。 - 更新文档:使用
updateDocument()
方法更新指定 ID 的文档。 - 查询文档:使用
searchDocuments()
方法,根据字段值进行查询。 - 删除文档:使用
deleteDocument()
方法删除指定 ID 的文档。
5. 改进与扩展
- 分页查询:可以扩展查询功能,支持分页,避免返回过多数据。
- 错误处理:根据实际需要加强错误处理逻辑,捕获并处理可能的异常。
- 连接池支持:为了提高性能,建议使用连接池来管理 Elasticsearch 客户端。
通过这样的封装工具类,你可以轻松地执行 Elasticsearch 的常见操作,而不需要每次都编写繁琐的客户端代码。