thinkphp使用elasticsearch

1.根据thinkphp版本下载对应的 elasticsearch版本

https://mirrors.huaweicloud.com/elasticsearch/

这里我下载的是8.5.3版本

cd /www/server
wget https://mirrors.huaweicloud.com/elasticsearch/8.5.3/elasticsearch-8.5.3-linux-x86_64.tar.gz
tar -zxvf elasticsearch-8.5.3-linux-x86_64.tar.gz
cd elasticsearch-8.5.3
vi config/elasticsearch.yml

elasticsearch.yml内容如下

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
#node.name: node-1
node.name: zk-node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
path.data: /www/elastic/data
#
# Path to log files:
#
#path.logs: /path/to/logs
path.logs: /www/elastic/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: 127.0.0.1
#
# Set a custom port for HTTP:
#
http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.seed_hosts: ["host1", "host2"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
#cluster.initial_master_nodes: ["node-1", "node-2"]
#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true
cluster.initial_master_nodes: ["zk-node-1"]
 
cluster.routing.allocation.disk.watermark.flood_stage: 99%
cluster.routing.allocation.disk.threshold_enabled: false

添加elastic用户

groupadd elastic
useradd -g elastic elastic
chown -R elastic:elasticelasticsearch-8.5.3

安装ik分词库

https://github.com/medcl/elasticsearch-analysis-ik/releases

指定java_home 17以上
切换到elastic并启动elastic

su elastic
./bin/elastic -d

测试是否启动成功

curl 127.0.0.1:9200

{
  "name" : "zk-node-1",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "ASYFm--EQKu_hrqCSOHmVQ",
  "version" : {
    "number" : "7.10.2",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "747e1cc71def077253878a59143c1f785afa92b9",
    "build_date" : "2021-01-13T00:42:12.435326Z",
    "build_snapshot" : false,
    "lucene_version" : "8.7.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

设置外网访问并nginx转发elasticsearch

location / {
     proxy_pass http://127.0.0.1:9200;
}
image.png

thinkphp 安装对应的elasticsearch版本包

composer require elasticsearch/elasticsearch 7.*

composer dump-autoload

thinkphp elastic类

<?php
namespace Api\Controller;


use Elasticsearch\ClientBuilder;
 
class ElasticController 
{
    private $client;
 
    // 构造函数
    public function __construct(){
        //require $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/vendor/autoload.php';
        $hosts = [
            '127.0.0.1:9200',
        ];
        $this->client =  ClientBuilder::create()->setHosts($hosts)->build();
    }

    public function create(){
        $data = M('member')->where(['status'=>1])->select();        //数据库中查询数据
        $params = [
            'index' => 'user3', #index的名字不能是大写和下划线开头
            'id'=>003,                     //索引id 可自己设计
            'body' => [
                'settings' => [
                    'number_of_shards' => 2,
                    'number_of_replicas' => 0
                ],
                'content' => json_encode($data,true)
            ]
        ];
        //创建索引并写入es
        print_r($this->client->create($params));
    }
 
    // 初始化
    public function index()
    {
 
 
        // 只能创建一次
 
 
        $this->delete_index();
 
        $this->create_index(); //1.创建索引
 
        $this->create_mappings(); //2.创建文档模板
 
 
 
        /* foreach ($docs as $k => $v) {
             $this->add_doc($v['id'], $v); //3.添加文档
             echo '<pre>';
             print_r($this->get_doc($v['id']));
         }
         exit();*/
//        echo '<pre>';
//        print_r($this->get_doc(512));
//        exit();
 
//        $re = $this->search_doc("我做无敌",0,2); //4.搜索结果
//
//        echo '<pre>';
//        print_r($re);
//        exit();
        echo '<pre>';
        print_r("INIT OK");
        exit();
    }
 
 
    public function put_settings()
    {
        $params1 =
            [
 
                'index' => $this->index,
                'body' => [
                    'settings' => [
                        'blocks' =>
                            [
                                'read_only_allow_delete' => 'false'
                            ]
                    ],
                ]
            ];
        $this->client->indices()->putSettings($params1);
        echo 'SUCCESS';
    }
 
    // 创建索引
 
    public function create_index()
    { // 只能创建一次
        $params = [
            'index' => $this->index,
            'body' => [
                'settings' => [
                    'number_of_shards' => 3,
                    'number_of_replicas' => 2,
                    'blocks' =>
                        [
                            'read_only_allow_delete' => 'false'
                        ],
                    /*'transient' =>
                        [
                            'cluster' =>
                                [
                                    'routing' =>
                                        [
                                            'allocation' =>
                                                [
                                                    'disk' =>
                                                        [
                                                            'threshold_enabled' => 'true',
                                                            'watermark' =>
                                                                [
                                                                    'flood_stage' => '99%'
                                                                ]
                                                        ]
                                                ]
                                        ]
                                ]
                        ]*/
                ],
            ]
        ];
 
 
        try {
 
 
            $this->client->indices()->create($params);
 
 
        } catch (BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg, true);
            return $msg;
        }
    }
 
 
    // 删除索引
    public function delete_index()
    {
 
        $params = ['index' => $this->index];
        $index = $this->client->indices()->get($params);
 
        if ($index) {
            return $this->client->indices()->delete($params);
        }
 
        //
 
    }
 
    // 创建文档模板
    public function create_mappings()
    {
 
        /*--------------------允许type的写法 老版本 已去除--------------------------*/
 
 
        /*--------------------不允许type的写法--------------------------*/
        // Set the index and type
        $params = [
            'index' => $this->index,
            'body' => [
                '_source' => [
                    'enabled' => true
                ],
                'properties' => [
                    'id' => [
                        'type' => 'integer',
                    ],
                    'name' => [
                        'type' => 'text',
                        'analyzer' => 'ik_smart'
                        // 'analyzer' => 'keyword'
                    ],
 
                    /*-------------------------------------*/
 
                    /*'profile' => [
                        'type' => 'text',
                        'analyzer' => 'ik_max_word'
                    ],
                    'age' => [
                        'type' => 'integer',
                    ],*/
                ]
            ]
        ];
 
        $this->client->indices()->putMapping($params);
 
        /*       echo '<pre>';
               print_r('success');
               exit();*/
    }
 
    // 查看映射
    public function get_mapping()
    {
        $params = [
            'index' => $this->index,
        ];
        $re = $this->client->indices()->getMapping($params);
        echo '<pre>';
        print_r($re);
        exit();
 
    }
 
    // 添加一个文档(记录)
    public function add_doc($id, $doc)
    {
        $params = [
 
            'index' => $this->index,
            //  'type' => $this->type,
            'id' => $id,
            'body' => $doc
        ];
 
        return $this->client->index($params);
 
    }
 
    // 判断文档(记录)
    public function exists_doc($id = 1)
    {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' => $id
        ];
 
        return $this->client->exists($params);
 
    }
 
    // 获取一条文档(记录)
    public function get_doc($id = 1)
    {
        $params =
            [
                'index' => $this->index,
                // 'type' => $this->type,
                'id' => $id
            ];
 
        try {
 
            $re = $this->client->get($params);
 
        } catch (Missing404Exception $e) {
 
            echo '<pre>';
            print_r('未找到对应数据');
            exit();
 
        }
 
        echo '<pre>';
        print_r($re);
        exit();
 
    }
 
    // 更新一条文档()
    public function update_doc($id = 1)
    {
        // 可以灵活添加新字段,最好不要乱添加
        $params = [
            'index' => $this->index,
            'id' => $id,
            'body' => [
                'doc' => [
                    'name' => '大王'
                ]
            ]
        ];
 
        return $this->client->update($params);
 
    }
 
    // 删除一条文档()
    public function delete_doc($id = 1)
    {
        $params = [
            'index' => $this->index,
            //'type' => $this->type,
            'id' => $id
        ];
 
        return $this->client->delete($params);
 
    }
 
    // 查询文档 (分页,排序,权重,过滤)
    public function search_doc($keywords = "", $from = 0, $size = 10, $order = ['id' => ['order' => 'desc']])
    {
 
        /*   echo '<pre>';
           print_r($from);
           print_r($size);
           exit();*/
        $keywords_arr = array_filter(explode(" ", $keywords));
        $query = '';
        $number = count($keywords_arr);
        if($number > 10){
            return "ERROR";
        }
        if ($number > 1) {
            $arr = [];
            foreach ($keywords_arr as $ka){
                $arr[] = $ka;
            }
            $mathc_phrase = [];
 
            switch ($number){
                case 2:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1]
                        ];
                    break;
                case 3:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2]
                        ];
                    break;
                case 4:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2],
                            'name'=>$arr[3],
                        ];
                    break;
                case 5:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2],
                            'name'=>$arr[3],
                            'name'=>$arr[4],
                        ];
                    break;
                case 6:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2],
                            'name'=>$arr[3],
                            'name'=>$arr[4],
                            'name'=>$arr[5],
                        ];
                    break;
                case 7:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2],
                            'name'=>$arr[3],
                            'name'=>$arr[4],
                            'name'=>$arr[5],
                            'name'=>$arr[6],
                        ];
                    break;
                case 8:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2],
                            'name'=>$arr[3],
                            'name'=>$arr[4],
                            'name'=>$arr[5],
                            'name'=>$arr[6],
                            'name'=>$arr[7],
                        ];
                    break;
                case 9:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2],
                            'name'=>$arr[3],
                            'name'=>$arr[4],
                            'name'=>$arr[5],
                            'name'=>$arr[6],
                            'name'=>$arr[7],
                            'name'=>$arr[8],
                        ];
                    break;
                case 10:
                    $mathc_phrase =
                        [
                            'name'=>$arr[0],
                            'name'=>$arr[1],
                            'name'=>$arr[2],
                            'name'=>$arr[3],
                            'name'=>$arr[4],
                            'name'=>$arr[5],
                            'name'=>$arr[6],
                            'name'=>$arr[7],
                            'name'=>$arr[8],
                            'name'=>$arr[9],
                        ];
                    break;
 
            }
 
           // $should = [];
            /*foreach ($keywords_arr as $k => $keyword) {
 
                 //   $query .= $keyword . " OR ";
                $mathc_phrase[] = ['name'=>$keyword];
 
            }*/
          //  $query = substr($query,0,strlen($query)-3);
 
            $query_func = [
                'bool' =>
                    [
                        'must' =>
                            [
                                //$should
 
                                //$mathc_phrase
                                /*'query_string' =>
                                    [
                                        'default_field' => 'name',
                                        'query' => $query
                                    ]*/
 
 
                                'match_phrase'=>$mathc_phrase,
                               /*  'match_phrase'=>
                                [
                                    'name'=>'研究会',
                                ]*/
                            ]
                    ]
 
 
            ];
            /*echo '<pre>';
            print_r($query_func);
            exit();*/
        } else {
           // $query = $keywords;
 
            $query_func = [
 
                /*-----------------------------name 单字段单匹配---------------------------*/
                'bool' =>
                    [
                        'should' =>
                            [
                                'match_phrase' =>
                                    [
                                        'name' => $keywords
                                    ]
                            ]
                    ]
 
            ];
        }
 
        if ($keywords) {
            $params = [
                'index' => $this->index,
                //  'type' => $this->type,
                'body' => [
                    'query' => $query_func,
 
                    'sort' =>
                        [$order],
                    'from' => $from,
                    'size' => $size
                ]
            ];
 
        } else {
            $params = [
                'index' => $this->index,
                //  'type' => $this->type,
                'body' => [
                    /* 'query' => [
                         'match_all'=>[]
                     ],*/
                    'sort' => [$order]
                    , 'from' => $from, 'size' => $size
                ]
            ];
        }
 
 
        try {
            $re = $this->client->search($params);
        } catch (\Exception $e) {
            echo '<pre>';
            print_r($e->getMessage());
            exit();
        }
 
 
        return $re;
    }
 
 
    /**
     * 批量插入数据到索引
     */
    public function insertCorporation()
    {
        $corporations = Corporation::select();
        foreach ($corporations as $corporation) {
 
            $corporation = $corporation->toArray();
 
            $this->add_doc($corporation['id'], $corporation);
        }
        echo '<pre>';
        print_r('完成了');
        exit();
    }
 
}

通过应用地址插入数据到elastic

HOST/api.php/Elastic/create
image.png

安装elasticsearch可视化工具
https://github.com/qax-os/ElasticHD/releases 自己下载对应系统的版本 这里我安装windows版本的

解压文件后 通过命令行

cd D:\Eshome\esHD  (这里替换掉你下载解压后的文件夹目录)

ElasticHD -p 127.0.0.1:9800

在输入框输入elastic地址 如果是本地 则是127.0.0.1:9200,如果是远程地址,则填写相应的ip加端口


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 227,702评论 6 531
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,143评论 3 415
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 175,553评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,620评论 1 307
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,416评论 6 405
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,940评论 1 321
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,024评论 3 440
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,170评论 0 287
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,709评论 1 333
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,597评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,784评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,291评论 5 357
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,029评论 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,407评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,663评论 1 280
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,403评论 3 390
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,746评论 2 370

推荐阅读更多精彩内容