Skip to content

Instantly share code, notes, and snippets.

@bobbytables
Created April 20, 2011 17:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobbytables/931994 to your computer and use it in GitHub Desktop.
Save bobbytables/931994 to your computer and use it in GitHub Desktop.
We needed a way to Map/Reduce our search queries in CakePHP shells. This is our result. Built off of the incredible plugin, https://github.com/ichikaway/cakephp-mongodb
<?php
public function startup(){
App::import('Datasource', 'Mongodb.Mongodb');
$this->mongo = ConnectionManager::getDataSource($this->SearchLog->useDbConfig);
}
public function main(){
$map = 'function () { emit(this.slug, {count:1}); }';
$reduce = 'function (key, values) { var count = 0; values.forEach(function (v) {count += v.count;}); return count; }';
$map = new MongoCode($map);
$reduce = new MongoCode($reduce);
$this->mongo->ensureIndex($this->SearchLog, array('slug' => 1));
$this->out('Grouping search results into occurences...');
$start = microtime(true);
$this->mongo->mapReduce(array(
'mapreduce' => $this->SearchLog->table,
'map' => $map,
'reduce' => $reduce,
'out' => 'popular_searches' // Mongo will drop this collection and re-populate it (unless specified otherwise)
));
$this->out('Done!');
$this->out('Took '.(microtime(true) - $start).' seconds');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment