2012-01-23 4 views
0

나는 플레이! framework morphia-mongodb 모듈을 포함하고 있으며 그룹 집계를위한 훌륭한 내장 기능을 가지고 있습니다. 불행히도 모든 예제는 고정 필드에 의한 그룹화/집계 만 표시하는 반면, 계산 된 필드에 의한 집계가 필요합니다 : 일별 그룹화 된 timestamp. 아무도 이것이 올바른 접근법을 알고 있는지 궁금합니다. (영화와 상영을 사용하여, 자신이 알아 내기 위해 약간의 파고 발생한, 그래서는 참조 용으로 여기에 게시하도록하겠습니다) 난 그냥 기본지도에 의존 할 수 있습니다 알고재생! 프레임 워크 morphia 모듈 그룹 집계 날짜 버킷으로

/축소 :

 DBCollection coll = Movie.col(); 
     String map = "function() { " + 
      (this.showtime.getMonth() + 1) + '/' + this.showtime.getDate()}; " 
      + "var key = {date: this.showtime.getFullYear() + '/' 
      + (this.showtime.getMonth() + 1)  
      + '/' + this.showtime.getDate()}; " 
      + "emit(key, {count: 1}); }"; 

     String reduce = "function(key, values) { var sum = 0; " 
      + " values.forEach(function(value) {sum += value['count'];});" 
      + " return {count: sum}; }"; 

     String output = "dailyShowingCount"; 

     MapReduceOutput out = coll.mapReduce(
      map, reduce, output, MapReduceCommand.OutputType.REPLACE, null); 

     SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");  
     for (Iterator<DBObject> itr = out.results().iterator(); itr.hasNext();) { 
      DBObject dbo = itr.next(); 

      String compoundKeyStr = dbo.get("_id").toString(); 
      String compoundValStr = dbo.get("value").toString(); 

      DBObject compKey = (DBObject)JSON.parse(compoundKeyStr); 
      DBObject compVal = (DBObject)JSON.parse(compoundValStr); 

      //don't know why count returns as a float, but it does, so i need to convert  
      Long dCount = new Double(
       Double.parseDouble(compVal.get("count").toString()) 
      ).longValue(); 

      Date date = df.parse(compKey.get("date").toString()); 
     } 

그러나 morphia 모듈을 사용하여이 집계를 수행하는 데있어 이미 우아한 기본 제공 방법이있는 경우이를 대신 사용하고 싶습니다. 한 가지 생각은 내 Java 클래스 (예 : "getDay()")에 가상 필드를 만든 다음 그룹화/집계하는 것입니다. 누구도이 경험이 있습니까?

답변

0

가장 쉬운 방법은 모델에서 파생 열을 만들어 데이터베이스에 저장하는 것입니다.

@Entity Movie extends Model { 
    public Date showTime; 
    private Date showTimeDate; 
    @OnUpdate 
    @OnAdd 
    void calcShowTimeDate() { 
     Calendar c = Calendar.getInstance(); 
     c.setTime(showTime); 
     c.set(Calendar.HOUR_OF_DAY, 0); 
     c.set(Calendar.MILLISECOND, 0); 
     c.set(Calendar.MINUTE, 0); 
     c.set(Calendar.SECOND, 0); 
     showTimeDate = c.getTime() 
    } 
} 

은 그럼 당신은 http://www.playframework.org/modules/morphia-1.2.4d/statistics

의 지시에 따라 showTimeDate 열을에 집계 할 수