Elasticsearch-PHP学习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LJFPHP/article/details/89113776

一、前言

      身为一个phper,要学习ES还是有点难度的,毕竟是基于Java写的,不过这也难不倒我们的php大佬,一个ES-PHP插件横空出世,赶紧学习一波~

二、正文

1、 ES-PHP-sdk的手册

 链接:https://www.elastic.co/guide/cn/elasticsearch/php/current/index.html

2、如果要使用ES-PHP,需要的版本:(需要测试安装的扩展,目前不全)

(1)PHP 7.0.0 或者更高版本
(2)需要原生 JSON 扩展的版本为 1.3.7 或者更高版本(貌似php安装自带json)
(3)ext-curl:PHP 的 Libcurl 扩展 (文档上说的是libcurl,但是百度没查到,只是开启了php的curl扩展)

3、本地安装,参照手册,通过composer安装

4、本地测试php插件

(1) 需要先配置host等,建议封装一个类,在类里面初始化host,实例化客户端$client

 public function init()
    {
        $hosts = [
            'localhost:9200',         // IP + Port
        ];
        $this->client = ClientBuilder::create()           // Instantiate a new ClientBuilder
        ->setHosts($hosts)      // Set the hosts
        ->build();              // Build the client object
    }

5、实现一次简单的搜索:

(前提是你搜索的这个索引的文档下是有数据的,我这里的数据是es基础篇上创建的一些数据)

 public function actionSearchData()
{
    $params = [
        'index' => 'test_2',
        'type' => '_doc',
        'body' => [
            'query' => [
                'match' => [
                    'name' => '联通'         	//这部分,搜索的时候,字段名称name要和你之前新建索引数据的字段保持一致,
                ]			//名称不一致则无法搜索到
            ]
        ]
    ];
    $repos =  $this->client->search($params);
    print_r($repos);
}

结果:

Array
(
    [took] => 9
    [timed_out] => 
    [_shards] => Array
        (
            [total] => 5
            [successful] => 5
            [skipped] => 0
            [failed] => 0
        )
    [hits] => Array
        (
            [total] => 1
            [max_score] => 0.2876821
            [hits] => Array
                (
                    [0] => Array
                        (
                            [_index] => test_2
                            [_type] => _doc
                            [_id] => 2
                            [_score] => 0.2876821
                            [_source] => Array
                                (
                                    [name] => 中国联通
                                )
                        )
                )
        )
)

      这里可以根据文档,试着操作es的搜索,查询索引文档等功能。都熟悉之后,代表我们至少可以使用es-php来查询一些数据了,接下来就是一些复杂的查询,还有相关配置等。

ES的中文文档手册:
https://www.elastic.co/guide/cn/elasticsearch/guide/current/combining-queries-together.html

      这个插件整体来讲还是很简单的,关键是看文档,文档看完基本心里就有数了。不过需要注意的事,文档讲的只是ES文档的一部分内容,真正的想了解原理,还有深层次的东西,还是要看ES中文文档。

end

猜你喜欢

转载自blog.csdn.net/LJFPHP/article/details/89113776