2013-04-23 3 views
3

이것은 couchbase에서 처음 시도한 것입니다. 내 json 의사는 다음과 같습니다.couchbase에서 reduce 함수 작성하기

{ 
    "member_id": "12345", 
    "devices": [ 
     { 
      "device_id": "1", 
      "hashes": [ 
       "h1", 
       "h2", 
       "h3", 
       "h4" 
      ] 
     }, 
     { 
      "device_id": "2", 
      "hashes": [ 
       "h1", 
       "h2", 
       "h3", 
       "h4", 
       "h5", 
       "h6", 
       "h7" 
      ] 
     } 
    ] 
} 

주어진 해시에 대한 모든 member_ids를 알려주는보기를 만들고 싶습니다. 이 같은

뭔가 :

h1["12345","233","2323"] //233,2323 are other member id  
h2["12345"] 

member_id가 설정 한 번 나타납니다.

나는지도 기능

function (doc, meta) { 
    for(i=0;i< doc.devices.length;i++) 
    { 
    for(j=0;j< doc.devices[i].hashes.length;j++) { 
     emit(doc.devices[i].hashes[j],null) 
      } 
    } 
} 

을 쓴이

h1 "12345" 
h1 "12345" 
h2 "12345" 
h1 "233" 

를 반환하지만 내가 여기에서 전진 할 수 아니에요. 결과를 줄이려면지도 기능을 어떻게 변경해야합니까?

답변

3

지도 기능. 대부분 당신 것이지만, meta.id을 값으로 내 보냅니다.

function(doc, meta) { 
    for(i=0; i< doc.devices.length; i++) { 
    for(j=0; j< doc.devices[i].hashes.length; j++) { 
     emit(doc.devices[i].hashes[j], meta.id) 
    } 
    } 
} 

감소 기능. 값 (https://stackoverflow.com/a/13486540/98509에서 가져온)에서 유일한 고유 배열을 반환합니까

function(keys, values, rereduce) { 
    return values.filter(function (e, i, arr) { 
    return arr.lastIndexOf(e) === i; 
    }); 
} 
+0

thnx 작동합니다! – harshit