【问题标题】:Play! framework morphia module group aggregation by date bucket玩!框架morphia模块组聚合按日期桶
【发布时间】:2012-01-23 16:23:47
【问题描述】:

我正在使用 Play!框架 morphia-mongodb 模块,我看到它有很好的内置插件来进行组聚合。不幸的是,所有示例仅显示按固定字段进行分组/聚合,而我需要按计算字段进行聚合:按天分组的时间戳。我想知道是否有人知道正确的方法?

我知道我可以求助于原生地图/减少(它本身需要一点点挖掘才能弄清楚,所以我在这里发布以供参考,使用电影和放映时间):

        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()”),然后通过它进行分组/聚合。有人有这方面的经验吗?

【问题讨论】:

    标签: javascript mongodb playframework mapreduce morphia


    【解决方案1】:

    最简单的方法是在模型中创建一个派生列并将其保存到数据库中。

    @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 列上进行聚合

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2016-04-07
      • 2013-11-25
      • 1970-01-01
      相关资源
      最近更新 更多