Skip to content

Instantly share code, notes, and snippets.

@nuklehed
Last active February 28, 2020 16:16
Show Gist options
  • Save nuklehed/0de5d0c4dc3822b36a2350c253017dcf to your computer and use it in GitHub Desktop.
Save nuklehed/0de5d0c4dc3822b36a2350c253017dcf to your computer and use it in GitHub Desktop.
PHP version of Mongo fuzzy search
<?php
// This is based on a fuzzy search video of a lecture by John L. Page. I am implementing
// a version for 5.8M records in Mongo for a Laravel PHP app. This is working and should
// port to laravel-mongodb using the "raw" method. Not sure if we could do the same thing
// in Eloquent but it shouldn't matter (would only make it look cleaner!)
$m = new \MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');
/*-- May not be using the proper terminology but it makes sense to me :) --
* 1. Match _id's using $or conditional. This means we only want a result if one of values match.
* 2. For each match, count the number of matches and project it to the 'c' field.
* 3. Take only the documents where 'c' is greater than 1.
* 4. Finally, project those results to documents with just the _id field.
*/
$agg = array(
array( '$match' =>
array( '$or' =>
array( [ '_id' => 'AABERG' ], [ '_id' => 'FILTEAU'] )
)
),
array( '$project' =>
array( 'c' =>
array( '$add' => [
array( '$cond' => [ array( '$eq' => array( '$_id', 'AABERG' ) ), 1, 0 ] ),
array( '$cond' => [ array( '$eq' => array( '$_id', 'FILTEAU' ) ), 1, 0 ] )
])
)
),
array( '$match' =>
array( 'c' =>
array( '$gte' => 1 )
)
),
array( '$project' => array( '_id' => 1 ))
);
// Create the command object for our collection and pipeline
$cmd = new \MongoDB\Driver\Command([
'aggregate' => 'nominals_v2_names',
'pipeline' => $agg
]);
// params: db name, command
$results = $m->executeCommand('people', $cmd);
foreach ($results as $r) {
var_dump($r);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment