ElasticSearch 6.5环境准备与概述
网络上流传的许多ElasticSearch示例往往版本陈旧,缺乏时效性。本教程采用的测试环境为ElasticSearch 6.5版本,以确保内容的最新性与适用性。
首先需要通过Composer工具进行依赖包的引入与安装。
composer require 'elasticsearch/elasticsearch'
在PHP代码中正确引入相关类库后,即可初始化客户端连接。
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->setHosts(['172.16.55.53'])->build();
接下来将逐步实现一个基础的文档添加与搜索功能流程。
第一步需要新建一个Index(索引)。
需明确概念:Index对应关系型数据库(如MySQL)中的Database(数据库),而非其中的Index(索引),这一点至关重要。
$params = [
'index' => 'myindex', #index的名字不能是大写和下划线开头
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
]
]
];
$client->indices()->create($params);
在MySQL中仅有数据库是不够的,还需建立表结构;同理,在ElasticSearch中,Type(类型)对应MySQL中的Table(表)。
注意:在ES 6之前的版本中,一个Index可以包含多个Type,这类似于MySQL数据库中拥有多张表那样自然。但在ES 6及以后版本中,每个Index仅允许存在一个Type,且未来版本可能会彻底移除Type概念。
Type并非独立定义,而是与字段属性一同在Mapping中进行定义。
$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基本尝试》。
当数据库(Index)和表(Type/Mapping)准备就绪后,即可开始向其中插入数据。
概念说明:此处所说的“数据”,在ElasticSearch术语中被称为Document(文档)。
$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后,即可通过get接口查找指定的文档内容。
$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);
上述流程仅为简单使用示例,并不完整,仅涵盖了文档添加,未涉及文档删除操作。
下面提供完整的测试代码,基于Laravel环境编写。当然,运行环境仅影响执行方式,不影响核心逻辑理解。代码包含基本的常用CRUD操作:
<?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();
}
}
到此这篇关于PHP中使用ElasticSearch最新实例讲解的文章就介绍到这了,更多相关PHP中使用ElasticSearch最内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!