記錄一次es商品門店查詢,關鍵字SearchSourceBuilder

SearchSourceBuilder 使用說明
參考:https://www.cnblogs.com/reycg-blog/p/9946821.html

@Override
public List<String> baseProductShopNotExistEsSearch(ReqBaseProductShopPageEsQueryVO reqVO) {
    try {
        SearchRequest searchRequest = new SearchRequest(EsOperateTables.BASE_PRODUCT_SHOP_SAP.getAlias());
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.fetchSource("shop_code", null);//過濾門店編碼爲null數據
        Collection<String> ids = reqVO.getIds();
        if (CollectionUtils.isNotEmpty(ids)) {
            ids=ids.stream().distinct().collect(Collectors.toList());
            sourceBuilder.query(QueryBuilders.termsQuery(EsUtils.ID, ids));//根據ID查詢
        }else{
            throw new RRException("請求參數不能爲空");
        }
        sourceBuilder.timeout(TimeValue.timeValueMinutes(2L));
        sourceBuilder.size(new Long(ConstantsUtils.QueryPartams.MAX_RESULT_COUNT).intValue());//分頁量
        sourceBuilder.sort(EsUtils.ID, SortOrder.DESC);//排序
        searchRequest.source(sourceBuilder);
        //scroll 分頁搜索
        Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));
        searchRequest.scroll(scroll);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        String scrollId = searchResponse.getScrollId();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        List<String> mapList = Lists.newArrayList();
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        while (true) {
            if(StringUtils.isNotBlank(scrollId)){
                clearScrollRequest.addScrollId(scrollId);
            }
            if(searchHits == null || searchHits.length == 0){
                break;
            }
            Arrays.stream(searchHits).forEach(hit -> mapList.add(hit.getId()));
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            scroll = new Scroll(TimeValue.timeValueMinutes(1L));
            scrollRequest.scroll(scroll);
            searchResponse = restHighLevelClient.scroll(scrollRequest, RequestOptions.DEFAULT);
            scrollId = searchResponse.getScrollId();
            searchHits = searchResponse.getHits().getHits();
        }
        ClearScrollResponse clearScrollResponse = restHighLevelClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        boolean succeeded = clearScrollResponse.isSucceeded();
        if(!succeeded){
            throw new RRException("清除es遊標失敗");
        }
        if(CollectionUtils.isNotEmpty(mapList)){
            return Lists.newArrayList(CollectionUtils.disjunction(ids,mapList));
        }else{
            return Lists.newArrayList(ids);
        }

    } catch (Exception e) {
       log.error(e.getMessage());
        throw new RRException(e.getMessage());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章