下载PHP包
https://github.com/elastic/elasticsearch-php
# 选择合适的与PHP版本对应的包版本
composer require elasticsearch/elasticsearch ~7.8
代码:
<?php
namespace app\service;
use Elasticsearch\ClientBuilder;
/**
* ES服务器实现者
* Class Elasticsearch
* @package app\service
*/
class Elasticsearch
{
protected $host = [
'127.0.0.1:9200'
];
protected $client;
protected $index;
public function __construct($index)
{
if(!isset($this->indexMappingsConf()[$index])){throw new \Exception($index.':该索引未配置映射关系');}
$this->client = ClientBuilder::create()->setHosts($this->host)->build();
$this->index = $index;
}
/**
* 索引映射关系配置
* @return \string[][][]
*/
private function indexMappingsConf(){
return array(
'goods' => [
'goods_name' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'copy_to' => 'all'
],
'cat_name' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'copy_to' => 'all'
],
'price' => [
'type' => 'float'
],
'is_imperfect' => [
'type' => 'byte'
]
],
);
}
/**
* 文档是否存在
* @param $id
* @return bool
*/
public function exists($id){
$params = ['index' => $this->index,'id' => $id];
return $this->client->exists($params);
}
/**
* 获取文档全部内容
* @param $id
* @return array|callable
*/
public function get($id){
$params = ['index' => $this->index,'id' => $id];
return $this->client->get($params);
}
/**
* 获取指定文档数据
* @param $id
* @return array|callable
*/
public function find($id){
$params = ['index' => $this->index,'id' => $id];
return $this->client->getSource($params);
}
public function search($body=[]){
$params = [
'index' => $this->index,
'body' => $body
];
return $this->client->search($params);
}
/**
* 更新单个文档
* @param $data
* @return array|callable
* @throws \Exception
*/
public function save($data){
if(empty($data)){throw new \Exception('更新参数不能为空');}
if(!isset($data['id'])){throw new \Exception('id不能为空');}
$params = [
'index' => $this->index,
'id' => $data['id'],
'body' => $data
];
return $this->client->index($params);
}
/**
* 批量更新文档或替换已有文档
* @param $datas
* @return array|callable|mixed
*/
public function saveAll($datas){
return $this->client->bulk($this->getBulkParams($datas));
}
/**
* 创建索引
* @return array|mixed
*/
public function createIndex(){
$params = [
'index' => $this->index,
'body' => [
'settings' => [
'number_of_shards' => 1,
'number_of_replicas' => 0
],
'mappings' => [
'properties' => $this->indexMappingsConf()[$this->index]
]
],
// 'client' => [ 'ignore' => [404,400] ]
];
return $this->client->indices()->create($params);
}
private function getBulkParams($datas){
$params = ['index' => $this->index];
switch ($this->index){
case 'goods':
foreach ($datas as $key=>$row){
$params['body'][]=array(
'index' => array(
'_id'=>$row['id']
),
);
$params['body'][]=array(
'goods_name'=>$row['goods_name'],
'cat_name'=>$row['cat_name'],
'price'=>(float)$row['price'],
'is_imperfect'=>(int)$row['is_imperfect'],
);
}
break;
}
return $params;
}
}
调用示例:
$goodsElasticsearchService = new \app\service\Elasticsearch('goods');
$res = $goodsElasticsearchService->search();
dump($res);