ElasticSearch与PHP交互
转眼间我们已经对es有一定的了解,接下来我们来了解es与编程语言的交互,由于es大多数是与Java做交互且小编是PHPer,故在此创建
一篇es与php相关文档。
安装
需满足以下条件
PHP 7.0.0 或更高版本
Composer
ext-curl:PHP 的 Libcurl 扩展(详情查看下方注意事项)
原生 JSON 扩展 (ext-json) 1.3.7或更高版本
安装方式:
way-one:
根据官方文档进行安装
地址:https://www.elastic.co/guide/cn/elasticsearch/php/current/_installation_2.html
way-two:
用composer package 进行安装
composer require elasticsearch/elasticsearch +version
注:
composer 安装自行百度。
es-php版本最好与es本身一致。以免出现意想不到的错误。
语法使用
加载 es-php
使用命名空间加载
引入自动加载(如果集成在框架中不必引入,直接用use即可)
require 'vendor/autoload.php';
引入es-php处理类
use Elasticsearch\ClientBuilder;
创建es实例对象
ClientBuilder::create()
->setHosts()
->setElasticMetaHeader()
->includePortInHostHeader()
->setRetries()
->setLogger()
->build();
设置主机
$host = ['http://1x1.3x.8x.1x8:9200', '1xx.3x.8x.1x8:9200',]
日志,存储地址
$logger = new Logger('es-monolog');
$logger -> pushHandler(new StreamHandler($saveFile, Logger::WARNING));
设置日志文件地址
create() -- 创建
setHosts($host) -- 设置连接主机,多个地址,号隔开
setElasticMetaHeader(false|true) -- 是否显示头部
includePortInHostHeader(false|true) -- 用于启用Host表头中的端口
setRetries(5) -- 设置重连次数
setLogger($logger) -- 自定义文件地址 -- (php -Monolog 自行百度)
build() -- 生成连接器
创建索引
注:由于在第二节,ElasticSearch----语法学习中学习过相应语法,故此处只用PHP简单举例且语法与es-json语法相似
相应解释
索引参数
paramData -- 创建索引的参数
创建索引时使用的方法
$this->_esConnection->indices()->create($paramData)
方法具体含义
api-文档
https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-create-index.html
代码详情可用icode进行点击查看
$paramData = [
'index' => 'my_index', // 索引民
'body' =>[
"settings" => [ // 主分片设置
"number_of_shards" => 1, // 分片存储个数
"number_of_replicas" => 1, // 主片存储个数
// 定制化分词器
"analysis" => [
'char_filter' => [ // 词性预处理
'&_to_end' => [ // 过滤名称
'type' => 'mapping',
'mappings' => ['&=> and'],
],
],
'filter' => [ // 词性过滤器
'my_stopwords' => [ //过滤名称
'type' => 'stop', // 类型
'stopwords' => ['the', 'a'] // 过滤词
],
],
'analyzer' => [ // 自定义分词器
'my_analyzer'=> [ // 分词性名称
'type' => 'custom',
'char_filter' => ['html_strip', '&_to_end'], // 预处理方法
'tokenizer' => 'standard', // 分词类型
'filter' => ['lowercase', 'my_stopwords'] // 过滤次方法
],
],
]
],
"mappings" => [ //字段映射
"properties" => [
"title" => [ // 字段名称
'type' => 'keyword', // 字段类型
],
'places' => [
'type'=>'text',
'analyzer' => 'my_analyzer', // 存储引用的分词器 , 存储与搜索时用的分词器是一致的
'search_analyzer' => 'my_analyzer', // 搜索时引用的分词器
],
"age" => [
"type" => 'long'
],
'price' => [
'type' => 'float'
],
],
// 定制化模板
'dynamic_templates' => [
[
'titles' => [
'match' => 'til*', // 属性名包含 title_ 且以它为开头的
'match_mapping_type' => 'string', // 检索类型
'mapping' => [
'type' => 'text',
'analyzer' => 'english', // 存储时引用的分词类型
]
],
],
],
],
'aliases' => [ // 设置别名
'default_index' => new \stdClass(), // 别名名称
],
],
];
$this->_esConnection->indices()->create($paramData);
查询索引
简易查询
$searchParam = [
'index' => ['book'], //索引名
//'_source_includes' => ['name', 'description'], // 返回数据的字段
//'_source_excludes' => ['pic', 'studymodel'], // 返回数据中不包含的字段
//'scroll' => '1m', // 当次查询的时间 , // 用于滚动查询,
//'size' => 1, // 当次查询展示的数据,
//'from' => 10, // 从那条记录开始查找(下标,从0开始)
'body' => [
// **** 查询全部(默认)
//'query' => [
// 'match_all' => new \stdClass(),
//]
// **** 多条件查询
"query" => [
'bool' => [
// **** 全文检索
'must' => [
// **** =单属性匹配
'match' => [
'name' => 'VBootstrap',
],
// **** 多field匹配, field 中的关系为 or
//ss 'multi_match' => [
// 'query' => 'vbootstrap',
// 'fields' => ['name', 'description'],
// ],
// **** 单个--keyword匹配, <=> == 匹配
//'term' => [
// 'studymodel' => '201001'
//],
// **** 多个--keyword匹配, <=> == 匹配
//'terms' => [
// 'studymodel' => ['201001', '201002'],
//]
// **** 查看索引中存在某个字段(属性)的信息
//'exists' => [
// 'field' => 'name',
//],
// **** 相近匹配
//'fuzzy' => [
// 'name' => [
// 'value' => 'cbootstrpa',
// ],
// **** 通过ids查询
//'ids'=>[
// 'values'=>[1,5,9],
//],
// **** 正则表达式 查询
//['regexp' => [
// 'name' => [
// 'value' => 'b.*p'
// ]
//]],
//['ids'=>[
// 'values'=>[1,5,9],
//]]
],
// **** 过滤查找,不进行_score 分数的验证,常用于 数值匹配,keyword 检索
'filter' => [
'range' => [
'price' => [
'gte' => 10,
'lte' => 40,
],
],
],
],
],
// **** 排序
'sort' => [
['price' => ['order'=>'desc',]],
]
],
];
$res = $this->_esConnection->search($params);
聚合查询, 具体请看第二节,ElasticSearch----语法学习
$sedarchParam = [
'body' => [
"aggs" => [
"count_category"=>[
"terms" => [
"field" => "field_category",
],
],
"max_price" => [
"max" => [
"field" => "field_price",
],
],
"min_price" => [
"min" => [
"field"=>"field_price"
],
],
"sum_price" => [
"sum" => [
"field"=>"field_price"
],
],
"avg_price" => [
"avg" => [
"field"=>"field_price"
],
],
]
],
];;
删除索引
$deleteArr = [
'index' => ['my_index'], //索引名多个索引用, 号隔开
];
$res = $this->_esConnection->indices()->delete($deleteArr);
新增索引文档
$paramData = [
'index_field' => 'book', // 索引|文档 名称
'id_field' => 2, // 索引中唯一id
'body_field' => [ // 添加的值
'name_field' => 'xiaobai',
'age_field' => 20,
],
];
$res = $this->_esConnection->index($paramData);
更新索引文档
// 局部更新
$paramData = [
'index' => 'book', // 索引|文档 名称
'id' => 2, // 索引中唯一id
'body' => [ // 更新元素
'doc'=> [
'name' => 'xiaogezi',
],
],
];
//脚本化更新
$age = 5;
$paramData = [
'index' => 'book', // 索引|文档 名称
'id' => 2, // 索引中唯一id
'body' => [ // 更新元素
'script' => "ctx._source.age += {$age}",
],
];
$res = $this->_esConnection->update($paramData);
通用语法
# 查看索引是否存在
$existsArr = [
'index' => ['my_index'], //索引名,多个索引名用,号隔开
];
$res = $this->_esConnection->indices()->exists($existsArr);
# 分词解析
$analyzerArr = [
'index' => 'my_index', //索引名(若不引用索引中的自定义分词器可不用写)
'body' => [ // 测速的数组
'analyzer' => 'my_analyzer', // 分词器
'text'=>'& tom&jerry are a friend in the house, <a>, HAHA!', // 分词器文本
]
];
$res = $this->_esConnection->indices()->analyze($analyzerArr);
# 创建别名
//设置索引别名(增加|修改)
$aliaesArr = [
'index' => ['my_index', 'my_index_new'], // index 要操作的索引名, 多个用, 号隔开
'name' => 'default_index', // 索引别名
];
$res = $this->_esConnection->indices()->putAlias($aliaesArr);
// 删除别名
$res = $this->_esConnection->indices()->deleteAlias($aliaesArr);
// scroll查询
$params = [
'scroll' => '30s', // 滚动请求之间的间隔时间
'size' => 50, // 每次返回多少个结果
'index' => 'my_index' //索引名
];
$res = $this->_esConnection->search($params);
// 注: 下次查询必须带上述查询返回的scroll_id
$this->_esConnection->scroll([
'body' => [
'scroll_id' => $res['scroll_id'], //...using our previously obtained _scroll_id
'scroll' => '30s' // and the same timeout window
]
]);
// es7-sql 查询
$searchParam = [
'format' =>'yaml', // json(default), txt, csv, tsv
'body' => [
'query' => 'select * from tvs'
]
];
$res = $this->_esConnection->sql()->query($searchParam);
总结
ElasticSearch–php-api文档
ElasticSearch官方文档
禁止转载,违者必究
补录
第一节,ElasticSearch----安装部署
第二节,ElasticSearch----语法学习
第三节,ElasticSearch----索引详解
第四节,ElasticSearch----IK分词器
第五节,ElasticSearch----PHP交互