mongodb map从子文档中发出键

时间:2012-02-10 17:47:57

标签: mongodb mapreduce

我有一个包含子文档的文档:

{
    "_id" : ObjectId("XXXXX"),
    "SearchKey" : "1234",
    "SearchTerms" : {
        "STA" : ["1"],
        "STB" : ["asdfasdf"],
        "STC" : ["another"]
    }
}

SearchTerm元素不固定 - 例如,有时我们会有没有STC的STA。

我可以这样做:

var map = function() {
    for (key in this.SearchTerms)
    {
        emit(key, 1);
    }
}

但我不能这样做:

var map = function() {
    for (var i=0; i< this.SearchTerms.length; i++)
    {
        emit(this.SearchTerms[i], 1)
    }
}

因为后者在减少后不会产生任何结果。为什么不呢?

顺便说一句 - 我需要做的是计算所有文档中搜索项的交叉积,即查找(STA和STB)和(STA和STC)以及(STB和STC)的发生率在上面的情况。如果有人知道如何立即做到这一点,那就更好了。

一如既往,感谢您的帮助

2 个答案:

答案 0 :(得分:3)

您发出的密钥应该是两个密钥的组合。

    var map = function() {
        if(!this.SearchTerms) return;
        for(var i = 0 ; i < this.SearchTerms.length; i++){
            var outerKey = this.SearchTerms[i];
            for(var j = i + 1; j < this.SearchTerms.length; j++){
               var innerKey = this.SearchTerms[j];
               // assuming you don't care about counting (STA and STC) separately from (STC and STA), 
               // then order doesn't matter, lets make sure both occurences have the same key.
               var compositeKey = (outerKey < innerKey) ? outerKey+"_"+innerKey : innerKey+"_"+outerKey; 
               emit(compositeKey, 1);
            }
        }
    }

答案 1 :(得分:0)

这是因为this.SearchTerms是字典/子文档而不是数组。 this.SearchTerms[0]不存在。

对于第二个问题:这样的事情应该有效:

for (key1 in this.SearchTerms)
{
  for (key2 in this.SearchTerms)
  {       
    if (key1 < key2)
    {
      key = [key1, key2];
      emit(key, 1);
    }
  }
}
相关问题