<?php
declare (strict_types = 1);
namespace App\Elasticsearch;
use Hyperf\Elasticsearch\ClientBuilderFactory;
use Hyperf\Utils\ApplicationContext;
class Elasticsearch
{
/**
* @var ContainerInterface
*/
protected $container;
protected $es_client;
/**
* 实例化客户端对象
**/
public function __construct()
{
$this->container = ApplicationContext::getContainer();
$client_builder = $this->container->get(ClientBuilderFactory::class);
$builder = $client_builder->create();
$host = explode(',', config('es_host'));
$this->es_client = $builder->setHosts($host)->build();
}
/**
* 判断索引是否存在
**/
public function indexExistsEs($index)
{
$params = [
'index' => $index,
];
$result = $this->es_client->indices()->exists($params);
return $result;
}
/**
* 创建索引
**/
public function createIndex($index)
{
$params = [
'index' => $index,
];
$result = $this->es_client->indices()->create($params);
return $result;
}
/**
* 设置mapping
**/
public function putMapping($params)
{
extract($params);
$mapping['index'] = $index;
$mapping['type'] = $type;
$field_type['keyword'] = [
'type' => 'keyword',
];
$field_type['text'] = [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word',
];
$data = [
'properties' => value(function () use ($mapping_key, $field_type) {
$properties = [];
foreach ($mapping_key as $key => $value) {
if (empty($value)) {
continue;
}
foreach ($value as $cvalue) {
$properties[$cvalue] = $field_type[$key];
}
}
return $properties;
})
];