<?php


namespace Api\PhpUtils\Elastic\Manager;


use Elasticsearch\Client;

trait DocumentManager
{
    /**
     * @var Client
     */
    protected $client;

    /**
     * 索引文档
     * @param $index
     * @param $data
     * @param string $id
     * @return array|callable
     */
    public function indexDoc($index, $data, string $id = '')
    {
        $params = [
            'index' => $index,
            'body' => $data
        ];
        if (!empty($id)) {
            $params['id'] = $id;
        }

        return $this->client->index($params);
    }

    /**
     * @param $data
     * @return array|callable
     */
    public function bulkIndexDoc($data)
    {
        $params = ['body' => $data];
        return $this->client->bulk($params);
    }

    /**
     * 删除文档
     * @param $index
     * @param $id
     * @return array|callable
     */
    public function deleteDoc($index, $id)
    {
        $params = [
            'index' => $index,
            'id' => $id
        ];

        return $this->client->delete($params);
    }

    /**
     * 获取文档
     * @param $index
     * @param $id
     * @return array|callable
     */
    public function getDoc($index, $id)
    {
        $params = [
            'index' => $index,
            'id' => $id
        ];

        return $this->client->get($params);
    }

    /**
     * 更新文档
     * @param $index
     * @param $id
     * @param $data
     * @return array|callable
     */
    public function updateDoc($index, $id, $data)
    {
        $params = [
            'index' => $index,
            'id' => $id,
            'body' => $data
        ];

        return $this->client->update($params);
    }

    /**
     * 搜索操作
     * @param $index
     * @param $data
     * @return array|callable
     */
    public function searchDoc($index, $data)
    {
        $params = [
            'index' => $index,
            'body' => $data
        ];

        return $this->client->search($params);
    }
}