1、安装扩展
composer require elasticsearch/elasticsearch
2、连接ES客户端
<?php
/*
User : Administrator
Date : 2020/8/31
Time : 14:36
*/
use Elasticsearch\ClientBuilder;
class EsModel
{
protected function getEsClient()
{
$client = ClientBuilder::create()->setHosts([$this->getEsConfig()])
->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
->setRetries(10)->build();
return $client;
}
protected function getEsConfig()
{
$config = [
'host' => '127.0.0.1',
'port' => '8200',
'scheme' => 'http',
'user' => 'root',
'pass' => '123456'
];
return $config;
}
}
3、插入数据
public function insertDataIntoEs($tableName,array $data)
{
$params = [
'index' => $tableName,
'id' => $data['id'],
'body' => $data
];
$client = $this->getEsClient();
$result = $client->index($params);
return $result;
}
public function insertAllDataIntoEs(array $data)
{
$client = $this->getEsClient();
$result = $client->bulk($data);
return $result;
}
4、删除数据
public function deleteDataFromEsById($tableName,$id)
{
$params = [
'index' => $tableName,
'id' => $id
];
$client = $this->getEsClient();
$result = $client->delete($params);
return $result;
}
5、基本查询
match查询:match查询会做分词处理,比如"宝马多少马力"会被分词为"宝马 多少 马力", 所有有关"宝马 多少 马力", 那么所有包含这三个词中的一个或多个的文档就会被搜索出来。
match_phrase查询:关键点(slop参数)短语匹配,es会根据分词的position对分词进行过滤,这个是就slop参数,默认是0
scroll分页:关键点(size分页)查询时可根据size数做分页操作。
public function searchDataPaginateFromEsByConditions($tableName,array $conditions)
{
$params = [
'scroll' => '1m',
'size' =>20,
'index' => $tableName,
'body' => [
'query' => $conditions,
'sort' => ['create_time'=>'desc']
]
];
$client = $this->getEsClient();
try
{
$result = $client->search($params);
$list = [];
$i=1;
while (isset($result['hits']['hits']) && count($result['hits']['hits']) > 0 && $i <= 20)
{
$list[] = $result['hits']['hits'];
$scroll_id = $result['_scroll_id'];
$result = $client->scroll([
'body' => [
'scroll_id' => $scroll_id,
'scroll' => '1m'
]
]);
$i++;
}
}catch (\Exception $exception)
{
return $exception->getMessage()
$list = [];
}
return $list;
}
本文详细介绍了如何在ThinkPHP6中使用Elasticsearch,包括安装扩展、建立客户端连接、数据的插入和删除,以及进行了match和match_phrase查询的解释,还探讨了scroll分页的size设置用于实现高效分页。

1334

被折叠的 条评论
为什么被折叠?



