1.首先我们来看最终效果
整合完成JestClient,查询出ES中所有的索引。
2.首先我们来看一看什么是JestClient
Jest 是ElasticSearch 的java Http Rest 客户端。
他主要是让我们更在使用java执行es语法的时候更方法,他给我们很多的封闭。
3.整合JestClient
3.1 老套路添加依赖
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>6.3.1</version>
</dependency>
3.2 在application.yml中添加配置文件
spring:
elasticsearch:
jest:
uris: http://127.0.0.1:9200/
read-timeout: 120s
connection-timeout: 120s
3.3 在代码中使用了
注入Bean对象
@Autowired
private JestClient jestClient;
在方法中写API
@Override
public Page<Map<String, String>> getIndex(String name, PageVo page) {
GetMapping.Builder builder = new GetMapping.Builder();
if (StrUtil.isNotEmpty(name)) {
builder.addIndex(name);
}
GetMapping getMapping = builder.build();
try {
JestResult execute = jestClient.execute(getMapping);
if (execute.isSucceeded()) {
JsonObject jsonObject = execute.getJsonObject();
Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();
List<Map<String, String>> arrayList = entries.stream().map((el) -> {
Map<String, String> map = new HashMap<>();
map.put("indexName", el.getKey());
map.put("indexValue", el.getValue().toString());
return map;
}).collect(Collectors.toList());
Page<Map<String, String>> mapPage = PageUtil.listBuildMapPage(page, arrayList);
return mapPage;
}
throw new TbootException("连接es失败");
} catch (IOException e) {
e.printStackTrace();
throw new TbootException("连接es失败");
}
}
3.4 代码解释
GetMapping.Builder builder = new GetMapping.Builder();
if (StrUtil.isNotEmpty(name)) {
builder.addIndex(name);
}
GetMapping getMapping = builder.build();
这段代码是组装请求参数, 对应ES中查询索引Mapping结构
GET http://localhost:9200/_mapping 查询索引结构
下图是ES执行结果
3.5 发起请求代码解释
其实也没有什么好解释的,就是将请求参数,发起一个http 的请求。
JestResult execute = jestClient.execute(getMapping);
简单小结
这篇文章就是一个JestClient的一个小小的入门,包括了springboot整合Jest,还使用了jestClient发起了一个查询请求。实现了一个功能,实现全部索引的查询。
这里有一个问题就是这个_mapping 是没有分页查询的, 这是ElasticSearch的问题,和JestClient没有关系。 不过我们自己实现了分页查询和条件查询。
如果想看效果的话可以关注我们的线上案例。
效果预览 效果预览 效果预览 推荐使用edge浏览器,谷歌浏览器多刷新几次。
我们的gitee地址