上次的mongodb之group http://my.oschina.net/jmacs/blog/97078
下面展示下map reduce
数据:
要求用sql描述,通俗易懂。
要求一:SELECT group ,sum(value),count(1),avg(value) from xx GROUP BY groupmap函数:
StringBuilder mapfun = new StringBuilder(); mapfun.append("function (){"); mapfun.append("emit(this.group,{value : this.value, sum : 0 , avg : 0});"); mapfun.append("}");
reduce函数:
StringBuilder reduceFun = new StringBuilder(); reduceFun.append("function (key,vals){"); reduceFun.append(" var res = vals[0] ;"); reduceFun.append(" var sum = 0 ;"); reduceFun.append(" var count = 0 ;"); reduceFun.append(" for(var i in vals) {"); reduceFun.append(" count ++;"); reduceFun.append(" sum += vals[i].value;"); reduceFun.append(" }"); reduceFun.append(" res.sum = sum;"); reduceFun.append(" res.avg = sum/count;"); reduceFun.append(" return res;"); reduceFun.append("}");打印输出:
List<Map<String, Object>> list = dao.mapReduce("c", mapfun.toString(), reduceFun.toString()); for (Map<String, Object> map : list) { System.out.println(map); }
select group ,sum(value),count(1),avg(value),max(value),min(value) from xx group by groupmap函数:
StringBuilder mapfun = new StringBuilder(); mapfun.append("function (){"); mapfun.append("emit(this.group,{group:this.group ,value : this.value});"); mapfun.append("}");reduce函数:
StringBuilder reduceFun = new StringBuilder(); reduceFun.append("function (key,vals){"); reduceFun.append(" var res = {} ;"); reduceFun.append(" var sum = 0 ;"); reduceFun.append(" var count = 0 ;"); reduceFun.append(" var avg = 0 ;"); reduceFun.append(" var max = vals[0].value;"); reduceFun.append(" var min = vals[0].value;"); reduceFun.append(" for(var i in vals) {"); reduceFun.append(" var value = vals[i].value;"); reduceFun.append(" count ++;"); reduceFun.append(" sum += value;"); reduceFun.append(" if(max < value){"); reduceFun.append(" max = value"); reduceFun.append(" }"); reduceFun.append(" if(min > value){"); reduceFun.append(" min = value"); reduceFun.append(" }"); reduceFun.append(" }"); reduceFun.append(" res.group = vals[0].group;"); reduceFun.append(" res.sum = sum;"); reduceFun.append(" res.avg = sum/count;"); reduceFun.append(" res.max = max;"); reduceFun.append(" res.min = min;"); reduceFun.append(" return res;"); reduceFun.append("}");打印出书:
List<Map<String, Object>> list = dao.mapReduce("c", mapfun.toString(), reduceFun.toString()); for (Map<String, Object> map : list) { System.out.println(map); }