【问题标题】:MapReduce: aggregate in map function?MapReduce:地图功能中的聚合?
【发布时间】:2017-03-24 06:51:30
【问题描述】:

假设您有一个数据库,其中每个文档都是来自 Twitter 的推文,并且您希望使用 MapReduce 生成另一个文档,其中包含:

  • 每个国家/地区发布的推文数量
  • 这些推文中包含的单词列表,带有一个计数器,用于计算该单词的总点击量。这也适用于每个国家/地区。

我的问题:在 map 函数上聚合和计算单词是否可以,然后再在 reduce 函数上?这样做,map 函数的输出表示单个推文的信息,reduce 函数聚合来自同一个国家/地区的几条推文的信息,但我不知道这是否是一个好的做法MapReduce 算法...

提前谢谢你!

【问题讨论】:

    标签: mongodb mapreduce


    【解决方案1】:

    在 mongoDB 3.4 中,您可以使用聚合框架来完成此过程。

    对于第一个项目符号,您只需在国家字段中使用 $group 运算符并计算推文。

    对于第二个项目符号,您必须在推文文本的字段中使用 $split(new in 3.4) 运算符,然后在生成的数组中使用 $unwind,最后使用 $group with word as _id or country + word as _id。

    如果您有旧版本的 mongodb,则必须使用 map-reduce 过程,但请记住,聚合框架比 mongodb 上的 map-reduce 快得多。

    $split:https://docs.mongodb.com/manual/reference/operator/aggregation/split/#exp._S_split

    $unwind:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

    $组:https://docs.mongodb.com/manual/reference/operator/aggregation/group/

    【讨论】:

      【解决方案2】:

      由 Moi Syme 从上面的 great answer 构建,理想情况下,您将运行以下聚合操作以获得所需的结果:

      db.tweets.aggregate([
          { "$project": { "wordList": { "$split": [ "$text", " " ] }, "user.country": 1 } },
          { "$unwind": "$wordList" },
          {
              "$group": {
                  "_id": {
                      "country": "$user.country",
                      "word": "$wordList"
                  },
                  "count": { "$sum": 1 }
              }
          },
          {
              "$group": {
                  "_id": "$_id.country",
                  "numberOfTweets": { "$sum": 1 },
                  "counts": {
                      "$push": {
                          "word": "$_id.word",
                          "count": "$count"
                      }
                  }
              }
          }
      ])
      

      【讨论】:

        猜你喜欢
        • 2017-06-05
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2019-01-06
        • 2015-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多