笔记:
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;
}