<?php namespace App\Servers\ElasticSearch;

use Elasticsearch\ClientBuilder;
use App\Servers\ElasticSearch\Lib\Query;

/**
 * ES
 * 
 * @author      刘相欣
 * 
 */
class ElasticSearch{

	// 终端链接
	private			$client = null;

	/**
	 * 初始化
	 * 
	 */
	public function __construct()
	{
		$this->getClient();
	}

	/**
	 * 创建终端
	 * 
	 */
	public function getClient($config=[]){
		// 链接配置
		$hosts			= $config ? $config : (array) config('elasticsearch.hosts');
		// Instantiate a new ClientBuilder //Set the hosts //Build the client object
		$this->client	= ClientBuilder::create()->setHosts($hosts)->build();
		// 返回结果
		return			$this->client;
	}

	/**
	 * 更改链接
	 * 
	 */
	public function setClient($config=[]){
		// 链接配置
		$hosts			= $config ? $config : (array) config('elasticsearch.hosts');
		// Instantiate a new ClientBuilder //Set the hosts //Build the client object
		$this->client	= ClientBuilder::create()->setHosts($hosts)->build();
		// 返回结果
		return			$this;
	}

	/**
	 * 指定索引
	 * 
	 * @param	String		$index	索引名称
	 * 
	 * @return 	\App\Servers\ElasticSearch\Lib\Query
	 * 
	 */
	public function query($index,$type='_doc'){
		// 返回实例化后的查询类
		return				 	new Query($this->client,$index,$type);
	}

	/**
	 * 自动调用
	 * 
	 *
	 */
	public function __call($name, $arguments)
	{
		// 执行
		$result  	= call_user_func_array([$this->client,$name],$arguments);
		// 结果返回
		return 		$result;
	}

}