基于 SpringBoot 2.7.x 使用最新的 Elasticsearch Java API Client 之 ElasticsearchClient
在SpringBoot 2.7.x中,我们可以使用Elasticsearch的Java API Client进行搜索和操作Elasticsearch。以下是一些示例代码。
- 创建Elasticsearch客户端:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
- 索引文档:
IndexRequest indexRequest = new IndexRequest("posts");
indexRequest.id("1");
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2021-12-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
indexRequest.source(jsonString, XContentType.JSON);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
- 获取文档:
GetRequest getRequest = new GetRequest(
"posts", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
- 更新文档:
UpdateRequest updateRequest = new UpdateRequest("posts", "1");
updateRequest.doc(XContentType.JSON, "message", "updated message");
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
- 删除文档:
DeleteRequest deleteRequest = new DeleteRequest(
"posts", "1");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
- 搜索文档:
SearchRequest searchRequest = new SearchRequest("posts");
searchRequest.source().query(QueryBuilders.matchQuery("message", "trying"));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
- 关闭Elasticsearch客户端:
client.close();
注意:在实际的生产环境中,你需要处理可能发生的异常,并确保在应用程序关闭时关闭Elasticsearch客户端,以释放资源。
以上代码仅供参考,具体使用时需要根据实际的Elasticsearch版本和配置进行调整。
评论已关闭