문자열 배열을 포함하는 열이있는 데이터베이스가 있습니다. 예시 표 :
name | words | ...
Ash | ["Apple", "Pear", "Plum"] | ...
Joe | ["Walnut", "Peanut"] | ...
Max | ["Pineapple", "Apple", "Plum"] | ...
이제이 테이블을 주어진 단어 배열과 비교하고 일치율에 따라 문서를 그룹화하고 싶습니다.
예상 결과가있는 입력 예 :
// matched for input = ["Walnut", "Peanut", "Apple"]
{
"1.00": [{name:"Joe", match:"1.00"}],
"0.33": [{name:"Ash", match:"0.33"}, {name:"Max", match:"0.33"}]
}
map
일치율을 키로 사용하여 문서를 내보내는 다음 기능을 사용하고 있습니다 .
function map() {
var matches = 0.0;
for(var i in input)
if(this.words.indexOf(input[i]) !== -1) matches+=1;
matches /= input.length;
var key = ""+matches.toFixed(2);
emit(key, {name: this.name, match: key});
}
이제 누락 된 것은 내 보낸 reduce
KV 쌍을 결과 객체로 결합 하는 일치 함수입니다.
나는 이것을 다음과 같이 시도했다.
function reduce(key, value) {
var res = {};
res[key] = values;
return res;
}
그러나 나는 사양에 문제가 있습니다.
MongoDB는 동일한 키에 대해 축소 함수를 두 번 이상 호출 할 수 있습니다. 이 경우 해당 키에 대한 축소 함수의 이전 출력은 해당 키에 대한 다음 축소 함수 호출에 대한 입력 값 중 하나가됩니다.
... 중첩 된 결과 개체가 생성됩니다. 일치별로 문서를 그룹화하는 올바른 방법은 무엇입니까?
동일한 키에 대해 축소 기능을 두 번 이상 호출하십시오.
그것은 멱 등성 이고, 감소 함수는 그것을 존중해야합니다.
그러나 이것을 간단하게 만들기 위해지도 출력이 축소 출력과 동일한 형식인지 확인하기 만하면됩니다.
귀하의 경우 다음과 같이 작동합니다.
db.col.insert({"name": "Ash", "words": ["Apple", "Pear", "Plum"]})
db.col.insert({"name": "Joe", "words": ["Walnut", "Peanut"]})
db.col.insert({"name": "Max", "words": ["Pineapple", "Apple", "Plum"]})
function map() {
input = ["Walnut", "Peanut", "Apple"]
var matches = 0.0;
for(var i in input)
if(this.words.indexOf(input[i]) !== -1) matches+=1;
matches /= input.length;
var key = ""+matches.toFixed(2);
emit(key, {users: [{name: this.name, match: key}]});
}
function reduce(key, value) {
ret = value[0]
for(var i=1; i<value.length; i++){
ret.users = ret.users.concat(value[i].users)
}
return ret
}
db.col.mapReduce(map, reduce, {"out": {inline:1}})
산출:
{
"results" : [
{
"_id" : "0.33",
"value" : {
"users" : [
{
"name" : "Ash",
"match" : "0.33"
},
{
"name" : "Max",
"match" : "0.33"
}
]
}
},
{
"_id" : "0.67",
"value" : {
"users" : [
{
"name" : "Joe",
"match" : "0.67"
}
]
}
}
],
"timeMillis" : 22,
"counts" : {
"input" : 3,
"emit" : 3,
"reduce" : 1,
"output" : 2
},
"ok" : 1
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다