java操作elasticsearch索引库的方法 本质就是java发送http请求给ES
其中的Java Rest Client又包括两种:
- Java Low Level Rest Client
- Java High Level Rest Client
我们学习的是Java HighLevel Rest Client客户端API

引入依赖:
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId></dependency>
版本覆盖 当前工程的父依赖为Springboot依赖 里面已经定义了版本 所以要在当前依赖 自定义版本
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.10.1</elasticsearch.version>
</properties>
这样能救能直接使用索引库的连接功能
在test类中测试 在每个测试之前启动的方法 和之后的启动方法
启动前的方法:创建一个rest高级连接 参数为连接bulid构造器 用RestClient.builder方法创建此构造器 参数为httphost地址 用HttpHost.create方法创建地址 参数为ES的地址和端口
启动后方法:关闭连接
public class HotelIndexTest {
private RestHighLevelClient client;
@BeforeEach
void setUp() {
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.94.129:9200")
));
}
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
@Test
public void xxxx(){
}
}
创建索引库请求:put /itheima 创建索引库和约束是同是进行的
新建一个创建索引库请求对象 参数为索引库名
请求对象的source方法 为请求对象添加请求语句 和语句的 格式
使用连接的indices()方法 获取所有索引库所有的操作方法 在使用create方法 参数为请求对象 和默认请求选项
@Test
void createHotelIndex() throws IOException {
// 1.创建Request对象
CreateIndexRequest request = new CreateIndexRequest("hotel");
// 2.准备请求的参数:DSL语句
request.source(MAPPING_TEMPLATE, XContentType.JSON);
// 3.发送请求
client.indices().create(request, RequestOptions.DEFAULT);
}
删除数据库:delete /itheima
创建一个删除索引库的请求对象 参数为库名
使用连接的indices()方法 获取所有的索引库对象 在使用create方法 参数为请求对象 和默认请求选项
@Test
void testDeleteHotelIndex() throws IOException {
// 1.创建Request对象
DeleteIndexRequest request = new DeleteIndexRequest("hotel");
// 2.发送请求
client.indices().delete(request, RequestOptions.DEFAULT);
}
判断索引库是否存在:get/itheima
创建一个获取索引库的请求对象 参数为库名
使用连接的indices()方法 获取所有的索引库对象 在使用create方法 参数为请求对象 和默认请求选项
返回值为Boolean类型
@Test
void testExistsHotelIndex() throws IOException {
// 1.创建Request对象
GetIndexRequest request = new GetIndexRequest("hotel");
// 2.发送请求
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
// 3.输出
System.err.println(exists ? "索引库已经存在!" : "索引库不存在!");
}
