微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用ElasticSearch实现搜索时即时提示与全文搜索功能

<!DOCTYPE html><html lang="en"><head>
    <Meta charset="UTF-8">
    <title>Documenttitle>
    <style>#header_search_suggest{
    position: absolute;
    width: calc(100% - 10px);
    left: 4px;
    border: solid 1px #ccc;
    background-color: white;
    text-align: left;
    z-index: 101;
    display: block;}#header_search_suggest li{
    font-size: 14px;
    border-bottom: 1px solid #eeeeee;}#header_search_suggest li a{
    padding:0.5em 1em;
    color:#333333;
    display: block;
    text-decoration: none;}#header_search_suggest li a:hover{
    background-color: #EDF0F2;
    color:#2F7EC4;}#header_search_suggest li a em{
    font-style: italic;
    color:#999;
    font-size:0.8em;}.btn{width: 7em;}

    style><script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">script> 最新版本的 Bootstrap 核心 CSS 文件 --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> 最新的 Bootstrap 核心 JavaScript 文件 --><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js">script>head><body>
       
        输入搜索关键词试试

                 

     

<script>var xhr = null; $('#keyword').bind('input propertychange', function () {    if (xhr) {        xhr.abort();//如果存在ajax的请求,就放弃请求    }    var inputText = $.trim(this.value);    if (inputText != "") { //检测键盘输入的内容是否为空,为空就不发出请求        xhr = $.ajax({            type: 'POST',            url: '/index.PHP/index/index/search',//注意这里输入框输入进行及时提示方法与action方法不同            cache: false,//不从浏览器缓存中加载请求信息            // data: "keyword=" + inputText,            data: {keyword: inputText},            dataType: 'json',            success: function (json) {                //console.log(json);  json是返回的json数据                if (json.count != 0) {                    //检测返回的结果是否为空                    var lists = "";                   // console.log(json[0]._source.title);
            //由于返回多条数据,进行each遍历

                   $.each(json, function (index, obj) {               //返回多条数据,index是第几条,obj是内容                        //处理高亮关键词(这里是输入关键词自动出现的列表的样式)                        console.log(json[index]._source.title);                        var searchContent = json[index]._source.title;//标题                        var suggestItem = '';                        if (searchContent.toLowerCase().indexOf(inputText.toLowerCase()) > -1) {                            var searchRegExp = new RegExp('(' + inputText + ')', "gi");                            suggestItem = searchContent.replace(searchRegExp, ("$1"));                        }                        suggestItem = suggestItem + " - " + json[index]._type + ' * ' + json[index]._id + "";                        //遍历出每一条返回的数据                        lists += "

  • <a href='/index.PHP/index/index/search?id=
" + json[index]._id + "&key=" + encodeURI(searchContent + ' - ' + json[index]._type) + "'>" + suggestItem + "";                    });                    $("#header_search_suggest").html(lists).show();//将搜索到的结果展示出来                } else {                    $("#header_search_suggest").hide();                }                //记录搜索历史记录                $.post('/index.PHP/index/index/savesearchlog',{keyword: inputText,count: json.count});            }        });    } else {        $("#header_search_suggest").hide();//没有查询结果就隐藏搜索框    } }).blur(function () {    setTimeout('$("#header_search_suggest").hide()',500);//输入框失去焦点的时候就隐藏搜索框,为了防止隐藏过快无法点击,设置延迟0.5秒隐藏});script>body>html>

以上是html部分,下面是PHP部分

 public function getsearch(){
//这个方法是表单点击搜索时action提交的方法        $client = ClientBuilder::create()->build();        $keys = Request::instance()->param('keyword');        $keys = $keys ? $keys : '测试';        $params = [            'index' => 'article_index',
            'type' => 'article_type',
            'body' => [                'query' => [                    'match' => [                        'content' => $keys
                    ]
                ]
            ]
        ];        $response = $client->search($params);        $str = '';        $list = $response['hits']['hits'];        //pp($list);die;
        $str .= '';                
        $str .= 'idtitlecontent';        foreach ($list as $k => $v) {            $str .= '' . $v['_source']['id'] . '' . $v['_source']['title'] . '' . $v['_source']['content'] . '';
        }        $str .='';        return $str;
        
    }    public function search() {
//这部分方法是ajax 在搜索框输入文字时进行提示方法        /*$client = ClientBuilder::create()->setHosts($hosts)->build();*/
        //实例化es类;在项目中引入自动加载文件,并且实例化一个客户端:
        $client = ClientBuilder::create()->build();        $keys = Request::instance()->param('keyword');//tp5方法获取get post数据自动辨别        $keys = $keys ? $keys : '6';        $params = [            'index' => 'article_index',
            'type' => 'article_type',
            'body' => [                'query' => [                    'match' => [                        'content' => $keys
                    ]
                ]
            ]
        ];        $response = $client->search($params);         return json($response['hits']['hits']);        //pp($response['hits']['hits']);
        die;
}

最终效果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐