在PHP中使用Elasticsearch

目录

【在MacOS中安装Elasticsearch相关软件】

安装Elasticsearch

安装Kibana

安装 elasticsearch-head

【在PHP中操作Elasticsearch】 


【在MacOS中安装Elasticsearch相关软件】

安装Elasticsearch

参考 Install Elasticsearch on macOS with Homebrew | Elasticsearch Guide [7.17] | Elastic

# 安装 ES
brew tap elastic/tap
brew install elastic/tap/elasticsearch-full

# 启动 ES
elasticsearch

浏览器中访问 http://localhost:9200/

安装Kibana

Kibana是ES的一个配套工具,可以让用户在网页中与ES进行交互。参考 Install Kibana on macOS with Homebrew | Kibana Guide [7.17] | Elastic

# 安装Kibana
brew install elastic/tap/kibana-full

# 启动 Kibana
kibana

浏览器中访问:http://localhost:5601/

安装 elasticsearch-head

Ealsticsearch只是提供各种api,如果想直观的管理api,可以使用 elasticsearch-head 客户端工具。

# 安装 node
brew install node #或者访问 https://nodejs.cn/download/

# 下载 elasticsearch-head 源代码并使用npm安装
git clone https://github.com/mobz/elasticsearch-head.git
cd elasticsearch-head 
npm install

#启动 elasticsearch-head
npm run start

修改ES的配置文件支持跨域,否则elasticsearch-head无法连接。

vim /usr/local/etc/elasticsearch/elasticsearch.yml 在最后面加入下面的内容:

# 是否支持跨域
http.cors.enabled: true
# *表示支持所有域名
http.cors.allow-origin: "*"

浏览器中访问 http://localhost:9100/

【在PHP中操作Elasticsearch】 

还是用之前 PHP中接入consul,实现微服务的注册发现和配置中心_浮尘笔记的博客-CSDN博客 中的ThinkPHP6框架演示,给 config/common.php 中添加如下内容

return [
    'es' => 'http://127.0.0.1:9200',
];

service/Elasticsearch.php 

<?php

namespace app\service;

use app\Http;
use think\facade\Config;

class Elasticsearch {
    /**
     * @param string $indexName
     * @param string $tableName
     * @param $data
     * @param $id string ES中的id
     * @return mixed
     */
    public function add($indexName = 'default', $tableName = 'all', $data, $id) {
        $url = Config::get('common.es') . '/' . $indexName . '/' . $tableName . '/' . $id;
        $str = Http::curlPost($url, $data);
        return $str;
    }

    public function update($indexName = 'default', $tableName = 'all', $data, $id) {
        $data = [
            'doc' => $data
        ];
        $url = Config::get('common.es') . '/' . $indexName . '/' . $tableName . '/' . $id . '/_update';
        $str = Http::curlPost($url, $data);
        return $str;
    }

    public function delete($indexName = 'default', $tableName = 'all', $id) {
        $url = Config::get('common.es') . '/' . $indexName . '/' . $tableName . '/' . $id;
        $str = Http::curlDelete($url);
        return $str;
    }

    public function search($indexName, $tableName, $query, $from, $size, $sort = ['id' => 'desc'], $excludes = ['content']) {
        $url = Config::get('common.es') . '/' . $indexName . '/_search';
        $array = [];
        $count = 0;
        $data = [
            'from' => $from,
            'size' => $size,
            'sort' => $sort,
            'query' => $query,
        ];
        if (!empty($excludes)) {
            $data['_source'] = [
                'excludes' => $excludes
            ];
        }
        $str = Http::curlPost($url, $data);
//        var_dump($url);
//        var_dump($data);
//        var_dump($str);
//        exit;

        if ($str) {
            if (isset($str['hits']) && $str['hits']['total'] > 0) {
                $count = $str['hits']['total']['value'];
                foreach ($str['hits']['hits'] as $val) {

                    if (isset($val['_source']['shares'])) {
                        $val['_source']['share'] = $val['_source']['shares'];
                        unset($val['_source']['shares']);
                    }

                    array_push($array, $val['_source']);
                }
            }
        }

        return ['count' => $count, 'data' => $array];
    }


}

controller/EsDemo.php

<?php

namespace app\controller;

use app\BaseController;
use app\service\Elasticsearch;

class EsDemo extends BaseController {
    /**
     * @var Elasticsearch
     */
    private $es;

    public function initialize() {
        parent::initialize();
        $this->es = new Elasticsearch();
    }

    public function add() {
        $str = $this->es->add('demo', 'all', ['id' => 1, 'name' => 'zhangsan', 'sex' => 0], 'demo-1');
        echo json_encode($str);
    }

    public function update() {
        $str = $this->es->update('demo', 'all', ['name' => 'zhangsan1', 'sex' => 1], 'demo-1');
        echo json_encode($str);
    }

    public function delete() {
        $str = $this->es->delete('demo', 'all', 'demo-1');
        echo json_encode($str);
    }

    public function search() {
        $query = [
            "bool" => [
                "filter" => [
                    ["term" => ["id" => 1]],
                ],
            ]
        ];

        $str = $this->es->search('demo', 'all', $query, 0, 1, ["id" => 'desc']);
        echo json_encode($str);
    }
}

配置路由 route/app.php

Route::get('es/add', 'EsDemo/add');
Route::get('es/update', 'EsDemo/update');
Route::get('es/delete', 'EsDemo/delete');
Route::get('es/search', 'EsDemo/search');

然后启动服务:php think run -p8087

访问 http://127.0.0.1:8087/es/add

然后查看 elasticsearch-head 中就有了刚才设定的demo-1

查询操作:http://127.0.0.1:8087/es/search

更新操作:http://127.0.0.1:8087/es/update

删除操作:http://127.0.0.1:8087/es/delete

源代码:app/controller/EsDemo.php · 浮尘/thinkphp-demo-2023 - Gitee.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮尘笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值