前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ElasticSearch php 学习笔记 (SDK封装)

ElasticSearch php 学习笔记 (SDK封装)

作者头像
躺平程序员老修
发布2023-09-05 16:07:25
3370
发布2023-09-05 16:07:25
举报
文章被收录于专栏:躺平程序员老修

elasticsearch

环境准备

安装es https://www.elastic.co/cn/downloads 安装IK分词插件 https://github.com/medcl/elasticsearch-analysis-ik

ES 部署 Version: 7.4.2

  • wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.4.2-linux-x86_64.tar.gz
  • cd elasticsearch-7.4.2/bin
  • ./elasticsearch

报错'can not run elasticsearch as root',参考https://blog.csdn.net/oschina_41140683/article/details/93007721 其他错误与解决 https://blog.csdn.net/happyzxs/article/details/89156068

  • curl 127.0.0.1:9200 测试

config/elasticsearch.yml 修改 action.auto_create_index, 自动创建索引

IK分词器

https://github.com/medcl/elasticsearch-analysis-ik/tree/master

  • 下载 ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.4.2/elasticsearch-analysis-ik-7.4.2.zip
  • 查看 http://localhost:9200/_cat/plugins

测试:

11111111.png
11111111.png
s827.png
s827.png

使用php SDK操作ElasticSearch

实例参考:https://github.com/ShyZhen/fmock/tree/master/app/Library/ElasticSearch

示例代码 :

代码语言:javascript
复制
<?php
/**
 * Created by huaixiu.zhen@gmail.com
 * http://litblc.com
 * User: huaixiu.zhen
 * Date: 2018/5/26
 * Time: 19:33
 */

namespace App\Http\Controllers\Api\V1;

use Elasticsearch\ClientBuilder;

class ElasticsearchController
{
    private static $esClient;

    /**
     * 初始化连接
     */
    public function __construct()
    {
        if (!self::$esClient) {
            self::$esClient = ClientBuilder::create()
                ->setHosts([env('ELASTICSEARCH_HOST_NODE_1')])
                ->build();
        }
    }


    /**
     * 创建一个索引(index,类似于创建一个库)
     * 6.0版本以后一个index只能有一个type
     * Author huaixiu.zhen@gmail.com
     * http://litblc.com
     * @param $index
     * @return array
     */
    public function indexCreate($index)
    {
        $params = [
            'index' => $index,
            'body' => [
                'settings' => [
                    'number_of_shards' => env('NUMBER_OF_SHARDS', 5),      // 分片 默认5
                    'number_of_replicas' => env('NUMBER_OF_REPLICAS', 1)   // 副本、备份 默认1
                ]
            ]
        ];
        $response = self::$esClient->indices()->create($params);

        return $response;
    }


    /**
     * 删除一个索引(index,类似于删除一个库)
     * Author huaixiu.zhen@gmail.com
     * http://litblc.com
     * @param $index
     * @return array
     */
    public function indexDelete($index)
    {
        $params = [
            'index' => $index
        ];
        $response =  self::$esClient->indices()->delete($params);

        return $response;
    }


    /**
     * 更改或增加user索引的映射
     * 在创建完user的index后使用
     * Author huaixiu.zhen
     * http://litblc.com
     * @param $index
     * @param $type
     * @return array
     */
    public function putMappingsForUser($index, $type)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => [
                $type => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
                        'name' => [                     // name 是需要搜索分词的字段
                            'type' => 'text',
                            'analyzer' => 'ik_smart',
                            'search_analyzer' => 'ik_smart',
                            'search_quote_analyzer' => 'ik_smart'
                        ]
                    ]
                ]
            ]
        ];
        $response = self::$esClient->indices()->putMapping($params);

        return $response;
    }

    /**
     * 更改或增加 文章 post 索引的映射 // TODO 字段优化
     * 在创建完post的index后使用,目前已经集成到es:init命令中
     * Author huaixiu.zhen
     * http://litblc.com
     * @param $index
     * @param $type
     * @return array
     */
    public function putMappingsForPost($index, $type)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => [
                $type => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
                        'title' => [
                            'type' => 'text',
                            'analyzer' => 'ik_smart',
                            'search_analyzer' => 'ik_smart',
                            'search_quote_analyzer' => 'ik_smart'
                        ],
                        'content' => [
                            'type' => 'text',
                            'analyzer' => 'ik_smart',
                            'search_analyzer' => 'ik_smart',
                            'search_quote_analyzer' => 'ik_smart'
                        ],
                    ]
                ]
            ]
        ];
        $response = self::$esClient->indices()->putMapping($params);

        return $response;
    }


    /**
     * 创建一条数据(索引一个文档)
     * Author huaixiu.zhen@gmail.com
     * http://litblc.com
     * @param $index string
     * @param $type string
     * @param $id int
     * @param $body array('key' => 'val')
     * @return array
     */
    public function createDoc($index, $type, $id, $body)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'id' => $id,
            'body' => $body,

        ];
        $response = self::$esClient->index($params);

        return $response;
    }


    /**
     * 获取一个文档(对应上面createDoc)
     * Author huaixiu.zhen@gmail.com
     * http://litblc.com
     * @param $index string
     * @param $type string
     * @param $id int
     * @return array
     */
    public function getDoc($index, $type, $id)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'id' => $id
        ];
        $response = self::$esClient->get($params);

        return $response;
    }


    /**
     * 搜索文档 doc
     * Author huaixiu.zhen@gmail.com
     * http://litblc.com
     * @param $index string
     * @param $type string
     * @param $query string
     * @return array
     */
    public function search($index, $type, $query)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => [
                'query' => [
// 单字段
//                    'match' => [
//                        'key1' => $query
//                    ]

// 多字段
                    'multi_match' => [
                        'query' => $query,
                        "type" => "best_fields",
                        'operator' => 'or',
                        'fields' => ['title', 'content']  // TODO 根据数据表字段,准确说是存入es的字段进行修改
                    ]
                ]
            ]
        ];
        $response = self::$esClient->search($params);

        return $response['hits'];
    }


    /**
     * 删除一条记录(文档) doc
     * Author huaixiu.zhen@gmail.com
     * http://litblc.com
     * @param $index
     * @param $type
     * @param $id
     * @return array
     */
    public function delete($index, $type, $id)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'id' => $id
        ];
        $response = self::$esClient->delete($params);

        return $response;
    }
}

postman测试结果

这里只给出get和search的截图

  • 获取doc
qqqqq.png
qqqqq.png
  • 搜索doc
wwww.png
wwww.png

后记

我认为学习一门新技术,必须从他的源出发,如果一开始就使用各路大神封装好的插件的话,那应该挺无聊,也得不到进步,类似scout那样都封装成了一个样子,对使用很友好,但是对学习技术是不利的。 下一步,我将结合scout+laravel+es来做自己项目的搜索服务,ye!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 环境准备
  • ES 部署 Version: 7.4.2
  • IK分词器
  • 使用php SDK操作ElasticSearch
  • postman测试结果
  • 后记
相关产品与服务
Elasticsearch Service
腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档