PHP ES高亮
隨著WEB技術的不斷發展,各種WEB應用在人們的生活中越來越常見。在WEB應用的開發中,PHP是一種非常流行的編程語言。而Elasticsearch作為一個分布式搜索引擎,也被越來越多的人所認識。在PHP開發中,如果需要使用Elasticsearch作為搜索引擎,那么就需要用到PHP ES高亮。
<?php
require_once 'Elasticsearch/vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->build();
$search_param = [
'index' =>'index',
'type' =>'type',
'from' =>($page - 1) * $size,
'size' =>$size,
'body' =>[
'query' =>[
'bool' =>[
'should' =>[
[
'match_phrase' =>[
'title' =>$keyword
]
],
[
'match_phrase' =>[
'content' =>$keyword
]
],
[
'match_phrase' =>[
'_all' =>$keyword
]
]
]
]
],
'highlight' =>[
'pre_tags' =>['<span class="highlight">'],
'post_tags' =>['</span>'],
'fields' =>[
'content' =>['pre_tags' =>['<span class="highlight-content">'], 'post_tags' =>['</span>']],
'_all' =>['pre_tags' =>['<span class="highlight-all">'], 'post_tags' =>['</span>']]
]
]
]
];
$search_result = $client->search($search_param);
?>
從上面的代碼中可以看出,我們使用了Elasticsearch的highlight功能來實現高亮。
Elasticsearch提供了兩種類型的高亮:Plain和Postings,我們通常使用Postings類型的高亮。
highlight: {
fields: {
field1: {
type: "postings",
fragment_size: 150,
number_of_fragments: 3,
pre_tags: ["<strong>"],
post_tags: ["</strong>"]
},
field2: {
type: "plain",
fragment_size: 150,
number_of_fragments: 3,
pre_tags: ["<strong>"],
post_tags: ["</strong>"]
}
}
}
然后我們看一下Postings類型的高亮參數的解釋:
type
:指定為Postings類型的高亮。fragment_size
:高亮的片段大小。number_of_fragments
:高亮的片段數量。pre_tags
:前置標記。post_tags
:后置標記。
在PHP中使用ES高亮的話,需要安裝Elasticsearch的官方PHP庫,然后在代碼中調用Elasticsearch的Highlight API即可實現高亮。
<?php
$params = [
'index' =>'test_index',
'type' =>'test_type',
'body' =>[
'query' =>[
'match' =>[
'test_field' =>'test_query'
]
],
'highlight' =>[
'pre_tags' =>['<strong>'],
'post_tags' =>['</strong>'],
'fields' =>[
'test_field' =>new \stdClass()
]
]
]
];
$results = $client->search($params);
$hits = $results['hits']['hits'];
foreach ($hits as $hit) {
$highlight = $hit['highlight']['test_field'][0];
echo $highlight;
}?>
綜上所述,PHP ES高亮在實現搜索關鍵字高亮方面有極大的幫助,只需使用Elasticsearch的Highlight API即可方便地實現高亮。