基于docker安装Elasticsearch配合php应用

1.安装docker环境

centos7.0  内核3.10.*
 

yum list docker-ce

sudo yum install docker-ce-17.12.0.ce

ps:安装18以上会发现内核版本不够出现错误,因此选择这个版本

2.开启自启动

sudo systemctl start docker
sudo systemctl enable docker

3.查看docker 版本 正常显示为安装成功

docker version

4.因包含旧docker版本而安装失败的需要先卸载旧版

sudo yum remove docker  docker-common docker-selinux docker-engine

0.在安装es之前,首先编辑一下宿主机的内核参数,否则配置es集群的时候极有可能启动不成功:

[root@study-01 ~]# vim /etc/sysctl.conf
vm.max_map_count=655360
[root@study-01 ~]# sysctl -p # 加载参数

1.下载需要的Elasticsearch镜像

查看可下载的Elasticsearch镜像列表

docker search elasticsearch

2.pull镜像

#elasticsearch服务
docker pull docker.elastic.co/elasticsearch/elasticsearch:6.6.2
#可视化elasticsearch服务
docker  pull mobz/elasticsearch-head:5

3.启动

#可视化服务启动
docker run -itd --name es-head -p 9100:9100 mobz/elasticsearch-head:5
#elasticsearch服务启动
docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:6.6.2

4.访问 ip:9200出现下图为成功


1.由于容器默认不自带vi或vim命令,所以我们还得先进入到容器里,将所有的实例都安装上vim命令,示例如下:

[root@study-01 ~]# docker exec -it 容器ID bash
root@2dc233622dcb:/usr/share/elasticsearch# apt-get update
root@2dc233622dcb:/usr/share/elasticsearch# apt-get install vim -y

2.配置文件修改支持跨域提供可视化插件访问:

root@2dc233622dcb:/usr/share/elasticsearch# vim config/elasticsearch.yml # 在文件末尾加入如下内容
# 开启跨域,为了让es-head可以访问
http.cors.enabled: true
http.cors.allow-origin: "*"

3.中文分词elasticsearch-analysis-ik插件安装

root@2dc233622dcb:/usr/share/elasticsearch# wget https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.6.12/elasticsearch-analysis-ik-5.6.12.zip   # 下载压缩包
然后在es的plugins目录下创建ik目录,并解压下载的安装包到该目录下:

root@2dc233622dcb:/usr/share/elasticsearch# mkdir ./plugins/ik   # 创建ik目录
root@2dc233622dcb:/usr/share/elasticsearch# unzip elasticsearch-analysis-ik-5.6.12.zip  # 解压
root@2dc233622dcb:/usr/share/elasticsearch# mv elasticsearch/* plugins/ik/  # 移动解压后的文件
root@2dc233622dcb:/usr/share/elasticsearch# rm -rf elasticsearch   # 删除空目录
root@2dc233622dcb:/usr/share/elasticsearch# cd plugins/ik/
root@2dc233622dcb:/usr/share/elasticsearch/plugins/ik# ls   # 该插件所包含的文件如下
commons-codec-1.9.jar    elasticsearch-analysis-ik-5.6.12.jar  plugin-descriptor.properties
commons-logging-1.2.jar  httpclient-4.5.2.jar
config           httpcore-4.4.4.jar
root@2dc233622dcb:/usr/share/elasticsearch/plugins/ik#

4.进入es-head容器配置,允许所以ip访问


root@85f03139f1ba:/usr/src/app# vim Gruntfile.js
connect: {
        server: {
                options: {
                        hostname: '0.0.0.0',  # 增加这段
                        port: 9100,
                        base: '.',
                        keepalive: true
                }
        }
}

5.访问 ip:9100出现下面页面则成功,图中url是elasticsearch访问地址


1.php操作elasticsearch,通过composer 安装

composer require 'elasticsearch/elasticsearch'

在代码中引入


use Elasticsearch\ClientBuilder;

require 'vendor/autoload.php'; 

$client = ClientBuilder::create()->setHosts(['172.16.55.53'])->build();
 

下面循序渐进完成一个简单的添加和搜索的功能。

首先要新建一个 index:

index 对应关系型数据(以下简称MySQL)里面的数据库,而不是对应MySQL里面的索引,这点要清楚

 

$params = [
    'index' => 'myindex', #index的名字不能是大写和下划线开头
    'body' => [
        'settings' => [
            'number_of_shards' => 2,
            'number_of_replicas' => 0
        ]
    ]
];
$client->indices()->create($params);

 

在MySQL里面,光有了数据库还不行,还需要建立表,ES也是一样的,ES中的type对应MySQL里面的表。

注意:ES6以前,一个index有多个type,就像MySQL中一个数据库有多个表一样自然,但是ES6以后,每个index只允许一个type,在往以后的版本中很可能会取消type。

type不是单独定义的,而是和字段一起定义

 

$params = [
    'index' => 'myindex',
    'type' => 'mytype',
    'body' => [
        'mytype' => [
            '_source' => [
                'enabled' => true
            ],
            'properties' => [
                'id' => [
                    'type' => 'integer'
                ],
                'first_name' => [
                    'type' => 'text',
                    'analyzer' => 'ik_max_word'
                ],
                'last_name' => [
                    'type' => 'text',
                    'analyzer' => 'ik_max_word'
                ],
                'age' => [
                    'type' => 'integer'
                ]
            ]
        ]
    ]
];
$client->indices()->putMapping($params);

 

在定义字段的时候,可以看出每个字段可以定义单独的类型,在first_name中还自定义了 分词器 ik,

这个分词器是一个插件,需要单独安装的,参考另一篇文章:ElasticSearch基本尝试

现在 数据库和表都有了,可以往里面插入数据了

概念:这里的 数据 在ES中叫 文档

 

$params = [
    'index' => 'myindex',
    'type' => 'mytype',
    //'id' => 1, #可以手动指定id,也可以不指定随机生成
    'body' => [
        'first_name' => '张',
        'last_name' => '三',
        'age' => 35
    ]
];
$client->index($params);

 

多插入一点数据,然后来看看怎么把数据取出来:

通过id取出单条数据:

插曲:如果你之前添加文档的时候没有传入id,ES会随机生成一个id,这个时候怎么通过id查?id是多少都不知道啊。

所以这个插入一个简单的搜索,最简单的,一个搜索条件都不要,返回所有index下所有文档:

$data = $client->search();

现在可以去找一找id了,不过你会发现id可能长这样:zU65WWgBVD80YaV8iVMk,不要惊讶,这是ES随机生成的。

现在可以通过id查找指定文档了:

 

$params = [
    'index' => 'myindex',
    'type' => 'mytype',
    'id' =>'zU65WWgBVD80YaV8iVMk'
];
$data = $client->get($params);

 

最后一个稍微麻烦点的功能:

注意:这个例子我不打算在此详细解释,看不懂没关系,这篇文章主要的目的是基本用法,并没有涉及到ES的精髓地方,

ES精髓的地方就在于搜索,后面的文章我会继续深入分析

 

$query = [
    'query' => [
        'bool' => [
            'must' => [
                'match' => [
                    'first_name' => '张',
                ]
            ],
            'filter' => [
                'range' => [
                    'age' => ['gt' => 76]
                ]
            ]
        ]

    ]
];
$params = [
    'index' => 'myindex',
//  'index' => 'm*', #index 和 type 是可以模糊匹配的,甚至这两个参数都是可选的
    'type' => 'mytype',
    '_source' => ['first_name','age'], // 请求指定的字段
    'body' => array_merge([
        'from' => 0,
        'size' => 5
    ],$query)
];
$data = $this->EsClient->search($params);

2.封装类

<?php

use Elasticsearch\ClientBuilder;
use Faker\Generator as Faker;

/**
 * ES 的 php 实测代码
 */
class EsDemo
{
    private $EsClient = null;
    private $faker = null;
    /**
     * 为了简化测试,本测试默认只操作一个Index,一个Type,
     * 所以这里固定为 megacorp和employee
     */
    private $index = 'megacorp';
    private $type = 'employee';
    public function __construct(Faker $faker)
    {
        /**
         * 实例化 ES 客户端
         */
        $this->EsClient = ClientBuilder::create()->setHosts(['172.16.55.53'])->build();
        /**
         * 这是一个数据生成库,详细信息可以参考网络
         */
        $this->faker = $faker;
    }
    
    /**
     * 批量生成文档
     * @param $num
     */
    public function generateDoc($num = 100) {
        foreach (range(1,$num) as $item) {
            $this->putDoc([
                'first_name' => $this->faker->name,
                'last_name' => $this->faker->name,
                'age' => $this->faker->numberBetween(20,80)
            ]);
        }
    }
    /**
     * 删除一个文档
     * @param $id
     * @return array
     */
    public function delDoc($id) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' =>$id
        ];
        return $this->EsClient->delete($params);
    }
    /**
     * 搜索文档,query是查询条件
     * @param array $query
     * @param int $from
     * @param int $size
     * @return array
     */
    public function search($query = [], $from = 0, $size = 5) {
//        $query = [
//            'query' => [
//                'bool' => [
//                    'must' => [
//                        'match' => [
//                            'first_name' => 'Cronin',
//                        ]
//                    ],
//                    'filter' => [
//                        'range' => [
//                            'age' => ['gt' => 76]
//                        ]
//                    ]
//                ]
//
//            ]
//        ];
        $params = [
            'index' => $this->index,
//            'index' => 'm*', #index 和 type 是可以模糊匹配的,甚至这两个参数都是可选的
            'type' => $this->type,
            '_source' => ['first_name','age'], // 请求指定的字段
            'body' => array_merge([
                'from' => $from,
                'size' => $size
            ],$query)
        ];
        return $this->EsClient->search($params);
    }

    /**
     * 一次获取多个文档
     * @param $ids
     * @return array
     */
    public function getDocs($ids) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => ['ids' => $ids]
        ];
        return $this->EsClient->mget($params);
    }

    /**
     * 获取单个文档
     * @param $id
     * @return array
     */
    public function getDoc($id) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' =>$id
        ];
        return $this->EsClient->get($params);
    }

    /**
     * 更新一个文档
     * @param $id
     * @return array
     */
    public function updateDoc($id) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' =>$id,
            'body' => [
                'doc' => [
                    'first_name' => '张',
                    'last_name' => '三',
                    'age' => 99
                ]
            ]
        ];
        return $this->EsClient->update($params);
    }

    /**
     * 添加一个文档到 Index 的Type中
     * @param array $body
     * @return void
     */
    public function putDoc($body = []) {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
//            'id' => 1, #可以手动指定id,也可以不指定随机生成
            'body' => $body
        ];
        $this->EsClient->index($params);
    }
    /**
     * 删除所有的 Index
     */
    public function delAllIndex() {
        $indexList = $this->esStatus()['indices'];
        foreach ($indexList as $item => $index) {
            $this->delIndex();
        }
    }
    /**
     * 获取 ES 的状态信息,包括index 列表
     * @return array
     */
    public function esStatus() {
        return $this->EsClient->indices()->stats();
    }

    /**
     * 创建一个索引 Index (非关系型数据库里面那个索引,而是关系型数据里面的数据库的意思)
     * @return void
     */
    public function createIndex() {
        $this->delIndex();
        $params = [
            'index' => $this->index,
            'body' => [
                'settings' => [
                    'number_of_shards' => 2,
                    'number_of_replicas' => 0
                ]
            ]
        ];
        $this->EsClient->indices()->create($params);
    }

    /**
     * 检查Index 是否存在
     * @return bool
     */
    public function checkIndexExists() {
        $params = [
            'index' => $this->index
        ];
        return $this->EsClient->indices()->exists($params);
    }

    /**
     * 删除一个Index
     * @return void
     */
    public function delIndex() {
        $params = [
            'index' => $this->index
        ];
        if ($this->checkIndexExists()) {
            $this->EsClient->indices()->delete($params);
        }
    }

    /**
     * 获取Index的文档模板信息
     * @return array
     */
    public function getMapping() {
        $params = [
            'index' => $this->index
        ];
        return $this->EsClient->indices()->getMapping($params);
    }

    /**
     * 创建文档模板
     * @return void
     */
    public function createMapping() {
        $this->createIndex();
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => [
                $this->type => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
                        'id' => [
                            'type' => 'integer'
                        ],
                        'first_name' => [
                            'type' => 'text',
                            'analyzer' => 'ik_max_word'
                        ],
                        'last_name' => [
                            'type' => 'text',
                            'analyzer' => 'ik_max_word'
                        ],
                        'age' => [
                            'type' => 'integer'
                        ]
                    ]
                ]
            ]
        ];
        $this->EsClient->indices()->putMapping($params);
        $this->generateDoc();
    }

}

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值