標籤:style blog color os io for ar cti
mongodb的MapReduce主要包含兩個方法:map和reduce。
舉個例子,假設現在有下面3條記錄
{ "_id" : ObjectId("4e5ff893c0277826074ec533"), "x" : [ "a", "b" ] }{ "_id" : ObjectId("4e5ff893c0277826074ec534"), "x" : [ "b", "c" ] }{ "_id" : ObjectId("4e5ff893c0277826074ec535"), "x" : [ "c", "d" ] }
map方法調用emit方法,返回索引值對,鍵是x[i]的值,比如a; 值是1。
function () { for (var i = 0; i < this.x.length; i++) { emit(this.x[i], 1); }}
reduce方法負責把索引值對進行統計。
function (key, values) { var sum = 0; for (var i = 0; i < values.length; i++) sum += values[i]; return sum;}
執行結果如下
{ "_id" : "a", "value" : 1 }{ "_id" : "b", "value" : 2 }{ "_id" : "c", "value" : 2 }{ "_id" : "d", "value" : 1 }
假設map和reduce方法分別存放在map.js和reduce.js中,可以通過下面的代碼獲得mapreduce結果。
MapReduceResults<ValueObject> results = mongoOperations.mapReduce("jmr1", "classpath:map.js", "classpath:reduce.js", ValueObject.class);for (ValueObject valueObject : results) { System.out.println(valueObject);}
輸出是
ValueObject [id=a, value=1.0]ValueObject [id=b, value=2.0]ValueObject [id=c, value=2.0]ValueObject [id=d, value=1.0]
ValueObject代碼
public class ValueObject { private String id; private float value; public String getId() { return id; } public float getValue() { return value; } public void setValue(float value) { this.value = value; } @Override public String toString() { return "ValueObject [id=" + id + ", value=" + value + "]"; }}
可以增加一個MapReduceOptions來增加一些map-reduce的options,下面把結果存入collection。
MapReduceResults<ValueObject> results = mongoOperations.mapReduce("jmr1", "classpath:map.js", "classpath:reduce.js", new MapReduceOptions().outputCollection("jmr1_out"), ValueObject.class);
MapReduceOptions也可以通過靜態方法options()來執行個體化。
MapReduceResults<ValueObject> results = mongoOperations.mapReduce("jmr1", "classpath:map.js", "classpath:reduce.js", options().outputCollection("jmr1_out"), ValueObject.class);
還可以加入一個query來對統計進行過濾,下面是把包含a和b的document排除在外。
Query query = new Query(where("x").ne(new String[] { "a", "b" }));MapReduceResults<ValueObject> results = mongoOperations.mapReduce(query, "jmr1", "classpath:map.js", "classpath:reduce.js", options().outputCollection("jmr1_out"), ValueObject.class);