用Java代码查询Eelasticsearch的数据

笔记:
public List<UserRegDocument> findUserByGodID(Long mid, String val, int pageNo, int pageSize, String index) {
    if (mid == null) {
        return null;
    }

    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
    if (val != null) {
        queryBuilder.must(QueryBuilders.termQuery("user_id", val));
    }
//查询字段
    SearchResponse searchResponse = getSearchByRegBuilder(mid,index,queryBuilder,pageNo,pageSize)
            .addField(ProfileConstants.INDEX_COL_PRIKEY)
            .addField(ProfileConstants.INDEX_COL_USERID)
            .addField(ProfileConstants.INDEX_COL_REGTYPE)
            .addField(ProfileConstants.INDEX_COL_TENBIND)
            .addField(ProfileConstants.INDEX_COL_ALIBIND)
            .addField(ProfileConstants.INDEX_COL_MOBBIND)
            .addField(ProfileConstants.INDEX_COL_REGTIME)
            .get();
    return new ESHitParser<UserRegDocument>().parser(searchResponse,UserRegDocument.class);
}
//封装的查询方法
private SearchRequestBuilder getSearchByRegBuilder(Long mid,String index,BoolQueryBuilder query,int pageNo,int pageSize){
 
 
    query.must(QueryBuilders.termQuery(ProfileConstants.INDEX_COL_MID, mid));
    query.must(QueryBuilders.existsQuery(ProfileConstants.INDEX_COL_REGTIME));//排除某字段为空的数据
    return elasticFirmSearchHandler
            .getClient()
            .prepareSearch(index)
            .setTypes(ProfileConstants.INDEX_TYPE)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .addSort(SortBuilders.fieldSort(ProfileConstants.INDEX_COL_REGTIME).order(SortOrder.DESC))
            .setQuery(query)
            .setFrom((pageNo-1) * pageSize)
            .setSize(pageSize)
            .setExplain(false);
}

//取值封装的方法
public List<T> parser(SearchResponse searchResponse, Class cls){
    if(searchResponse == null || searchResponse.getHits() == null){
        return null;
    }

    SearchHit[] searchHists = searchResponse.getHits().getHits();
    if (searchHists == null || searchHists.length == 0) {
        return null;
    }

    List<T> list = new ArrayList<>();
    for (SearchHit hit : searchHists) {
        //System.out.println(hit.getSourceAsString());
        Set<Map.Entry<String, SearchHitField>> fieldEntry =  hit.getFields().entrySet();
        JSONObject json = new JSONObject();
        for(Map.Entry<String, SearchHitField> entry:fieldEntry){
            json.put(entry.getValue().getName(), entry.getValue().getValue());
        }
        System.out.println("json:" + json);
        T doc = (T)JSONObject.parseObject(json.toJSONString(),cls);
        list.add(doc);
    }
    return list;
}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值