搜索關(guān)鍵字,使結(jié)果高亮關(guān)鍵字,類(lèi)似百度搜索結(jié)果一樣,如下圖。
關(guān)鍵字高亮.png
在PHP中,調(diào)用elasticsearch進(jìn)行搜索時(shí),想讓結(jié)果高亮顯示,添加參數(shù)highlight
,在其下的field
中,添加需要高亮的字段,之前寫(xiě)成'content => []'
,沒(méi)有返回高亮結(jié)果。
后來(lái)通過(guò)搜索查詢相關(guān)問(wèn)答網(wǎng)站,才知道需要將類(lèi)型數(shù)組轉(zhuǎn)換為對(duì)象,如'content' => new \stdClass()
。
public function search()
{
$hosts = ['127.0.0.1:9200'];
$clientBuilder = ClientBuilder::create(); // Instantiate a new ClientBuilder
$clientBuilder->setHosts($hosts); // Set the hosts
$client = $clientBuilder->build(); // Build the client object
//Set search params
$params = [
'index' => 'index',
'type' => 'fulltext',
'body' => [
'query' => [
'term' => [
'content' => '中國(guó)'
]
],
'highlight' => [
'pre_tags' => ["<em>"],
'post_tags' => ["</em>"],
'fields' => [
"content" => new \stdClass()
]
]
]
];
$response = $client->search($params);
print_r($response);
}
返回的結(jié)果如下,查詢關(guān)鍵字“中國(guó)”,返回的結(jié)果中,在highlight
中,標(biāo)簽<em>高亮包含了“中國(guó)”:
Array
(
[took] => 2
[timed_out] =>
[_shards] => Array
(
[total] => 5
[successful] => 5
[failed] => 0
)
[hits] => Array
(
[total] => 2
[max_score] => 1.5
[hits] => Array
(
[0] => Array
(
[_index] => index
[_type] => fulltext
[_id] => 4
[_score] => 1.5
[_source] => Array
(
[content] => 中國(guó)駐洛杉磯領(lǐng)事館遭亞裔男子槍擊 嫌犯已自首
)
[highlight] => Array
(
[content] => Array
(
[0] =>
<em>中國(guó)</em>駐洛杉磯領(lǐng)事館遭亞裔男子槍擊 嫌犯已自首
)
)
)
[1] => Array
(
[_index] => index
[_type] => fulltext
[_id] => 3
[_score] => 0.53699243
[_source] => Array
(
[content] => 中韓漁警沖突調(diào)查:韓警平均每天扣1艘中國(guó)漁船
)
[highlight] => Array
(
[content] => Array
(
[0] => 中韓漁警沖突調(diào)查:韓警平均每天扣1艘
<em>中國(guó)</em>漁船
)
)
)
)
)
)