Skip to content

Instantly share code, notes, and snippets.

@justinrainbow
Forked from antirez/compl1.rb
Created April 22, 2011 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save justinrainbow/937387 to your computer and use it in GitHub Desktop.
Save justinrainbow/937387 to your computer and use it in GitHub Desktop.
Redis autocompletion - in php
<?php
# compl1.php - Redis autocomplete example
# download female-names.txt from http://antirez.com/misc/female-names.txt
$redis = new Redis();
$redis->connect('127.0.0.1');
# Create the completion sorted set
if (!$redis->exists('compl')) {
echo "Loading entries in the Redis DB\n";
foreach (file('female-names.txt') AS $n) {
$n = trim($n);
for ($l = 0; $l < strlen($n); $l++) {
$prefix = substr($n, 0, $l);
$redis->zadd('compl', 0, $prefix);
}
$redis->zadd('compl', 0, $n."*");
}
}
else {
echo "NOT loading entries, there is already a 'compl' key\n";
}
# Complete the string "mar"
function complete($redis, $prefix, $count) {
$results = array();
$rangelen = 50; # This is not random, try to get replies < MTU size
$start = $redis->zrank('compl', $prefix);
if (!$start) {
return $results;
}
while (count($results) < $count) {
$range = $redis->zrange('compl', $start, $start+$rangelen-1);
$start += $rangelen;
if (!$range) {
break;
}
foreach ($range AS $entry) {
$minlen = min(strlen($entry), strlen($prefix));
if (substr($entry, 0, $minlen) != substr($prefix, 0, $minlen)) {
$count = count($results);
break;
}
if (substr($entry, -1) == "*" && count($results) !== $count) {
$results[] = substr($entry, 0, -1);
}
}
}
return $results;
};
foreach (complete($redis, "marcell",50) as $res) {
echo $res, "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment