éãªã¬ã¼ã·ã§ãã«ãã¼ã¿ãã¼ã¹ãçµåæ¼ç®ãæ±ããªããããã¨ãã誤解ã解ãã
ææ¥ã®åå¼·ä¼ã®æºåããã¦ããããä»åã®æ¬ã®ç¯å²å¤ã§ãããã¡ããã¨ã¾ã¨ãã¦ãããªãã¨ãã¨ããã¨ãããæãåºããã®ã§æ¸ãã¦ããã¾ããã ãã¶åã«æ¸ããæ°ãããªãã§ããªããã©ã
CouchDBã§ã¯MapReduceã工夫ãããã¨ã§é¢ä¿ã¢ãã«ã®çµåæ¼ç®ãæ±ãã¾ãããªããKVSã¨ä¸ç·ããã«ããã¦ãJOINãã§ããªããããã ã®ãªãã ã®ãããã¾ãããSQLã®é¢ä¿æ¼ç®ã®æ¬è³ª(? ... ããç¥ããªããã©)ãè¦æ¥µãã¦ããã°ãCouchDBã®MapReduceã§ããããã®æ¼ç®ãã§ãã¾ãã
ã¨ãã話ãã ã£ããéãªã¬ã¼ã·ã§ãã«ãã¼ã¿ãã¼ã¹ã£ã¦ãããªããã¨ãã話ã¯æãã§ããã ã£ã¦ãªã¬ã¼ã·ã§ãã«ãã¼ã¿ãã¼ã¹ã£ã¦ããã¨ããã©ããããã¨ã«ãªããã ãã®ã
ã¾ãã¯æ®éã«å¤é¨çµå
ããã°ã¨ã³ããªã¨ããã°ã®ã³ã¡ã³ãã®ãªã¬ã¼ã·ã§ã³ãã ã¨ã¨ã³ã¿ã¼ãã©ã¤ãºè³ã®äººãç´å¾ããªããããªã®ã§ãåå¼ä¼ç¥¨ã¨åå¼æç´°ã§ããã¾ãã
ã¾ãã¯ãåå¼ä¼ç¥¨
{ "_id": "order1" "title": åå¼1", "description" : "..." "type": "Order" }
ã§ãæç´°ã
{ "_id" : "....", "name" : "ããã", "unit_price": 180, "num" : 5, "type" : "OrderDetail", "order_id" : "order1" }
{ "_id" : "....", "name" : "ã¿ãã", "unit_price": 140, "num" : 7, "type" : "OrderDetail", "order_id" : "order1" }
{ "_id" : "....", "name" : "ã¶ã©ã", "unit_price": 880, "num" : 2, "type" : "OrderDetail", "order_id" : "order1" }
ãããªæããããã«ããªã¬ã¼ã·ã§ãã«ãã§ãæ¬ç©ã®ä¼ç¥¨ãä½ãã¨ãã«ã¯ã次ã®ããã«MapReduce(ã®Map)ãã¾ãã
function(doc){ if( doc.type == "Order") { emit([doc._id, 0], doc); } if( doc.type == "OrderDetail") { emit([doc.order_id, 1, doc.name], doc); } }
ããããã¨æ¬¡ã®ãããªè¡¨ãã§ããããã®ã§ãã
order_id | ç¨®é¡ | ååå | ãã¼ã¿ |
---|---|---|---|
"order1" | 0 | undefined | Orderããã¥ã¡ã³ã |
"order1" | 1 | ã¶ã©ã | OrderDetailããã¥ã¡ã³ã |
"order1" | 1 | ã¿ãã | OrderDetailããã¥ã¡ã³ã |
"order1" | 1 | ããã | OrderDetailããã¥ã¡ã³ã |
"order2" | 0 | undefined | Orderããã¥ã¡ã³ã |
"order2" | 1 | XXXX | OrderDetailããã¥ã¡ã³ã |
"order2" | 1 | XXXX | OrderDetailããã¥ã¡ã³ã |
"order2" | 1 | XXXX | OrderDetailããã¥ã¡ã³ã |
"order3" | 0 | undefined | Orderããã¥ã¡ã³ã |
... | ... | ... | ... |
order_id <-> ååå ã®éã¯Keyã§ãã
ãããã£ã¦ãOrder._id = OrderDetail.order_id 㧠LEFT OUTER JOINãå®è¡ããã«ã¯ãstartkey=["order1",0]&endkey=["order1", 1, "\u9999"] ã¨æå®ãã¾ãã
ã¤ã¾ããé
åãkeyã«è©¦ç¨ãã¦ãå
é è¦ç´ ããNåç®ã¾ã§ãJOINãã¼ã«ãããã¨ãã§ãã(ãã®å ´åN=1)ãã§ããCouchDBã§ã¯emit(k,v)ã§ç»é²ããkã®å¤ã¯B+-Treeã«æ ¼ç´ããã¾ããã»ãã主ãã¼ã¨å¤é¨ãã¼ã«RDBã§ã¤ã³ããã¯ã¹å¼µãã®ã¨å¤ãããªãã
Reduceã§è¨ç®ããã
ã¨ããã§ãOrderã®éé¡ã®åè¨ãåºãã«ã¯
SUM({OrderDetail}.num * OrderDetail.unit_price)
ããªããã°ãªãã¾ãããããã¯ç°¡åã§ãããreduceã«æ¬¡ã®ãã®ãå®ç¾©ãã¦ããã°OKã
function(ks, vs, rr){ if( rr ){ return sum(vs); }else{ var s = 0; for(var i in vs){ var doc = vs[i]; if( doc.type == "OrderDetail") { s += doc.unit_price * doc.num; } } return s; } }
ãå¾æããã«ã¯10%å¼ãã§
Orderããã¥ã¡ã³ãã«ãå¾æãããã¼ã¯ãã¤ãã¦ããã10%OFFã«ãã¾ãããããã¨ããã®ã¯å°ãé£ããã§ãããããCouchDBã®MapReduceã«è½ã¨ãè¾¼ãããã§ããã°ããªããRelax Goldã§ãã
çãã¯ã¾ãå¾ã§ããã³ãã¯Reduceã交æå¾(è¨æ£)çµåå¾ãæºããæ¼ç®ã«ãªãããã«æ¼ç®åã¨å¼ãã¢ãã«åãããa * (b + c + d + ...) != (a * b) + c + d + ... ãªã®ã§ã©ããããããã§ãããããã¨ããã®ããã³ãã§ããããã
ã§ãã
JOINãã§ããã£ã¦ãããªã«éè¦ãªãã¨ã ã¨ã¯æããªããã§ãã....ã ããå½åã¯éãªã¬ã¼ã·ã§ãã«ã£ã¦ãã¨ã§ã