Skip to content

Instantly share code, notes, and snippets.

@showsky
Last active April 3, 2019 05:09
Show Gist options
  • Select an option

  • Save showsky/c852ed394146be6cbc5953b11628cfef to your computer and use it in GitHub Desktop.

Select an option

Save showsky/c852ed394146be6cbc5953b11628cfef to your computer and use it in GitHub Desktop.
Redis + PHP = AutoComplete
<?php
function init_suggest() {
$redis = new Redis();
$redis->pconnect('127.0.0.1', 6379);
$redis->delete('autocomplete');
$keyword = array(
'全境封鎖',
'火線獵殺',
'煞爾達'
);
$size = count($keyword);
for ($i = 0; $i < $size; $i++) {
$result = _str_combination($keyword[$i]);
foreach ($result as $value) {
$redis->zAdd('autocomplete', 0, $value);
}
}
}
function _str_combination($keyword) {
$size = mb_strlen($keyword);
for ($i = 0; $i < $size; $i++) {
$result[] = mb_substr($keyword, 0, $i + 1);
}
$result[$size - 1] = $result[$size - 1] . '*';
return $result;
}
public function autocomplete($keyword) {
$keyword_size = mb_strlen($keyword);
$redis = new Redis();
$redis->pconnect('127.0.0.1', 6379);
$search_index = $redis->zRank('autocomplete', $keyword);
$search = $redis->zRange('autocomplete', $search_index, -1);
$result = array();
foreach ($search as $value) {
if ( ! (mb_substr($value, 0, $keyword_size) == $keyword)) {
continue;
}
if (mb_substr($value, -1) == '*') {
$result[] = mb_substr($value, 0, mb_strlen($value) - 1);
}
}
return $result;
}
@showsky
Copy link
Copy Markdown
Author

showsky commented Apr 3, 2019

執行 init_suggest() 把關鍵字拆解排列,並增加到 Redis sorted set 結構去,配合 ZRAND 找到字首的 index,並配合 ZRANGE 就可以取出範圍,每個 entry 遇到 * 就是完整的關鍵字

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment