Autocomplete with Redis


/ Published in: PHP
Save to your folder(s)

PHP implementation of antirez\\\'s Redis autocompletion in Ruby. (http://antirez.com/post/autocomplete-with-redis.html)\\r\\nUsing Php Redis extension available here : http://github.com/owlient/phpredis


Copy this code and paste it in your HTML
  1. <?php
  2. $redis = new Redis();
  3. $redis->connect("db", 6379);
  4.  
  5. if(!$redis->exists(":compl")) {
  6. echo "Loading entries in the Redis DB\n";
  7. $file = file("female-names.txt");
  8. foreach($file as $line) {
  9. $line = trim($line);
  10. for($i=0 ; $i < strlen($line); $i++) {
  11. $prefix = substr($line, 0, $i);
  12. $redis->zAdd(":compl", 0,$prefix);
  13. }
  14. $redis->zAdd(":compl", 0, $line . "*");
  15. }
  16. } else {
  17. echo "NOT loading entries, there is already a 'compl' key \n";
  18. }
  19.  
  20. function complete($redis, $prefix, $count) {
  21. $results = array();
  22. $rangeLen = 50;
  23. $start = $redis->zRank(":compl", $prefix);
  24. if(!$start) {
  25. return $results;
  26. }
  27.  
  28. while(count($results) != $count) {
  29. $range = $redis->zRange(":compl", $start, $start+$rangeLen-1);
  30. $start += $rangeLen;
  31. if(!$range || count($range) == 0) {
  32. break;
  33. }
  34. foreach($range as $entry) {
  35. $minLen = min(strlen($entry), strlen($prefix));
  36. if(substr($entry, 0, $minLen) != substr($prefix, 0, $minLen)) {
  37. $count = count($results);
  38. }
  39. if(substr($entry, -1) == "*" && count($results) != $count) {
  40. $results[] = substr($entry, 0, -1);
  41. }
  42. }
  43. }
  44.  
  45. return $results;
  46. }
  47.  
  48. $results = complete($redis, "marcell", 50);
  49. foreach($results as $res) {
  50. echo $res . "\n";
  51. }

URL: redis-autcomplete

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.