1、创建工程、前期准备
目录结构
2、导入依赖
导入elasticsearch
提前导入fastjson、lombok
3、创建并编写配置类
4、创建并编写实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = -3843548915035470817L;
private String name;
private Integer age;
}
5、测试
所有测试均在 SpringbootElasticsearchApplicationTests中编写
注入 RestHighLevelClient
@Autowiredpublic RestHighLevelClient restHighLevelClient;
索引的操作
1、索引的创建
// 测试索引的创建,
Request PUT liuyou_index
@Test
public void testCreateIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("liuyou_index");
CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
// 查看是否创建成功
System.out.println(response);
// 查看返回对象
restHighLevelClient.close();
}
2、索引的获取,并判断其是否存在
// 测试获取索引,并判断其是否存在
@Test
public void testIndexIsExists() throws IOException {
GetIndexRequest request = new GetIndexRequest("index");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists);
// 索引是否存在
restHighLevelClient.close();
}
3、索引的删除
// 测试索引删除
@Test
public void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("liuyou_index");
AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());// 是否删除成功
restHighLevelClient.close();
}