栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

PHP实现elasticsearch/elasticsearchy实例

PHP实现elasticsearch/elasticsearchy实例

es中文文档

https://learnku.com/docs/elasticsearch73/7.3

极客时间-Elasticsearch核心技术与实践-课件及 Demo 下载地址

https://gitee.com/geektime-geekbang/geektime-ELK

第一:安装elasticsearch环境
## 相关阅读
- 安装指南 https://www.elastic.co/guide/en/elasticsearch/reference/7.1/install-elasticsearch.html
- Elastic Support Matrix(OS / JDK ) https://www.elastic.co/cn/support/matrix
- Elasticsearch 的一些重要配置 https://www.elastic.co/guide/en/elasticsearch/reference/current/important-settings.html
- https://www.elastic.co/guide/en/elasticsearch/reference/current/settings.html
- https://www.elastic.co/guide/en/elasticsearch/reference/current/important-settings.html
- Elasticsearch on Kuvernetes https://www.elastic.co/cn/blog/introducing-elastic-cloud-on-kubernetes-the-elasticsearch-operator-and-beyond
- CAT Plugins API https://www.elastic.co/guide/en/elasticsearch/reference/7.1/cat-plugins.html

window 的使用,首先下载安装包,百度网盘下载(https://pan.baidu.com/s/1CRT3W4wEESglCBDnslk2AA)
解压到本地,我是D:elasticsearch-7.1.0

#启动单节点 
bin/elasticsearch -E node.name=node0 -E cluster.name=geektime -E path.data=node0_data
window .binelasticsearch

#安装插件
bin/elasticsearch-plugin install analysis-icu
window .binelasticsearch-plugin install analysis-icu
第二:composer require elasticsearch/elasticsearch 第三

单例,InstanceTrait.php

= 5.6.0
            self::$instances[$key] = new $className(...$args);
        }
        return self::$instances[$key];
    }
}

服务,ElasticSearchModel.php

 [
            'host' => '127.0.0.1',
            'port' => 9200,
            'index' => 'sports_search_expert'
        ],
        'sports_search_blog' => [
            'host' => '127.0.0.1',
            'port' => 9200,
            'index' => 'sports_search_blog'
        ]
    ];

    private $_prodConfig = [
        'sports_search_expert' => [
            'host' => '127.0.0.1',
            'port' => 9200,
            'index' => 'sports_search_expert'
        ],
        'sports_search_blog' => [
            'host' => '127.0.0.1',
            'port' => 9200,
            'index' => 'sports_search_blog'
        ],
    ];

    private $_config;
    private $_client;
    private $_error = false;

    public function __construct($key)
    {
        $this->_config = $this->_devConfig;
        if (env('APP_ENV') == 'prod') {
            $this->_config = $this->_prodConfig;
        }

        if (!array_key_exists($key, $this->_config)) {
            $this->_error = true;
            return;
        }

        $this->_config = $this->_config[$key];
        $hosts = [$this->_config['host'] . ':' . $this->_config['port']];
        $this->_client = ClientBuilder::create()->setHosts($hosts)->build();
    }

    
    public function addDoc($type, $data)
    {
        try {
            if ($this->_error) {
                throw new Exception('配置错误');
            }
            if (!is_array($data)) {
                throw new Exception('参数缺失');
            }

            $params = [
                'index' => $this->_config['index'],
                'type' => $type,
                'body' => $data,
            ];

            if (isset($data['id'])) {
                $params['id'] = $data['id'];
            }

            $this->_client->index($params);
            return ['code' => 0, 'msg' => '成功'];
        } catch (Exception $exception) {
            Log::error($exception);
            return ['code' => -1, 'msg' => $exception->getMessage()];
        }
    }

    
    public function getDocById($type, $id)
    {
        try {
            if ($this->_error) {
                throw new Exception('配置错误');
            }

            $params = [
                'index' => $this->_config['index'],
                'type' => $type,
                'id' => $id
            ];
            return ['code' => 0, 'msg' => '成功', 'data' => $this->_client->get($params)];
        } catch (Missing404Exception $exception) {
            return ['code' => 0, 'data' => []];
        } catch (Exception $exception) {
            Log::error($exception);
            return ['code' => -1, 'msg' => $exception->getMessage()];
        }
    }

    
    public function updateDoc($type, $id, $data)
    {
        try {
            if ($this->_error) {
                throw new Exception('配置错误');
            }

            $params = [
                'index' => $this->_config['index'],
                'type' => $type,
                'id' => $id,
                'body' => ['doc' => $data]
            ];

            return ['code' => 0, 'msg' => '成功', 'data' => $this->_client->update($params)];
        } catch (Exception $exception) {
            Log::error($exception);
            return ['code' => -1, 'msg' => $exception->getMessage()];
        }
    }

    
    public function searchDoc($type, $body, $page = 1, $size = 10)
    {
        try {
            if ($this->_error) {
                throw new Exception('配置错误');
            }

            $params = [
                'index' => $this->_config['index'],
                'type' => $type,
                'body' => $body,
                'from' => ($page - 1) * $size,
                'size' => $size
            ];

            $data = $this->_client->search($params);
            $hits = isset($data['hits']) ? $data['hits'] : [];
            $total = isset($hits['total']) ? $hits['total'] : 0;
            $hitsArr = isset($hits['hits']) ? $hits['hits'] : [];
            $list = [];
            foreach ($hitsArr as $value) {
                $list[] = $value['_source'];
            }

            $return = [
                'total' => $total,
                'list' => $list
            ];
            return ['code' => 0, 'msg' => '成功', 'data' => $return];
        } catch (Exception $exception) {
            Log::error($exception);
            return ['code' => -1, 'msg' => '暂无数据', 'data' => []];
        }
    }
}

实例:SyncBlog.php

添加,更新,获取一个

ElasticSearchModel::getInstance('sports_search_blog')->addDoc('blog', $data);

ElasticSearchModel::getInstance('sports_search_blog')->updateDoc('blog', $id, $data);

ElasticSearchModel::getInstance('sports_search_blog')->getDocById('blog', $id);

getoneById($id, 4, 'sports');
        if (empty($blogInfo)) {
            return ['code' => -1, 'msg' => '不存在该资讯'];
        }

        //判断是否存在
        $result = ElasticSearchModel::getInstance('sports_search_blog')->getDocById('blog', $id);
        if (!empty($result['code'])) {
            return $result;
        }

        //不存在写入
        if (empty($result['data'])) {
            $data = [
                'id' => $id,
                'search' => $blogInfo['title'],
                'status' => $blogInfo['status']
            ];
            ElasticSearchModel::getInstance('sports_search_blog')->addDoc('blog', $data);
            return $result;
        }

        //存在更新
        $data = [
            'search' => $blogInfo['title'],
            'status' => $blogInfo['status']
        ];
        $result = ElasticSearchModel::getInstance('sports_search_blog')->updateDoc('blog', $id, $data);
        return $result;
    }
}

分页查找

ElasticSearchModel::getInstance('sports_search_blog')->searchDoc('blog', $data, $pageNo, $pageCount);

SearchBlog.php

 [
                'bool' => [
                    'must' => [
                        'match' => [
                            'search' => $name
                        ]
                    ],
                    'filter' => [
                        'term' => [
                            'status' => 1 //TODO 改成常量
                        ]
                    ],
                ],
            ]
        ];
        $result = ElasticSearchModel::getInstance('sports_search_blog')->searchDoc('blog', $data, $pageNo, $pageCount);

        if ($result['code'] != 0 || empty($result['data'])) {
            return $result;
        }

        $data = $result['data'];
        $list = $data['list'];

        $blogIdArr = array_column($list, 'id');
        $blogInfo = BlogModel::getInstance()->getBlogListByIdArrAndTypeIdArr($blogIdArr);

        $return = [];
        foreach ($list as $value) {
            if (!isset($blogInfo[$value['id']])) {
                continue;
            }

            $return[] = [
                'blog_id' => $value['id'],
                'blog_title' => $blogInfo[$value['id']]['title'],
                'blog_img' => $blogInfo[$value['id']]['thumbnail_url'],
            ];
        }

        $return = [
            'list' => $return,
        ];

        return ['code' => 0, 'data' => $return];
    }
}

Buy me a cup of coffee :)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/687932.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号