ElasticSearch 简介与 PHP 集成思路
ElasticSearch 是一款基于 Lucene 构建的搜索服务器,具备分布式多用户能力的全文搜索特性,并通过 RESTful web 接口提供服务。该引擎由 Java 开发,遵循 Apache 许可协议开源发布,是目前主流的企业级搜索引擎方案。其设计初衷面向云计算场景,旨在实现实时搜索,同时保证系统的稳定性、可靠性、高速度以及安装的便捷性。
PHP 基于 ElasticSearch 实现搜索功能
在进行搜索功能开发时,考虑到 ElasticSearch 对 PHP 的支持能力,因此构建了一个简单的测试案例。经过实际测试,效果良好,现将具体过程记录如下。
运行环境
php 7.2
elasticsearch 6.2 下载
elasticsearch-php 6 下载
安装 elasticsearch
首先下载源文件并解压,随后新建一个专用用户,并将解压目录的所属组修改为该用户。这是因为 elasticsearch 出于安全考虑,不允许使用 root 用户直接启动。
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.2.3.tar.gz
tar zxvf elasticsearch-6.2.3.tar.gz
useradd elasticsearch
password elasticsearch
chown elasticsearch:elasticsearch elasticsearch-6.2.3
cd elasticsearch-6.2.3
./bin/elasticsearch // 启动
安装 PHP 扩展
此处采用 composer 方式安装 elasticsearch-php。需在 composer.json 文件中添加 "elasticsearch/elasticsearch": "~6.0" 依赖配置,然后执行 composer update 命令完成安装。
{
"require": {
// ...
"elasticsearch/elasticsearch": "~6.0"
// ...
}
}
测试例子
创建表和测试数据
本次测试选用一张文章表作为数据源。首先执行建表操作,随后写入测试数据。在准备工作就绪后,开始编写具体的测试用例代码。
create table articles(
id int not null primary key auto_increment,
title varchar(200) not null comment '标题',
content text comment '内容'
);
insert into articles(title, content) values ('Laravel 测试1', 'Laravel 测试文章内容1'),
('Laravel 测试2', 'Laravel 测试文章内容2'),
('Laravel 测试3', 'Laravel 测试文章内容3');
从 Mysql 读取数据
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', 'root');
$sql = 'select * from articles';
$query = $db->prepare($sql);
$query->execute();
$lists = $query->fetchAll();
print_r($lists);
} catch (Exception $e) {
echo $e->getMessage();
}
实例化
require './vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->build();
概念说明:在 ElasticSearch 中,索引(Index)的概念对应于 MySQL 中的表(Table),而文档(Document)则对应于 MySQL 中的行记录(Row)。
得益于 ElasticSearch 的动态特性,当添加第一个文档时,系统会自动创建相应的索引并应用默认设置。
将文档加入索引
foreach ($lists as $row) {
$params = [
'body' => [
'id' => $row['id'],
'title' => $row['title'],
'content' => $row['content']
],
'id' => 'article_' . $row['id'],
'index' => 'articles_index',
'type' => 'articles_type'
];
$client->index($params);
}
从索引中获取文档
$params = [
'index' => 'articles_index',
'type' => 'articles_type',
'id' => 'articles_1'
];
$res = $client->get($params);
print_r($res);
从索引中删除文档
$params = [
'index' => 'articles_index',
'type' => 'articles_type',
'id' => 'articles_1'
];
$res = $client->delete($params);
print_r($res);
删除索引
$params = [
'index' => 'articles_index'
];
$res = $client->indices()->delete($params);
print_r($res);
创建索引
$params['index'] = 'articles_index';
$params['body']['settings']['number_of_shards'] = 2;
$params['body']['settings']['number_of_replicas'] = 0;
$client->indices()->create($params);
搜索
$params = [
'index' => 'articles_index',
'type' => 'articles_type',
];
$params['body']['query']['match']['content'] = 'Laravel';
$res = $client->search($params);
print_r($res);
以上即为 PHP 基于 ElasticSearch 实现搜索功能的详细内容,希望本站整理的内容能够帮助到大家。