restHighLevelClient
时间: 2024-06-19 08:02:30 浏览: 116
`RestHighLevelClient`是Elasticsearch提供的Java REST客户端,它提供了一系列API来与Elasticsearch进行交互。使用`RestHighLevelClient`可以执行CRUD操作、执行搜索请求、管理索引和集群等。
以下是使用`RestHighLevelClient`执行CRUD操作的范例(假设已经连接到Elasticsearch):
1. 创建索引
```java
CreateIndexRequest request = new CreateIndexRequest("index_name");
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
```
2. 添加文档
```java
IndexRequest request = new IndexRequest("index_name");
request.id("document_id");
request.source("field1", "value1", "field2", "value2");
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
```
3. 获取文档
```java
GetRequest request = new GetRequest("index_name", "document_id");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
```
4. 更新文档
```java
UpdateRequest request = new UpdateRequest("index_name", "document_id");
request.doc("field1", "new_value1", "field2", "new_value2");
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
```
5. 删除文档
```java
DeleteRequest request = new DeleteRequest("index_name", "document_id");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
```
以下是使用`RestHighLevelClient`执行搜索请求的范例:
```java
SearchRequest request = new SearchRequest("index_name");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery("field1", "value1"));
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
```
以下是使用`RestHighLevelClient`执行管理索引和集群的操作的范例:
1. 删除索引
```java
DeleteIndexRequest request = new DeleteIndexRequest("index_name");
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
```
2. 获取集群信息
```java
ClusterStateRequest request = new ClusterStateRequest();
ClusterStateResponse response = client.cluster().state(request, RequestOptions.DEFAULT);
```
3. 获取节点信息
```java
NodesInfoRequest request = new NodesInfoRequest();
NodesInfoResponse response = client.nodes().info(request, RequestOptions.DEFAULT);
```
阅读全文