美文网首页
thinkphp使用elasticsearch

thinkphp使用elasticsearch

作者: 回眸淡然笑 | 来源:发表于2023-04-19 18:03 被阅读0次

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

https://repo.huaweicloud.com/elasticsearch/

这里我下载的是7.10.2版本

cd /www/server
wget https://repo.huaweicloud.com/elasticsearch/7.10.2/elasticsearch-7.10.2-linux-x86_64.tar.gz
tar -zxvf elasticsearch-7.10.2-linux-x86_64.tar.gz
cd elasticsearch-7.10.2
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 elasticsearch:elasticsearch elasticsearch-7.10.2

安装ik分词库

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

切换到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']..'/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

相关文章

网友评论

      本文标题:thinkphp使用elasticsearch

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