es7.1基本查询 java API
链接: es7.1聚合查询 javaAPI (一).
1. 随机取15条数据
/**
* 1.随机取15条数据(默认10条)
* 类似sql如下:
* select * from myIndex order by rand() limit 15
*
* ShowData : 返回一条数据的实体类(不做赘述)
* getClient(): 获取es查询的连接对象(不做赘述)
* 注释: 只能取1万条
*/
public List<ShowData> query1(){
List<ShowData> result = new ArrayList<>(); //返回查询的结果集
RestHighLevelClient client = getClient(); //创建连接对象
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder() //创建查询对象
.size(15) //查询15条数据
.sort(SortBuilders.scriptSort(new Script("Math.random()"), //随机取数据
ScriptSortBuilder.ScriptSortType.NUMBER));
SearchRequest rq = new SearchRequest("myIndex") //创建请求对象 请求索引库
.source(sourceBuilder); //组装查询对象
try{
SearchResponse response = client.search(rq, RequestOptions.DEFAULT); //获得相应
ShowData showData;
for (SearchHit hit : response.getHits().getHits()) {
// 循环查询结果 转换成实体类
String sourceAsString = hit.getSourceAsString();
showData = JSON.parseObject(sourceAsString, ShowData.class);
result.add(showData);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
closeClient(client); //关闭连接对象
} catch (IOException e) {
e.p