🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
```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(); } } ```