-
-
Save justinrainbow/937387 to your computer and use it in GitHub Desktop.
Redis autocompletion - in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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