Rethinkdb:计算每个用户的标记出现次数

时间:2015-05-22 15:46:26

标签: rethinkdb

我的表格包含如下文档:

[{ user: { 
    key: '100' 
  },
  product: {
    name: 'Product 1',
    tags: [ 'tag1', 'tag2' ],
  }
}, { user: { 
    key: '100' 
  },
  product: {
    name: 'Product 1',
    tags: [ 'tag1', 'tag3' ],
  }
}, ...]

我想创建一个

的查询
  • groupe文档由user.key字段(每个用户1个文档的结果),
  • product.tags将是一个对象(而不是数组),每个标记都有标记出现次数。

结果示例:

[ { user: { 
    key: '100' 
  },
  product: {
    name: 'Product 1',
    tags: {
      tag1: 2, // tag1 found 2x for user.key=100
      tag2: 1, // tag2 found 1x for user.key=100
      tag3: 1
    }
  }
}, ...]

我想我可以通过映射和缩减来实现这一点,但我遇到了问题 - 我第一次使用rethinkdb。

1 个答案:

答案 0 :(得分:0)

这是一种方法:

// Group by user key
r.table('30400911').group(r.row('user')('key'))
  // Only get the product info inside the reduction
  .map(r.row('product'))
  .ungroup()
  .map(function (row) {
    return {
      user: row('group'),
      // Group by name
      products: row('reduction').group('name').ungroup().map(function (row) {
        return {
          name: row('group'),
          // Convert array of tags into key value pairs
          tags: r.object(r.args(row('reduction').concatMap(function (row) {
            return row('tags')
          }).group(function (row) {
           return row; 
          }).count().ungroup().concatMap(function (row) {
            return [row('group'), row('reduction')]
          })))
        }
      })
    }
  })

以下数据:

{
  "id":  "0565e91a-01ca-4ba3-b4d5-1043c918c79d" ,
  "product": {
    "name":  "Product 2" ,
    "tags": [
      "tag1" ,
      "tag3"
    ]
  } ,
  "user": {
    "key":  "100"
  }
} {
  "id":  "39999c9f-bbef-4cb7-9311-2516ca8f9ba1" ,
  "product": {
  "name":  "Product 1" ,
    "tags": [
      "tag1" ,
      "tag3"
    ]
  } ,
  "user": {
    "key":  "100"
  }
} {
  "id":  "566f3b79-01bf-4c29-8a9c-fd472431eeb6" ,
  "product": {
    "name":  "Product 1" ,
    "tags": [
      "tag1" ,
      "tag2"
    ]
  } ,
  "user": {
   "key":  "100"
  }
} {
  "id":  "8e95c467-cedc-4734-ad4d-a1f7a371efd5" ,
  "product": {
    "name":  "Product 1" ,
    "tags": [
      "tag1" ,
      "tag2"
    ]
  } ,
  "user": {
    "key":  "200"
  }
}

结果将是:

[
  {
    "products": [
      {
        "name":  "Product 1" ,
        "tags": {
          "tag1": 2 ,
          "tag2": 1 ,
          "tag3": 1
        }
      }, {
        "name":  "Product 2" ,
        "tags": {
          "tag1": 1 ,
          "tag3": 1
        }
      }
    ],
    "user":  "100"
  } ,
  {
  "products": [
    {
      "name":  "Product 1" ,
      "tags": {
        "tag1": 1 ,
        "tag2": 1
      }
    }
  ] ,
  "user":  "200"
  }
]