RestHighLevelClient 创建索引
时间: 2023-11-08 12:59:01 浏览: 95
ElasticSearch RestHighLevelClient 关于索引库、文档的基础操作
使用 RestHighLevelClient 创建 Elasticsearch 索引的步骤如下:
1. 创建 RestHighLevelClient 对象,连接 Elasticsearch 集群。
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
```
2. 准备索引的配置和映射信息。例如,创建一个名为 "my-index" 的索引,包含一个名为 "my-field" 的文本字段。
```java
IndexSettings settings = new IndexSettings();
settings.setNumberOfShards(1);
settings.setNumberOfReplicas(0);
IndexMapping mapping = new IndexMapping();
mapping.addField(new TextField("my-field"));
```
3. 创建 CreateIndexRequest 对象,并设置索引的名称、配置和映射信息。
```java
CreateIndexRequest request = new CreateIndexRequest("my-index");
request.settings(settings);
request.mapping(mapping);
```
4. 调用 RestHighLevelClient 的 indices() 方法执行创建索引的操作。
```java
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
```
完整代码如下:
```java
// 创建 RestHighLevelClient 对象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
try {
// 准备索引的配置和映射信息
IndexSettings settings = new IndexSettings();
settings.setNumberOfShards(1);
settings.setNumberOfReplicas(0);
IndexMapping mapping = new IndexMapping();
mapping.addField(new TextField("my-field"));
// 创建 CreateIndexRequest 对象,并设置索引的名称、配置和映射信息
CreateIndexRequest request = new CreateIndexRequest("my-index");
request.settings(settings);
request.mapping(mapping);
// 调用 RestHighLevelClient 的 indices() 方法执行创建索引的操作
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
// 处理创建索引的响应结果
boolean acknowledged = response.isAcknowledged();
boolean shardsAcknowledged = response.isShardsAcknowledged();
} catch (IOException e) {
// 处理异常
} finally {
// 关闭 RestHighLevelClient 对象
try {
client.close();
} catch (IOException e) {
// 处理异常
}
}
```
阅读全文