最新版ES8的client API操作 Elasticsearch Java API client 8.0
在Elasticsearch 8.0中,Java API client提供了一系列的方法来操作Elasticsearch。以下是一些基本的操作示例:
- 创建客户端:
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
ElasticsearchClient elasticsearchClient = new ElasticsearchClient(restClient);
- 索引文档:
IndexOperationRequest indexOperationRequest = new IndexOperationRequest.Builder()
.index("indexName")
.id("documentId")
.document(XContentType.JSON, "{ \"field\": \"value\" }")
.build();
elasticsearchClient.index(indexOperationRequest, RequestOptions.DEFAULT);
- 获取文档:
GetRequest getRequest = new GetRequest("indexName", "documentId");
GetResponse getResponse = elasticsearchClient.get(getRequest, RequestOptions.DEFAULT);
- 更新文档:
UpdateRequest updateRequest = new UpdateRequest("indexName", "documentId");
updateRequest.doc(XContentType.JSON, "{ \"field\": \"newValue\" }");
elasticsearchClient.update(updateRequest, RequestOptions.DEFAULT);
- 删除文档:
DeleteRequest deleteRequest = new DeleteRequest("indexName", "documentId");
elasticsearchClient.delete(deleteRequest, RequestOptions.DEFAULT);
- 搜索文档:
SearchRequest searchRequest = new SearchRequest("indexName");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field", "value"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
注意:以上代码仅展示了如何使用Elasticsearch Java API client进行基本操作,实际使用时可能需要处理异常和其他选项。在实际应用中,你可能还需要创建一个ElasticsearchRestClient实例,并使用RequestOptions来配置请求的各种选项。
评论已关闭