2

I am trying to work out the map functions and reduce functions for the following case:

documents:

{
 "_id" : "1_A",
 "key1": 10,
 "key2": 10
}

{
 "_id" : "2_A",
 "key1": 2,
 "key2": 3
}
{
 "_id" : "1_B",
 "key1": 20,
 "key2": 20
}

{
 "_id" : "2_B",
 "key1": 1,
 "key2": 0
}

etc.

expecting to have: the sum of each key (key1, key2... keyn) in all documents with id ends with "_A", "_B" ... "_Z" individually.

in this case, expecting to have sumA: "key1":12, "key2":13. and sumB: "key1":21, "key2":20;

I have been working on the map function(doc), it seems like to me that the it is only to deal with one document which specified as the "doc" value at a time.

Is there anyway to achieve the result as expected? is there anyway like SQL join???

1
  • was my answer helpful to you? or do you need more information i.e. I was not giving enough details? Commented Jul 30, 2013 at 8:01

1 Answer 1

1

yes, this is possible! You will have to emit a compound key here, like this: ["A", 1] for the value of key in a document with an id ending with A.

example for map:

function (doc) {
    for (var k in doc) {
        if (k !== '_id' && k !== 'rev') {
            emit([doc._id.substr(doc._id.length - 1), k.substr(k.length - 1)], 
                doc[k]);
        }
    }
}

For reduce you want to use the builtin function _sum for performance.

You can then query these sums using group=true as URL parameter, possibly restricting the values to only those with suffix A by using startkey and endkey (e.g. ["A"] and ["A", {}]).

In this case the result would be:

{"rows":[
    {"key":["A","1"],"value":12},
    {"key":["A","2"],"value":13},
    {"key":["B","1"],"value":21},
    {"key":["B","2"],"value":20}
]}
Sign up to request clarification or add additional context in comments.

1 Comment

it helps, and now I have got another question which is the consequence of this question: pls have a look stackoverflow.com/questions/18079917/…

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.