目录
创建spring boot工程
加入依赖
创建一个配置,获取ES工具类对象。
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ESConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
return client;
}
}
RestHighLevelClient
RestHighLevelClient的API作为ElasticSearch备受推荐的客户端组件,其封装系统操作ES的方法,包括索引结构管理,数据增删改查管理,常用查询方法,并且可以结合原生ES查询原生语法,功能十分强大。
索引管理
创建索引
索引名不能有大写字母
@Test
void createIndex() throws IOException {
/*该类把索引的信息都封装 索引名*/
CreateIndexRequest createIndexRequest = new CreateIndexRequest("ytrtest");
/*创建索引*/ /*索引名*/ /*基本固定写这个*/
CreateIndexResponse r = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
/*此方法查看是否创建成功*/
System.out.println(r.isAcknowledged());
}
删除索引
@Test
void delereIndex() throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("ytrtest");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
判断索引是否存在
@Test
/*判断索引是否存在*/
void judgeIndex() throws IOException {
GetIndexRequest getIndexRequest = new GetIndexRequest("ytrtest");
boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}