1.java 操作es ,创建user_new 索引,查看索引,删除索引 2.java 操作es,插入数
时间: 2023-09-17 22:00:49 浏览: 88
1. 使用Java操作ES创建user_new索引,查看索引和删除索引的步骤如下:
创建user_new索引:
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
CreateIndexRequest createRequest = new CreateIndexRequest("user_new");
CreateIndexResponse createResponse = client.indices().create(createRequest, RequestOptions.DEFAULT);
boolean acknowledged = createResponse.isAcknowledged();
if (acknowledged) {
System.out.println("user_new索引创建成功");
} else {
System.out.println("user_new索引创建失败");
}
client.close();
```
查看索引:
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
GetIndexRequest getRequest = new GetIndexRequest("user_new");
boolean exists = client.indices().exists(getRequest, RequestOptions.DEFAULT);
if (exists) {
System.out.println("user_new索引存在");
} else {
System.out.println("user_new索引不存在");
}
client.close();
```
删除索引:
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
DeleteIndexRequest deleteRequest = new DeleteIndexRequest("user_new");
AcknowledgedResponse deleteResponse = client.indices().delete(deleteRequest, RequestOptions.DEFAULT);
boolean acknowledged = deleteResponse.isAcknowledged();
if (acknowledged) {
System.out.println("user_new索引删除成功");
} else {
System.out.println("user_new索引删除失败");
}
client.close();
```
2. 使用Java操作ES插入数据的步骤如下:
插入数据:
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
IndexRequest request = new IndexRequest("user_new");
request.id("1");
String jsonString = "{\"name\":\"John Doe\",\"age\":25}";
request.source(jsonString, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println("插入数据成功,索引名称:" + response.getIndex() + ",id:" + response.getId());
client.close();
```
以上代码是向user_new索引插入一个id为1的文档,文档内容为{"name":"John Doe","age":25}。使用Java的RestHighLevelClient发送IndexRequest请求,并将待插入的文档以JSON格式传入请求的source,然后通过client.index方法执行插入操作。接收到的IndexResponse对象可以获取插入的文档的索引名称和id。
阅读全文