简单实现一个搜索提示

背景

站内搜索是一个网站的基本功能,一个好的搜索提示也能很好的提升用户体验,提高用户找到自己需要的东西的效率

需求

用户输入的时候自动提示,无论输入汉字,拼音,字母都有提示出来

下图是优酷站内搜索的时候弹出的提示
简单实现一个搜索提示_第1张图片

步骤

环境
  1. 安装elasticsearch 6.1.3
  2. 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"
                }
            }
        }
    }
}

用脚本插入数据

'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

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组件

效果如下
简单实现一个搜索提示_第2张图片

你可能感兴趣的:(简单实现一个搜索提示)