@SpringBootTest
public class MyTest{
//注入RestHighLevelClient对象
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
public void test() throws IOException {
//准备SearchRequest请求对象,并指定索引库名
SearchRequest searchRequest = new SearchRequest(索引库名);
//准备MatchAllQueryBuilder查询对象
MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
//在SearchRequest请求对象中放入MatchAllQueryBuilder查询对象
searchRequest.source().query(matchAllQueryBuilder);
//在SearchRequest请求对象中进行排序
searchRequest.source().sort(字段名, SortOrder.ASC);
//在SearchRequest请求对象中进行分页
searchRequest.source().from(跳过多少条数据).size(页面展示多少条数据);
//发送请求,得到响应对象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//从响应对象中获取响应结果
SearchHits searchHits = searchResponse.getHits();
//获取文档的总条数
long total = searchHits.getTotalHits().value;
//获取搜索结果数组
SearchHit[] hits = searchHits.getHits();
//创建文档集合,用于存放结果
List<文档类名> 集合对象名 = new ArrayList<>();
//遍历数组
for (SearchHit hit : hits) {
//获取Json格式的文档内容
String json = hit.getSourceAsString();
//反序列化Json,这里需要引入fastjson的依赖
文档类名 文档对象名 = JSON.parseObject(json, 文档类名.class);
//将结果放入集合
集合对象名.add(文档对象名);
}
}
}