- In Couch database a view is a combination of map and reduce function.
- In my previous post(link) we have seen how to create a custom map function.In this post we will see about reduce function.
- reduce function is used on each unique key of the result set of map function .It summarizes the result of map function and produces the specific result.
- In this demo, “a reduce function is created on student database.It collects all the fees of each student and returns the sum of fees .”
- a student object properties in futon,
- A map function getAllStudent returns the properties of student objects with keys,
function(document) {
atudent = {
name : document.name,
marks : document.marks,
roll : document.roll,
course : document.course,
fees : document.fees
};
emit(document.roll, atudent );
}
- The corresponding reduce function which sums up all the fees and returns it,
function(key, values, rereduce) {
var totalMoney = 0,
studentList = new Array();
for(i=0; i < values.length; i++) {
totalMoney += values[i].fees;
}
return ("sum",totalMoney );
}
- The Futon view of (map,reduce) combination is,
- Map Function result futon view,
- Map Function result JSON view ,
{ "offset" : 0,
"rows" : [ { "id" : "326e49164d9b414a6c1ce2c8a802d28e",
"key" : 3,
"value" : { "course" : "BTECH",
"fees" : 345,
"marks" : 80,
"name" : "sumanta",
"roll" : 3
}
},
{ "id" : "326e49164d9b414a6c1ce2c8a802d175",
"key" : 4,
"value" : { "course" : "BTECH",
"fees" : 345,
"marks" : 75,
"name" : "sandeep",
"roll" : 4
}
},
{ "id" : "1a508cb01eab7f1ea315551a9703c20b",
"key" : 5,
"value" : { "course" : "MSC",
"fees" : 467,
"marks" : 267,
"name" : "bapi",
"roll" : 5
}
},
{ "id" : "326e49164d9b414a6c1ce2c8a802dda1",
"key" : 7,
"value" : { "course" : "SSC",
"fees" : 123,
"marks" : 95,
"name" : "sangeeta",
"roll" : 7
}
},
{ "id" : "326e49164d9b414a6c1ce2c8a802f200",
"key" : 7,
"value" : { "course" : "MSC IT",
"fees" : 321,
"marks" : 73,
"name" : "Surabhi",
"roll" : 7
}
},
{ "id" : "1a508cb01eab7f1ea315551a9703c5cf",
"key" : 45,
"value" : { "course" : "BTECH",
"fees" : 567,
"marks" : 345,
"name" : "Dilip",
"roll" : 45
}
}
],
"total_rows" : 6
}
- Reduce Function result futon view(reduce check box selected),
- Reduce Function result as JSON object,
{"rows":[
{"key":null,"value":2168}
]}
- The Design view of the document for the getAllStudent,