ES高级API空指针异常

ES高级API空指针异常

@Autowired
    private RestHighLevelClient client;
    /**
     * 查询所有
     *  1. matchAll
     *  2. 将查询结果封装为Goods对象,装载到List中
     *  3. 分页。默认显示10条
     */
    @Test
    public void testMatchAll() throws IOException {
        //2. 构建查询请求对象,指定查询的索引名称
        SearchRequest searchRequest = new SearchRequest("skuinfo");
        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //6. 查询条件
        QueryBuilder query = QueryBuilders.matchAllQuery();//查询所有文档
        //5. 指定查询条件
        sourceBuilder.query(query);
        //3. 添加查询条件构建器 SearchSourceBuilder
        searchRequest.source(sourceBuilder);
        // 8 . 添加分页信息
        sourceBuilder.from(0);
        sourceBuilder.size(20);
        //1. 查询,获取查询结果
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //7. 获取命中对象 SearchHits
        SearchHits searchHits = searchResponse.getHits();
        //7.1 获取总记录数
        long value = searchHits.getTotalHits();
        System.out.println("总记录数:"+value);
        List<SkuInfo> skusList = new ArrayList<>();
        //7.2 获取Hits数据  数组
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            //获取json字符串格式的数据
            String sourceAsString = hit.getSourceAsString();
            //转为java对象
            SkuInfo skus = JSON.parseObject(sourceAsString, SkuInfo.class);
            skusList.add(skus);
        }
        for (SkuInfo goods : skusList) {
            System.out.println(goods);
        }
    }
上一篇:elasticsearch——Rest Client


下一篇:ElasticSearch的RestHighLevelClient高阶操作