ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
```java import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpHost; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import org.junit.Test; import java.io.IOException; @Slf4j public class IndexOperation { /** * 创建索引 */ @Test public void createIndex() throws IOException { //获取elasticsearch客户端 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http")) ); //创建索引,如果索引已经存在则抛出异常 CreateIndexRequest request = new CreateIndexRequest("user"); //发送请求并获取响应 CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); boolean acknowledged = response.isAcknowledged(); //创建结果:true log.info("创建结果:{}", acknowledged); //关闭连接 client.close(); } /** * 查询索引 */ @Test public void getIndex() throws IOException { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http")) ); //查询索引 GetIndexRequest request = new GetIndexRequest("user"); GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT); //size: 1, indices: [user] log.info("size: {}, indices: {}", response.getIndices().length, response.getIndices()); client.close(); } /** * 删除索引 */ @Test public void deleteIndex() throws IOException { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http")) ); //删除索引 DeleteIndexRequest request = new DeleteIndexRequest("user"); //发送请求并获取响应 AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT); //操作结果:true log.info("操作结果:{}", response.isAcknowledged()); //关闭连接 client.close(); } } ```