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

时间:2022-11-24 04:17:21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<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/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script> </head>
<body> <div class="container" style="margin-top: 3em;"> <form method="post" action="/index.php/index/index/getsearch" id="header_search" class="form-inline">
<div class="form-group">
<label for="exampleInputName2">输入搜索关键词试试</label>
<input type="text" class="form-control" id="keyword" name="keyword" value="" autocomplete="off" />
</div>
<div class="form-group">
<input type="submit" value="搜索" class="btn btn-success"/>
</div> </form>
<ul id="header_search_suggest"></ul> </div> <!-- js部分,这部分控制,输入框输入时,进行及时提示的功能 -->
<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, ("<strong>$1</strong>"));
}
suggestItem = suggestItem + "<em> - " + json[index]._type + ' * ' + json[index]._id + "</em>";
//遍历出每一条返回的数据
lists += "<li class='listName' ><a href='/index.php/index/index/search?id=" + json[index]._id + "&key=" + encodeURI(searchContent + ' - ' + json[index]._type) + "'>" + suggestItem + "</a></li>";
}); $("#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 .= '<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/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>'; $str .= '<table class="table table-hover">
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>content</th>
</tr>
</thead>
<tbody>'; foreach ($list as $k => $v) {
$str .= '<tr><td>' . $v['_source']['id'] . '</td><td>' . $v['_source']['title'] . '</td><td>' . $v['_source']['content'] . '</td></tr>';
}
$str .='</tbody></table>';
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;
}

最终效果

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

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