php操作ElasticSearch搜索引擎流程详解

admin3年前PHP教程30
目录
一、安装二、使用三、新建ES数据库四、创建表五、插入数据六、 查询所有数据七、查询单条数据八、搜索九、测试代码

〝 古人学问遗无力,少壮功夫老始成 〞

如果这篇文章能给你带来一点帮助,希望给飞兔小哥哥一键三连,表示支持,谢谢各位小伙伴们。

一、安装

通过composer安装

?

1
composer require 'elasticsearch/elasticsearch'






二、使用

创建ES类

?

1
2
3
4
5
6
7
8
9
<?php
 
require 'vendor/autoload.php';
 
//如果未设置密码
$es = \Elasticsearch\ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->build();
 
//如果es设置了密码
$es = \Elasticsearch\ClientBuilder::create()->setHosts(['username:password@xxx.xxx.xxx.xxx:9200'])->build()






三、新建ES数据库

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

?

1
2
3
4
5
6
7
8
9
10
11
<?php
$params = [
    'index' => 'autofelix_db', #index的名字不能是大写和下划线开头
    'body' => [
        'settings' => [
            'number_of_shards' => 5,
            'number_of_replicas' => 0
        ]
    ]
];
$es->indices()->create($params);






四、创建表在MySQL里面,光有了数据库还不行,还需要建立表,ES也是一样的ES中的type对应MySQL里面的表ES6以前,一个index有多个type,就像MySQL中一个数据库有多个表一样但是ES6以后,每个index只允许一个type在定义字段的时候,可以看出每个字段可以定义单独的类型在first_name中还自定义了 分词器 ik,这是个插件,是需要单独安装的?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    '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'
                ]
            ]
        ]
    ]
];
$es->indices()->putMapping($params);






五、插入数据现在数据库和表都有了,可以往里面插入数据了在ES里面的数据叫文档可以多插入一些数据,等会可以模拟搜索功能?

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    //'id' => 1, #可以手动指定id,也可以不指定随机生成
    'body' => [
        'first_name' => '飞',
        'last_name' => '兔',
        'age' => 26
    ]
];
$es->index($params);






六、 查询所有数据?

1
2
3
4
<?php
$data = $es->search();
 
var_dump($data);






七、查询单条数据如果你在插入数据的时候指定了id,就可以查询的时候加上id如果你在插入的时候未指定id,系统将会自动生成id,你可以通过查询所有数据后查看其id?

1
2
3
4
5
6
7
<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    'id' =>  //你插入数据时候的id
];
$data = $es->get($params);






八、搜索

ES精髓的地方就在于搜索

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$params = [
    'index' => 'autofelix_db',
    'type' => 'autofelix_table',
    'body' => [
        'query' => [
            'constant_score' => [ //非评分模式执行
                'filter' => [ //过滤器,不会计算相关度,速度快
                    'term' => [ //精确查找,不支持多个条件
                        'first_name' => '飞'
                    ]
                ]
            ]
        ]
    ]
];
 
$data = $es->search($params);
var_dump($data);






九、测试代码

基于Laravel环境,包含删除数据库,删除文档等操作

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
<?php
use Elasticsearch\ClientBuilder;
use Faker\Generator as Faker;
 
/**
 * ES 的 php 实测代码
 */
class EsDemo
{
    private $EsClient = null;
    private $faker = null;
 
    /**
     * 为了简化测试,本测试默认只操作一个Index,一个Type
     */
    private $index = 'autofelix_db';
    private $type = 'autofelix_table';
 
    public function __construct(Faker $faker)
    {
        /**
         * 实例化 ES 客户端
         */
        $this->EsClient = ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->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();
    }
}






到此这篇关于php操作ElasticSearch搜索引擎流程详解的文章就介绍到这了,更多相关php ElasticSearch搜索引擎内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:blog.csdn/weixin_41635750/article/details/121444448

免责声明:本文内容来自用户上传并发布,站点仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。请核实广告和内容真实性,谨慎使用。

相关文章

高防服务器、高防IP和高防CDN选择哪个好?100G国内高防服务器的原理是什么?

在经营网站的过程中,难免会遇见越来越多情况,比如ddos网站流量攻击,ddos流量攻击可以使得网站直接瘫痪,所以为了网站安全和业务服务的正常执行,就需要防护ddos流量攻击,目前防护ddos流量攻击的...

扬州游戏高防服务器租用需要考虑哪些

扬州游戏高防服务器租用需要考虑哪些?如果您计划在扬州租用游戏高防服务器,以下是需要考虑的几个因素:1.服务器性能:选择高性能服务器可以确保您的游戏体验更加流畅,特别是在网络高峰期。2.防御能力:高防服...

PHP解决高并发问题(opcache)

php高并发之opcache今天工作的时候接触到客户的一台服务器,业务逻辑比较简单 。估算pv在120w左右吧,用的是阿里云2c4g的服务器。一大早就开始卡顿了,登陆服务器后查看负载到了八九十。之后就...

从国内访问新加坡服务器延迟多大

从国内访问新加坡服务器延迟多大?从国内访问新加坡服务器的延迟取决于多个因素,比如你所在的地理位置、网络带宽、网络拥塞程度等。一般来说,从中国大陆连接到新加坡服务器的网络延迟通常在100-300毫秒之间...

php将xml转化对象的实例详解

XML文件?1$xml= "123456";将文件转换成对象?1$objectxml = simplexml_load_string($xml);将对象转换个JSON?1$xmlj...

PHP缓存系统APCu扩展的使用

目录APCu 扩展方法说明使用演示总结想必大家都使用过 memcached 或者 redis 这类的缓存系统来做日常的缓存,或者用来抗流量,或者用来保存一些常用的热点数据,其实在小项目中,PHP 也已...