yii2中使用elasticsearch
elastic官网的操作类
https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_configuration.html
composer.json的require中加入:
"elasticsearch/elasticsearch": "~6.0"
composer update
config/params.php中添加
'elasticsearch' => [
'192.168.163.128:9200'
],
新建EsService.php
namespace app\modules\study\service;
use Elasticsearch\ClientBuilder;
use Yii;
class EsService
{
public $index;
public $type;
public $client;
public function __construct($index, $type)
{
$this->index = $index;
$this->type = $type;
$hosts = yii::$app->params['elasticsearch'];
$this->client = ClientBuilder::create()->setHosts($hosts)->build();
}
/**
* @param xx
* @desc 创建索引
*/
public function createIndex()
{
$params = [
'index' => $this->index,
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
]
]
];
$response = $this->client->indices()->create($params);
return $response;
}
/**
* @param xx
* @desc 删除索引
*/
public function deleteIndex()
{
$params = ['index' => $this->index];
$response = $this->client->indices()->delete($params);
return $response;
}
/**
* @param $id
* @param $data
* @desc 添加文档
*/
public function createDocument($id, $data)
{
$params = [
'index' => $this->index,
'type' => $this->type,
'id' => $id,
'body' => $data
];
$response = $this->client->index($params);
return $response;
}
