public void top100Postinfo() {
long start = System.nanoTime();
try {
final long startTime = 1443628800000L;
final long endTime = 1446436799000L;
Query query = new Query();
query.addCriteria(Criteria.where("createTS").gte(startTime).lte(endTime));
query.addCriteria(Criteria.where("srcPostId").exists(true));
query.addCriteria(Criteria.where("referInfo").exists(false));
query.addCriteria(Criteria.where("dr").is(0));
long count = postinfoDAO.getCount(query);
System.out.println("count:" + count);
final int filterCount = 100;
DBObject result1 = postinfoDAO.getMongoTemplate().execute(Postinfo.class, new CollectionCallback<DBObject>() {
@Override
public DBObject doInCollection(DBCollection collection) throws MongoException, DataAccessException {
// match匹配条件
Map matchMap = new HashMap();
matchMap.put("createTS", new BasicDBObject("$gt", startTime).append("$lt", endTime));
matchMap.put("referInfo", new BasicDBObject("$exists", false));
matchMap.put("srcPostId", new BasicDBObject("$exists", true));
matchMap.put("dr", 0);
DBObject matchOption = new BasicDBObject("$match", matchMap);
// group条件
Map groupMap = new HashMap();
groupMap.put("_id", "$srcPostId");
groupMap.put("total", new BasicDBObject("$sum", 1));
BasicDBObject groupOption = new BasicDBObject("$group", groupMap);
// sort条件
Map sortMap = new HashMap();
sortMap.put("total", -1);
BasicDBObject sortOption = new BasicDBObject("$sort", sortMap);
// limit条件
BasicDBObject limitOption = new BasicDBObject("$limit", filterCount);
// 获取结果集
AggregationOutput output = collection.aggregate(matchOption, groupOption, sortOption, limitOption);
Iterator<DBObject> iterator = output.results().iterator();
DBObject result = null;
List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
while (iterator.hasNext()) {
result = iterator.next();
String id = (String) result.get("_id");
Integer total = (Integer) result.get("total");
System.out.println("id:" + id);
System.out.println("total:" + total);
Map<String, String> resultMap = new HashMap<>();
resultMap.put("id", id);
resultMap.put("total", String.valueOf(total));
resultList.add(resultMap);
}
exportExcel(resultList);
return result;
}
});
} catch (Exception e) {
e.printStackTrace();
}
long finish = System.nanoTime();
System.out.println(TimeUnit.NANOSECONDS.toSeconds(finish - start) + ":秒");
System.out.println("top20PercentPostinfo 执行完毕");
}
// 相当于mongo语句如下
db.Postinfo.aggregate([
{ $match: { "createTS":{"$gt":1443628800000, "$lt":1446436799000}, "srcPostId":{$exists:true}, "referInfo":{$exists:false}, "dr":0 } },
{ $limit: 1 },
{ $group: { _id: "$srcPostId", total: { $sum: 1 } } },
{ $sort: { total: -1 } }
]);