在ThinkPHP框架下使用Elasticsearch进行全文检索和聚合查询需要进行以下步骤:
composer require elasticsearch/elasticsearch
config/elasticsearch.php
文件中添加如下代码:return [
'hosts' => [
[
'host' => 'localhost',
'port' => '9200',
'scheme' => 'http',
],
],
];
use Elasticsearch\ClientBuilder;
class MyModel extends Model
{
public function search($keyword, $size = 10)
{
$client = ClientBuilder::create()->setHosts(config('elasticsearch.hosts'))->build();
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'content' => $keyword,
],
],
'size' => $size,
],
];
$response = $client->search($params);
$hits = $response['hits']['hits'];
// 处理搜索结果
// ...
return $hits;
}
public function aggregate()
{
$client = ClientBuilder::create()->setHosts(config('elasticsearch.hosts'))->build();
$params = [
'index' => 'my_index',
'body' => [
'aggs' => [
'my_agg' => [
'terms' => [
'field' => 'category',
],
],
],
],
];
$response = $client->search($params);
$aggregations = $response['aggregations'];
// 处理聚合结果
// ...
return $aggregations;
}
}
其中,search
方法使用match
查询实现全文检索,aggregate
方法使用terms
聚合实现分组统计。
需要注意的是,为了避免敏感政治问题,本回答不提供具体的搜索和聚合内容,请读者自行替换相关字段和条件。
更多详细信息请参考官方文档。