@Test
public void createIndex() throws IOException {
Request getRequest = new Request("put", "/20220327001/");
getRequest.setJsonEntity("{\n" + " \"settings\":{\n" + " \"number_of_shards\":5,\n" + " \"number_of_replicas\":3\n" + " },\n" + " \"mappings\":{\n" + "\n" + " \"properties\":{\n" + " \"name\":{\n" + " \"type\":\"keyword\"\n" + " }\n" + "\n" + " }\n" + " }\n" + "}");
RestClient client = EsConfig.initClient();
Response response = client.performRequest(getRequest);
client.close();
System.out.println(EntityUtils.toString(response.getEntity()));
}
/**
* 查询所有的索引信息
*/
@Test
public void searchIndices() {
RestClient client = EsConfig.initClient();
Request request = new Request("GET", "/_cat/indices?v");
try {
Response response = client.performRequest(request);
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException exception) {
LOGGER.info(exception.getMessage());
} finally {
try {
client.close();
} catch (IOException exception) {
LOGGER.info(exception.getMessage());
}
}
}
/**
* 根据索引id查询索引信息
*/
@Test
public void searchIndexById() {
RestClient client = EsConfig.initClient();
Request request = new Request("Get", "/20220325001/");
try {
Response response = client.performRequest(request);
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException exception) {
LOGGER.info(exception.getMessage());
} finally {
try {
client.close();
} catch (IOException exception) {
LOGGER.info(exception.getMessage());
}
}
}
/**
* 删除索引
*/
@Test
public void deleteIndex() {
RestClient client = EsConfig.initClient();
Request request = new Request("delete", "/20220325003");
Cancellable cancellable = client.performRequestAsync(request, new ResponseListener() {
@Override
public void onSuccess(Response response) {
try {
LOGGER.info(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
LOGGER.info(e.getMessage());
}
}
@Override
public void onFailure(Exception e) {
System.out.println(e.getMessage());
}
});
}
@Test
public void query() throws IOException {
RestClient client = EsConfig.initClient();
Request request = new Request("GET", "20220325001/_doc/20220326001");
// StringBuilder body = new StringBuilder();
Response response = client.performRequest(request);
System.out.println(EntityUtils.toString(response.getEntity()));
}
@Test
public void queryMatch() throws IOException {
RestClient client = EsConfig.initClient();
Request request = new Request("POST", "/20220325001/_search?filter_path=hits");
request.setJsonEntity(" {\n" +
" \"query\":{\n" +
" \"match_all\":{\n" +
" \n" +
" }\n" +
" }\n" +
"}");
Response response = client.performRequest(request);
System.out.println(EntityUtils.toString(response.getEntity()));
client.close();
}
}
RestClient实现Elasticsearch的简单操作
最新推荐文章于 2025-05-18 17:27:39 发布