美文网首页
mongo map reduce demon

mongo map reduce demon

作者: 良人与我 | 来源:发表于2019-01-30 09:43 被阅读6次

    对文档 entryStat 进行统计
    按照 shareTpye 筛选后的数据
    通过key 进行 mapreduce
    类似 sql 的

    select id ,count(1)
    from entryStat
    where shareType = #{shareType }
    groupby id

    代码如下

        public List<EntryStatMrResult> listEntryStat(int shareType){
            Query query = new Query(Criteria.where("shareType").is(shareType));
            MapReduceResults<EntryStatMrResult> mapReduceResults =  mongoTemplate.mapReduce(
                    query,
                    "entryStat",
                    "classpath:map.js",
                    "classpath:reduce.js",
                    EntryStatMrResult.class);
            return Lists.newArrayList( mapReduceResults.iterator());
        }
    

    文档的数据类型是

    @Getter
    @Setter
    public class EntryStat implements Serializable {
    
        @Id
        public String id;
    
        public String userId;
    
        public String userName;
    
        public Integer shareType ;
    
        public Date createTime;
    
        public Date updateTime;
    }
    

    返回类型

    @Data
    public class EntryStatMrResult {
    
        private String  id;
    
        private Integer value;
    
    }
    

    map.js

    function map() {
        emit(this.userId,1);
    }
    

    reduce.js

    function reduce(key, values2) {
        var sum = 0;
        for (var i = 0; i < values2.length; i++)
            sum += values2[i];
        return sum;
    }
    

    mongo 依赖

            <!--mongodb依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
            </dependency>
    

    参考文档
    https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
    https://docs.mongodb.com/manual/tutorial/map-reduce-examples/

    相关文章

      网友评论

          本文标题:mongo map reduce demon

          本文链接:https://www.haomeiwen.com/subject/ifsqsqtx.html