0

我正在尝试在我们的应用程序中汇总一堆用户个人资料数据。每个用户都有一个带有性别和种族属性的嵌入式配置文件。

{
  'email': 'foo@email.com',
  'profile': {
    'gender': 'male',
    'ethnicity': 'Hispanic'
  }
}

如果我使用这样的组功能:

db.respondents.group({
  key: {},
  initial: {'gender': {'male':0,'female':0}, 'ethnicity': {}, 'count': 0},
  reduce: function (user, totals) {
    var profile = user.profile;

    totals.gender[profile.gender]++;
    totals.ethnicity[profile.ethnicity] = (totals.ethnicity[profile.ethnicity] || 0);
    totals.ethnicity[profile.ethnicity]++
    totals.count++;
 }
});

我以我想要的形式得到结果:

{
    "gender" : {
        "male" : ###,
        "female" : ###
    },
    "ethnicity" : {
        "Caucasian/White" : ###,
        "Hispanic" : ###,
                    ...

    },
    "count" : ###
}

我无法让它作为 map/reduce 命令工作,当然使用不同的 reduce 函数。我不确定如何使总数相加。他们总是不正确的。我知道reduce的输出必须与map的输入格式相同,但我觉得我在reduce工作的方式上遗漏了一些东西......

作为对@Jenna 的回应,输入如下所示:

{
  'email': 'foo@email.com',
  'profile': {
    'gender': 'male',
    'ethnicity': 'Hispanic'
  }
}

功能是:

function map(){
  emit('demographics', this.profile)
}

function reduce (key, values) {
  var reduced = {'gender': {'male':0,'female':0}, 'ethnicity': {}, 'count': 0};
  values.forEach(function(value) {
    reduced.gender[value.gender]++;
    reduced['ethnicity'][value.ethnicity] = (reduced['ethnicity'][value.ethnicity] || 0);
    reduced['ethnicity'][value.ethnicity]++;
    reduced.count++;
  });
  return reduced;
}

输出是:

{
    "_id": "demographics",
    "value": {
      "gender": {
        "male": 76.0,
        "female": 64.0
      },
      "ethnicity": {
        "Caucasian/White": 109.0,
        "Other": 5.0,
        "Asian": 10.0,
        "African-American": 8.0,
        "Hispanic": 7.0,
        "Native American": 1.0
      },
      "count": 141.0
    }
}

输出不正确,因为数据库中有超过 100k 条记录。

4

1 回答 1

2

可以在先前调用的输出上再次调用 reduce 函数。正确的是,map 的输出应该与 reduce 的输出相同。您当前的 map 函数返回的内容与您的 reduce 函数不同。尝试这样的事情:

function map(){
  result = {'gender': {'male': 0, 'female': 0}, 'ethnicity': {}, 'count': 1};
  result['gender'][this.gender] = 1;
  result['ethnicity'][this.ethnicity] = 1;
  emit('demographics', result);
}

function reduce (key, values) {
  var reduced = {'gender': {'male':0,'female':0}, 'ethnicity': {}, 'count': 0};
  values.forEach(function(value) {
    reduced['gender']['male'] += value['gender']['male'];
    reduced['gender']['female'] += value['gender']['female'];
    for(ethnicity in value['ethnicity']){
      if(reduced['ethnicity'][ethnicity] === undefined)
        reduced['ethnicity'][ethnicity] = 0
      reduced['ethnicity'][ethnicity] += value['ethnicity'][ethnicity]
    }
    reduced['count'] += values.count;
  });
  return reduced;
}
于 2012-07-02T18:38:20.647 回答