4

This is my first attempt at couchbase. My json doc looks like this:

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

I want to create a view which tells me all member_ids for a given hash.

Something like this:

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

The member_id should appear once in the set.

I wrote a map function

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)
          }
  }
}

and this returns

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

but I'm not able to move forward from here. How should I change my map function to reduce the result?

0

1 Answer 1

5

Map function. Mostly yours, but emits meta.id as a value.

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)
    }
  }
}

Reduce function. Is just return unique array from values (taken from https://stackoverflow.com/a/13486540/98509)

function(keys, values, rereduce) {
  return values.filter(function (e, i, arr) {
    return arr.lastIndexOf(e) === i;
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.