MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Il tuo primo Map-Reduce in MongoDB: un esempio guidato

Ho messo insieme qualcosa che credo faccia ciò che vuoi. Potrebbe non essere esatto, perché non sono sicuro al 100% del tuo schema; i tuoi esempi mostrano refer disponibile nel tipo a ma non nel b, e non so se sia una svista. In ogni caso, ecco il mio tentativo.

La funzione map:

function() { var obj = { "types": {}, "tags": {} } obj.types[this.type] = 1; if (this.tags) { for (var tag in this.tags) { obj.tags[this.tags[tag]] = 1; } } emit(this.refer.url, obj); } 

La funzione reduce:

function(key, values) { var obj = { "types": {}, "tags": {} } for (var i = 0; i < values.length; i++) { for (var type in values[i].types) { if (!type in obj.types) { obj.types[type] = 0; } obj.types[type] += values[i].types[type]; } for (var tag in values[i].tags) { if (!tag in obj.tags) { obj.tags[tag] = 0; } obj.tags[tag] += values[i].tags[tag]; } } return obj; } 

Ecco come funziona. La funzione map usa refer.url come chiave (la mia ipotesi in base alla tua descrizione), quindi il risultato finisce con _id uguale all'URL del referrer, raggruppato per URL. Ogni valore emesso è un oggetto con due sotto-oggetti, types e tags, strutturati in modo identico così che map e reduce parlino lo stesso formato.

Ora colleghiamolo in PHP (assumendo che $map e $reduce contengano le funzioni qui sopra):

$mapFunc = new MongoCode($map); $reduceFunc = new MongoCode($reduce); $query = array( 'time' => array('$gte' => time() - (60*60*60*24*30)), 'refer.external' => true ); $collection = 'visits'; $command = array( 'mapreduce' => $collection, 'map' => $mapFunc, 'reduce' => $reduceFunc, 'query' => $query, ); $statsInfo = $db->command($command); $statsCollection = $db->selectCollection($sales['result']); $stats = $statsCollection->find(); foreach ($stats as $stat) { echo $stats['_id'] . ' Visited '; foreach ($stats['value']['types'] as $type => $times) { echo "Type $type $times Times, "; } foreach ($stats['value']['tags'] as $tag => $times) { echo "Tag $tag $times Times, "; } echo "\n"; } 

Nota che non ho testato tutto questo. È semplicemente ciò che ho escogitato leggendo il tuo schema e l'implementazione map-reduce di MongoDB, quindi trattalo come un punto di partenza da adattare.