PHP中使用ElasticSearch最新实例讲解
这篇文章主要介绍了PHP中使用ElasticSearch最新实例讲解,这篇文章的教程是比较详细,有需要的同学可以研究下
网上很多关于ES的例子都过时了,版本很老,这篇文章的测试环境是ES6.5
通过composer安装
composer require 'elasticsearch/elasticsearch'
在代码中引入
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$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,
这个分词器是一个插件,需要单独安装的,参考另一篇文章: