简单实现一个搜索提示
背景
站内搜索是一个网站的基本功能,一个好的搜索提示也能很好的提升用户体验,提高用户找到自己需要的东西的效率
需求
用户输入的时候自动提示,无论输入汉字,拼音,字母都有提示出来
下图是优酷站内搜索的时候弹出的提示
步骤
环境
- 安装elasticsearch 6.1.3
- java1.8
创建索引
PUT localhost:9200/vindex
{
"settings":{
"number_of_shards":3,
"number_of_replicas":0
},
"mappings":{
"film":{
"properties":{
"title":{
"type":"text",
"analyzer":"ik_max_word"
},
"title_cn":{
"type":"completion"
},
"title_qpy":{
"type":"completion"
},
"title_spy":{
"type":"completion"
}
}
}
}
}
用脚本插入数据
<?php
include "vendor/autoload.php";
$pinyin = new \Overtrue\Pinyin\Pinyin();
$films = array(
\'摔跤吧!爸爸\',
\'请以你的名字呼唤我\',
\'看不见的客人\',
\'海边的曼彻斯特\',
\'银翼杀手2049\',
\'至暗时刻 \',
\'杰出公民\',
\'天才枪手\',
\'天空之眼\',
\'天才捕手\',
\'天才少女\',
\'The Shape of Water\',
\'Three Billboards Outside Ebbing, Missouri\',
);
foreach($films as $film){
$params = array(
\'index\'=>\'vindex\',
\'type\'=>\'film\',
\'body\'=>array(
\'title\'=>$film,
\'title_cn\'=>$film,
\'title_spy\'=> $pinyin->abbr($film),
\'title_qpy\'=>str_replace(\' \',\'\',$pinyin->sentence($film))
)
);
try {
$client = \Elasticsearch\ClientBuilder::create()->setHosts(array("localhost:9200"))->build();
$client->index($params);
}catch (\Exception $e){
print_r($e);
}
}
运行 php create_index.php
后端用search.php
<?php
include "vendor/autoload.php";
$client = \Elasticsearch\ClientBuilder::create()->setHosts(array("localhost:9200"))->build();
$keyword = $_GET[\'term\'];
//$keyword = \'t\';
$params = array(
\'index\'=>\'vindex\',
\'type\'=>\'film\',
\'body\'=>
array(
\'suggest\'=>
array(
\'title_spy_suggest\'=>array(
\'prefix\'=>$keyword,
\'completion\'=>array(\'field\'=>\'title_spy\',\'skip_duplicates\'=>true,\'size\'=>5),
),
\'title_qpy_suggest\'=>array(
\'prefix\'=>$keyword,
\'completion\'=>array(\'field\'=>\'title_qpy\',\'skip_duplicates\'=>true,\'size\'=>5),
),
\'title_cn_suggest\'=>array(
\'prefix\'=>$keyword,
\'completion\'=>array(\'field\'=>\'title_cn\',\'skip_duplicates\'=>true,\'size\'=>5),
),
),
),
);
$res = $client->search($params);
$search_result = array();
foreach($res[\'suggest\'][\'title_cn_suggest\'][0][\'options\'] as $key=>$value){
array_push($search_result , $value[\'_source\'][\'title\']);
}
foreach($res[\'suggest\'][\'title_spy_suggest\'][0][\'options\'] as $key=>$value){
array_push($search_result , $value[\'_source\'][\'title\']);
}
foreach($res[\'suggest\'][\'title_qpy_suggest\'][0][\'options\'] as $key=>$value){
array_push($search_result , $value[\'_source\'][\'title\']);
}
echo json_encode(array_values(array_unique($search_result)));
前端的话直接用jQuery UI里面的autocomplete组件
效果如下
版权声明:本文为jaychan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。