1初始化,构建RestHighLevelClient,绑定本地的的地址
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")));
return client;
}
}
//创建索引
@Test
void contextLoads() throws IOException {
//创建索引请求
CreateIndexRequest request = new CreateIndexRequest("pzdb");
//执行请求
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
//获取索引
@Test
void inde() throws IOException {
//判断索引是否存在
GetIndexRequest getRequest = new GetIndexRequest("pzdb");
boolean exists = restHighLevelClient.indices().exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
//删除索引请求
@Test
void deleteIndex() throws IOException {
DeleteIndexRequest delete = new DeleteIndexRequest("pzdb");
AcknowledgedResponse delete1 = restHighLevelClient.indices().delete(delete, RequestOptions.DEFAULT);
System.out.println(delete1.isAcknowledged());
}
//添加文档
@Test
void addDoc() throws IOException {
User user = new User(1, "张yoyo");
IndexRequest request = new IndexRequest("pzdb");
request.id("1");
request.timeout("1s");
request.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(index.toString());
System.out.println(index.status());
}
//获取文档,判断是否存在
@Test
void getDoc() throws IOException {
GetRequest getRequest = new GetRequest("pzdb", "1");
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
//获得文档信息
@Test
void getDocInfo() throws IOException {
GetRequest getRequest = new GetRequest("pzdb", "1");
GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(documentFields.getSourceAsString());
System.out.println(documentFields);
}
//获得文档信息
@Test
void updateDocInfo() throws IOException {
UpdateRequest update = new UpdateRequest("pzdb", "1");
update.timeout("1s");
User user = new User(1,"张禹桐");
update.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse update1 = restHighLevelClient.update(update, RequestOptions.DEFAULT);
System.out.println(update1.status());
}
@Test
void delectDoc() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("pzdb","1");
deleteRequest.timeout("1s");
DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.status());
}