[MongoDB] ๋งต๋ฆฌ๋์ค(map reduce)
๋งต๋ฆฌ๋์ค๋ ์ด๋ํ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๊ธฐ ์ํ ๋ฐฉ๋ฒ๋ก ์ด๋ค.
๋ํ์ ์ธ ๋งต๋ฆฌ๋์ค ์ ์ฉ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์์คํ
์ผ๋ก๋ Hadoop์ด ์๋๋ฐ, ๋ชฝ๊ณ DB๋ ์ ํ์ ์ด์ง๋ง ์ด๋ฌํ ๋ฐฉ๋ฒ์ ์ ๊ณตํ๋ค.
ํ๋ก์ฒ๋ผ ๋์คํฌ์ ์ ์ฌ๋ผ๊ฐ์ง๋ ์๋ ์ด๋ํ ๋ฐ์ดํฐ๋ฅผ ๋ค๋ฃจ๋๋ฐ๋ ํ๊ณ๊ฐ ์์ง๋ง, ๋ญ๊ฐ ๊ทธ ์๋์ ์ ๋งคํ ์ง์ ์์๋ ๋์์ผ๋ก ์ฌ์ฉํ ๋งํ๋ค.
mongodb 5.0๋ถํฐ๋ ์ด๊ฒ ๋์ aggregation-pipeline์ ์ฌ์ฉํ๋ ๊ฒ์ ๊ถ์ฅํ๋ค. ๊ทธ์ชฝ์ด ๋ ๋น ๋ฅด๊ณ ์ต์ ํ๋ ์ ๋๋ค๊ณ ํ๋ค.
๊ตฌ์กฐ
map reduce๋ ํฌ๊ฒ 3๊ฐ์ง ๊ตฌ์ฑ์์๋ก ์ด๋ฃจ์ด์ง๋ค.
๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋ ์กฐ๊ฑด์ธ query, ์ต์ด ๋ฐ์ดํฐ๋ฅผ ๊ฐ๊ณตํ๋ map, ๋ฐ์ดํฐ๋ฅผ ๊ทธ๋ฃจํํด์ ์ถ์ํ๋ reduce๋ค.
์๋๋ ๊ทธ ์์๋ค.

์ง์ ํ๋ฒ ํด๋ณด์.
์ฐ์ ์๋์ ๊ฐ์ด ๋ฐ์ดํฐ ์ธํ
์ ํ๋ค.
db.orders
// random datas
// random datas
db.orders.insertMany([
{
buyer_id: 1,
product_id: 154,
price: 200,
quantity: 5,
date: new Date("2014-03-01T08:00:00Z"),
},
{
buyer_id: 2,
product_id: 155,
price: 150,
quantity: 2,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 3,
product_id: 156,
price: 5500,
quantity: 1,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 4,
product_id: 157,
price: 440,
quantity: 1,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 5,
product_id: 158,
price: 510,
quantity: 1,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 1,
product_id: 159,
price: 520,
quantity: 1,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 3,
product_id: 1999,
price: 100,
quantity: 1,
date: new Date("2014-03-01T08:00:00Z"),
},
{
buyer_id: 3,
product_id: 155,
price: 150,
quantity: 2,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 3,
product_id: 44,
price: 50,
quantity: 14,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 4,
product_id: 12,
price: 330,
quantity: 1,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 5,
product_id: 14,
price: 140,
quantity: 3,
date: new Date("2014-03-01T09:00:00Z"),
},
{
buyer_id: 1,
product_id: 1500,
price: 52,
quantity: 4,
date: new Date("2014-03-01T09:00:00Z"),
},
]);

๊ทธ๋ฆฌ๊ณ ๊ตฌ๋งค์(buyer_id)๋ฅผ ๊ธฐ์ค์ผ๋ก ํด์ ์ด ์ผ๋ง๋ ๋์ ์ผ๋์ง ๊ตฌํ๋ ๋งต๋ฆฌ๋์ค๋ฅผ ๊ตฌํํด๋ดค๋ค.
db.orders.mapReduce(
function () {
emit(this.buyer_id, { price: this.price, quantity: this.quantity });
},
function (key, values) {
return values.reduce((acc, curr) => acc + curr.price * curr.quantity, 0);
},
{ out: "temp" }
);
์ฒซ๋ฒ์งธ ์ธ์์ธ map์์๋, emit์ผ๋ก reduce์ ๋ณด๋ผ key-value ์์ ๋ณด๋ธ๋ค.
๊ทธ๋ฆฌ๊ณ ๋๋ฒ์งธ ์ธ์๋ reduce์์๋ ๊ฐ ํค๋ณ๋ก ๊ฐ์ ์ด๋ป๊ฒ aggregateํ ์ง๋ฅผ ๊ตฌํํ๋ค. ์ฌ๊ธฐ์๋ ๊ฐ ๊ตฌ๋งค ๊ธ์ก์ ๋จ๊ฐ*๊ฐ์๋ก ๊ณฑํด์ ์ ๋ถ ๋ํ๋๋ก ํ๋ค.
์ธ๋ฒ์งธ ์ธ์์์ out์ ๊ฒฐ๊ณผ๋ฌผ์ ์ ์ฅํ collection๋ช
์ ์ง์ ํ๋ค.
์ ๋๋ก ์คํํ๋ฉด
์ด๋ ๊ฒ ์ ์ปฌ๋ ์
์ ํตํด ์กฐํ๊ฐ ๊ฐ๋ฅํด์ง ๊ฒ์ด๋ค.
์ด๋ฐ ์์ผ๋ก ์ฐ๋ฉด ๋๋ค.