mongodb mapReduce

来源:互联网 发布:linux查看网络命令 编辑:程序博客网 时间:2024/04/29 03:59

 /**
  * 岗位总需求统计
  */
 @Override
 public void findJobStandardCount() {
  StringBuffer mapFunction = new StringBuffer();
  StringBuffer reduceFunction = new StringBuffer();
  List<String> readMap = null;
  List<String> readReduce = null;
  try {

//org.apache.commons.io 包
   readMap = IOUtils.readLines(this.getClass().getClassLoader().getResourceAsStream("map.js"),"UTF-8");//读取js
   readReduce = IOUtils.readLines(this.getClass().getClassLoader().getResourceAsStream("reduce.js"),"UTF-8");
  } catch (IOException e1) {
   e1.printStackTrace();
  }
  for(int i=0; i<readMap.size();i++) {
   mapFunction.append(readMap.get(i)  + "\r\n");
  }
  for(int i=0; i<readReduce.size();i++) {
   reduceFunction.append(readReduce.get(i)  + "\r\n");
  }
        Query query = new Query();
        //Calendar c = DateUtils.changeFormatDate(-7, 0, 0, 0);
        //query.addCriteria(Criteria.where("createDate").is(c.getTime()));
        this.mgdao.mapReduce(query, "HR_JobStandard", mapFunction.toString(), reduceFunction.toString(),MapReduceOptions.options().outputCollection("SCHM_JobToDayCount") ,JobToDayEntity.class);
 }

 

map.js

function map(){
 var myDate = this.createDate;
 var year = myDate.getFullYear();
 var month = myDate.getMonth()+1;
 var date = myDate.getDate();
 var day=myDate.getDay();
 var toDate=new Date();
 var year2 = toDate.getFullYear();
 var month2 = toDate.getMonth()+1;
 var date2 = toDate.getDate();
 var day2=toDate.getDay();
  emit("all",{count:1});
 if(year==year2&&month2==month&&date2==date){
  emit("day",{count:1});
 }
 if(year==year2&&month2==month&&date2-1==date){
  emit("lastday",{count:1});
 }
 if(year==year2&&month==month2){
  emit("month",{count:1});
 }
 if(year==year2&&month==month2-1){
  emit("lastmonth",{count:1});
 }
 var start=date-day+1;
 var end=date+(7-day);
 if(year==year2&&month==month2&&date>=start&&date<=end){
  emit("week",{count:1});
 }
 if(year==year2&&month==month2&&date>=start-7&&date<=end-7){
  emit("lastweek",{count:1});
 }
  if(year==year2){
   if(month>=6*(month2/6)&&month<=6*(month2/6+1)){
    emit("halfYear",{count:1});
   } 
   }
  if(month2>=6){
    if(year==year2&&month>=0&&month<=6){
     emit("lasthalfYear",{count:1});
    }
  }else{
    if(year==year2-1&&month>=6&&month<=12){
      emit("lasthalfYear",{count:1});
    }
  }
}

reduce.js

function reduce(key, values) {
 var n=values.length;
 return {"count":n};
}

特别指出的是 emit()中如果只执行一遍 将不走reduce.js

0 0