javaAPI操作Elasticsearch
在Java中操作Elasticsearch,你可以使用Elasticsearch的Java API客户端——Elasticsearch-Rest-High-Level-Client
。以下是一些基本操作的示例代码:
- 创建客户端:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
- 索引文档:
IndexRequest request = new IndexRequest("index_name");
request.id("id");
request.source(XContentType.JSON, "field", "value");
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
- 获取文档:
GetRequest getRequest = new GetRequest("index_name", "id");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
- 更新文档:
UpdateRequest updateRequest = new UpdateRequest("index_name", "id");
updateRequest.doc(XContentType.JSON, "field", "new_value");
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
- 删除文档:
DeleteRequest deleteRequest = new DeleteRequest("index_name", "id");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
- 搜索文档:
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field", "value"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
- 关闭客户端:
client.close();
确保你的项目中包含了Elasticsearch的依赖。如果你使用Maven,可以添加如下依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.0</version>
</dependency>
请根据你的Elasticsearch版本选择合适的客户端版本。
评论已关闭