<?php

namespace App\Services\goods;

use Api\PhpUtils\Elastic\ElasticUtil;

class ElasticService
{
    public static function createIndex($index)
    {
        $elasticClient = ElasticUtil::getInstance();
        $data = [
            'mappings' => [
                'properties' => [
                    'id' => [
                        'type' => 'keyword',
                    ],
                    'name' => [
                        'type' => 'text',
                    ],
                ]
            ]
        ];
        $res = $elasticClient->createIndex($index, $data);
        var_export($res);
    }

    /**
     * 写入 es 一条数据
     * @param $index
     * @param $data
     * @param $id
     * @return array|callable
     */
    public static function indexDoc($index, $id, $data)
    {
        $elasticClient = ElasticUtil::getInstance();
        return $elasticClient->indexDoc($index, $data, $id);
    }

    /**
     * 修改 es 一条数据
     * @param $index
     * @param $id
     * @param $data
     * @return array|callable
     */
    public static function updateDoc($index, $id, $data)
    {
        $elasticClient = ElasticUtil::getInstance();
        return $elasticClient->updateDoc($index, $id, $data);
    }

    public static function bulk($index)
    {
        $elasticClient = ElasticUtil::getInstance();

        $data = [
            ['index' => ['_index' => $index]],
            ['test_field' => '公安部：各地校车将享最高路权'],
            ['index' => ['_index' => $index]],
            ['test_field' => '中韩渔警冲突调查：韩警平均每天扣1艘中国渔船'],
            ['index' => ['_index' => $index]],
            ['test_field' => '中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首'],
        ];
        $res = $elasticClient->bulkIndexDoc($data);
        var_export($res);
    }

    public static function searchDoc($index, $searchContent, $sortType, $from = 0, $size = 10)
    {
        $data = [
            "size"=>$size,
            "from"=>$from,
            "query" => [
                "match" => [
                    "test_field" => "中国"
                ]
            ],
            "sort" => [
                "match" => [
                    "test_field" => "中国"
                ]
            ],
        ];
        $elasticClient = ElasticUtil::getInstance();
        $res = $elasticClient->searchDoc($index, $data);
        var_export($res);
    }

}