美文网首页ElasticSearch学习笔记
ElasticSearch第3天 Elasticsearch-P

ElasticSearch第3天 Elasticsearch-P

作者: 赵旻峰 | 来源:发表于2021-10-20 23:26 被阅读0次

今日目标

Elasticsearch-PHP基本API使用

1.下载php框架和es扩展包

在扩展包的选择上,我们尽量选一些下载排名靠前的扩展,方便日后查阅文档还有学习。在packagist中文网可以看到以下几个扩展包的下载量都非常大,我们选择排名第一的进行使用

elasticsearch/elasticsearch

laravel/scout

ruflin/elastica

composer create-project laravel/laravel elasticsearch-php
composer install
composer require elasticsearch/elasticsearch

访问 http://localhost/elasticsearch-php/public/ 查看项目是否安装成功

2. 在项目中配置es

config/database.php

    'elasticsearch' => [
        // Elasticsearch 支持多台服务器负载均衡,因此这里是一个数组
        'hosts' => explode(',', env('ES_HOSTS')),
    ],

.env文件

#es配置# 这里是你的 ElasticSearch 服务器 IP 及端口号#多个hosts用 , 隔开
# 如果要启用ssl,加https前缀即可
#ES_HOSTS=127.0.0.1:9200,127.0.0.2:9200,127.0.0.3:9200,127.0.0.4:9200,127.0.0.5:9200 
ES_HOSTS=127.0.0.1:9200

注意:ES默认使用的是9200端口,在服务器上一定要开放对应端口才能正常服务

初始化elasticsearch对象

//注入到容器中 App/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use Elasticsearch\ClientBuilder as ElasticBuilder;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('es', function () {
            $bulider = ElasticBuilder::create()->setHosts(config('database.elasticsearch.hosts'));
            if (app()->environment() == 'local') {
                //配置日志,Elasticsearch 的请求和返回数据将打印到日志文件中,方便我们调试
                $bulider->setLogger(app('log'));
            }

            return $bulider->build();
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
    }
}

测试

php artisan tinker 
 
>>>app('es')->info()

使用

//使用了laravel的容器注入技术,在使用时可以直接app('es')->apis ,不需要再次实例化
app('es')->info();
app('es') ->index([
                'index' => 'name',
                'type' => 'title',
                'id' => 1,
                'body' => ['testField' => 'xxx'],
            ]);

//单独使用的话可以实例化
use Elasticsearch\ClientBuilder;
client = ClientBuilder::create()->build();client ->apis;

3.基本使用

索引一个文档

为了索引一个文档,我们要指定4部分信息:index,type,id 和一个 body。构建一个键值对的关联数组就可以完成上面的内容。body 的键值对格式与文档的数据保持一致性。(译者注:如 ["testField" ⇒ "abc"] 在文档中则为 {"testField" : "abc"}):

    public function index()
    {
        $params = [
            'index' => 'my_index',
            'type' => 'my_type',
            'id' => 'my_id',
            'body' => ['testField' => 'abc'],
        ];

        $response = app('es')->index($params);

        return $response;
    }
  • 响应
    响应的是一个关联数组,return 后通过调试工具看到的是json格式的字符串
{
    "_index": "my_index",
    "_type": "my_type",
    "_id": "my_id",
    "_version": 1,
    "result": "created",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 0,
    "_primary_term": 1
}

获取一个文档

public function fetch()
    {
        $params = [
            'index' => 'my_index',
            'type' => 'my_type',
            'id' => 'my_id',
        ];

        $response = app('es')->get($params);

        return $response;
    }
  • 响应
{
    "_index": "my_index",
    "_type": "my_type",
    "_id": "my_id",
    "_version": 2,
    "_seq_no": 1,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "testField": "abc"
    }
}

搜索文档

    public function search_es()
    {
        $params = [
            'index' => 'my_index',
            'type' => 'my_type',
            'body' => [
                'query' => [
                    'match' => [
                        'testField' => 'abc',
                    ],
                ],
            ],
        ];

        $response = app('es')->search($params);

        return $response;
    }
  • 响应结果
{
    "took": 2,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 0.2876821,
        "hits": [
            {
                "_index": "my_index",
                "_type": "my_type",
                "_id": "my_id",
                "_score": 0.2876821,
                "_source": {
                    "testField": "abc"
                }
            }
        ]
    }
}

删除一个文档

    public function delete_es_doc()
    {
        $params = [
            'index' => 'my_index',
            'type' => 'my_type',
            'id' => 'my_id',
        ];

        $response = app('es')->delete($params);

        return $response;
    }
  • 响应
{
    "_index": "my_index",
    "_type": "my_type",
    "_id": "my_id",
    "_version": 4,
    "result": "deleted",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 3,
    "_primary_term": 1
}

删除一个索引

    public function delete_es()
    {
        $deleteParams = [
            'index' => 'my_index',
        ];
        $response = app('es')->indices()->delete($deleteParams);

        return $response;
    }
  • 响应结果
{
    "acknowledged": true
}

创建一个索引

//创建一个索引
    public function index_es_cre()
    {
        $params = [
            'index' => 'my_index',
            'body' => [
                'settings' => [
                    'number_of_shards' => 12,
                    'number_of_replicas' => 0,
                ],
            ],
        ];

        $response = app('es')->indices()->create($params);

        return $response;
    }
  • 响应结果
{
    "acknowledged": true,
    "shards_acknowledged": true,
    "index": "my_index"
}

响应结果字段说明

_index:文档所在的索引名
_type:文档所在的类型名
_id:文档唯一id
_score:相关性算分
_uid:组合id,有_type和_id组成(从6.x开始_type不再起作用,同_id一样)
_source:文档的原始json数据,可以从这里获取每个字段的内容
_all:整合所有字段内容到该字段,默认下禁用

明日计划

深入学习Elasticsearch-PHP API的使用,使其可以满足跟数据库相关的业务需求

总结

image.png

MySQL 中的数据库(DataBase),等价于 ES 中的索引(Index)。

MySQL 中一个数据库下面有 N 张表(Table),等价于1个索引 Index 下面有 N 多类型(Type)。

MySQL 中一个数据库表(Table)下的数据由多行(Row)多列(column,属性)组成,等价于1个 Type 由多个文档(Document)和多 Field 组成。

MySQL 中定义表结构、设定字段类型等价于 ES 中的 Mapping。举例说明,在一个关系型数据库里面,Schema 定义了表、每个表的字段,还有表和字段之间的关系。与之对应的,在 ES 中,Mapping 定义索引下的 Type 的字段处理规则,即索引如何建立、索引类型、是否保存原始索引 JSON 文档、是否压缩原始 JSON 文档、是否需要分词处理、如何进行分词处理等。

MySQL 中的增 insert、删 delete、改 update、查 search 操作等价于 ES 中的增 PUT/POST、删 Delete、改 _update、查 GET。其中的修改指定条件的更新 update 等价于 ES 中的 update_by_query,指定条件的删除等价于 ES 中的 delete_by_query。

创建一个索引相当于创建一个库,索引一个文档相当于给库的某个表中新增一条记录,获取/搜索一个文档相当于获取某一个库的某个表中的一条记录,删除一个文档相当于删除这条记录,删除一个索引相当于删除了这个库

相关文章

网友评论

    本文标题:ElasticSearch第3天 Elasticsearch-P

    本文链接:https://www.haomeiwen.com/subject/bsqtaltx.html