Return to Snippet

Revision: 31880
at September 15, 2010 04:56 by Mikushi


Initial Code
<?php
$redis = new Redis();
$redis->connect("db", 6379);

if(!$redis->exists(":compl")) {
	echo "Loading entries in the Redis DB\n";
	$file = file("female-names.txt");
	foreach($file as $line) {
		$line = trim($line);
		for($i=0 ; $i < strlen($line); $i++) {
			$prefix = substr($line, 0, $i);
			$redis->zAdd(":compl", 0,$prefix);
		}
		$redis->zAdd(":compl", 0, $line . "*");
	}
} else {
	echo "NOT loading entries, there is already a 'compl' key \n";
}

function complete($redis, $prefix, $count) {
	$results = array();
	$rangeLen = 50;
	$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 || count($range) == 0) {
			break;
		}
		foreach($range as $entry) {
			$minLen = min(strlen($entry), strlen($prefix));
			if(substr($entry, 0, $minLen) !=  substr($prefix, 0, $minLen)) {
				$count = count($results);
			}
			if(substr($entry, -1) == "*" && count($results) != $count) {
				$results[] = substr($entry, 0, -1);
			}
		}
	}

	return $results;
}

$results = complete($redis, "marcell", 50);
foreach($results as $res) {
	echo $res . "\n";
}

Initial URL
redis-autcomplete

Initial Description
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

Initial Title
Autocomplete with Redis

Initial Tags

                                

Initial Language
PHP