使用PHP操作ElasticSearch
如何搭建ES环境和使用CURL操作可以参考我的另一篇文章: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,
这个分词器是一个插件,需要单独安装的,参考另一篇文章:ElasticSearch基本尝试
现在 数据库和表都有了,可以往里面插入数据了
概念:这里的 数据 在ES中叫 文档
$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查找指定文档了:
$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环境,当然环境只影响运行,不影响理解,包含基本的常用操作:
<?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的更多相关文章
- 使用curl命令操作elasticsearch
使用curl命令操作elasticsearch 大岩不灿 发表于 2015年4月25日 浏览 7,426 次 第一:_cat系列_cat系列提供了一系列查询elasticsearch集群状态的接口.你 ...
- 使用Java客户端操作elasticsearch(二)
承接上文,使用Java客户端操作elasticsearch,本文主要介绍 常见的配置 和Sniffer(集群探测) 的使用. 常见的配置 前面已介绍过,RestClientBuilder支持同时提供一 ...
- java操作elasticsearch实现组合桶聚合
1.terms分组查询 //分组聚合 @Test public void test40() throws UnknownHostException{ //1.指定es集群 cluster.name 是 ...
- java操作elasticsearch实现query String
1.CommonTersQuery: 指定字段进行模糊查询 //commonTermsQuery @Test public void test35() throws UnknownHostExcept ...
- java操作elasticsearch实现聚合查询
1.max 最大值 //max 求最大值 @Test public void test30() throws UnknownHostException{ //1.指定es集群 cluster.name ...
- java操作elasticsearch实现前缀查询、wildcard、fuzzy模糊查询、ids查询
1.前缀查询(prefix) //prefix前缀查询 @Test public void test15() throws UnknownHostException { //1.指定es集群 clus ...
- java操作elasticsearch实现条件查询(match、multiMatch、term、terms、reange)
1.条件match query查询 //条件查询match query @Test public void test10() throws UnknownHostException { //1.指定e ...
- java操作elasticsearch实现查询删除和查询所有
后期博客本人都只给出代码,具体的说明在代码中也有注释. 1.查询删除 //查询删除:将查询到的数据进行删除 @Test public void test8() throws UnknownHostEx ...
- java操作elasticsearch实现批量添加数据(bulk)
java操作elasticsearch实现批量添加主要使用了bulk 代码如下: //bulk批量操作(批量添加) @Test public void test7() throws IOExcepti ...
- 学习用Node.js和Elasticsearch构建搜索引擎(3):使用curl命令操作elasticsearch
使用Elasticsearch不免要提到curl工具,curl是利用URL语法在命令行方式下工作的开源文件传输工具.官网地址:https://curl.haxx.se/ 因为elasticsearch ...
随机推荐
- 开辟sys节点用户层直接操作物理地址(比/dev/mem方便)
在调试驱动程序时, 经常要设置主控器寄存器参数或者运行时读取寄存器值debug问题, 每次修改驱动读取寄存器值都要编译一次驱动再insmod, 十分不方便, 哪怕驱动提供一个节点 如dev/mem给应 ...
- Windows系统pip安装whl包
1.确保PIP的存在 2.CMD命令进入C:\Python34\Scripts里面后再执行PIP命令安装pip install wheel # D: 和cd 地址 3.把文件最好放在\S ...
- Docker进阶之一:Docker介绍与体系结构
一. Docker是什么 Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源,基于Linux内核的cgroup,namespace,Union FS 等技术, ...
- 痞子衡嵌入式:ARM Cortex-M内核MCU开发那些事 - 索引
大家好,我是痞子衡,是正经搞技术的痞子.本系列痞子衡给大家介绍的是ARM Cortex-M内核微控制器相关知识. ARM公司从2004年开始推出Cortex-M系列内核,迄今Cortex-M家族已经包 ...
- Springboot 系列(八)动态Banner与图片转字符图案的手动实现
使用过 Springboot 的对上面这个图案肯定不会陌生,Springboot 启动的同时会打印上面的图案,并带有版本号.查看官方文档可以找到关于 banner 的描述 The banner tha ...
- 树莓派linux系统中显示隐藏文件的几种方法
一.如果直接使用可视化文件管理器 1.直接点击右键,直接选择“显示隐藏文件”选项. 2.快捷键 CTRL + H 二.在终端命令行模式下 可以使用ls命令的-a参数来显示隐藏的文件及文件夹. ls - ...
- ioc初步理解(二) 简单实用autofac搭建mvc三层+automapper=》ioc(codeFirst)
之前在园子闲逛的时候,发现许多关于automapper的文章,以及用aotufac+automapper合在一起用.当然发现大多数文章是将automapper的特点说出或将automapper几处关键 ...
- Struts2笔记_拦截器
A.拦截器是什么 --- Interceptor:拦截器,起到拦截Action的作用. ---Filter:过滤器,过滤从客户端向服务器发送的请求. ---Interceptor:拦截器,拦截是客户端 ...
- 数据库缓存mybatis,redis
简介 处理并发问题的重点不在于你的设计是怎样的,而在于你要评估你的并发,并在并发范围内处理.你预估你的并发是多少,然后测试r+m是否支持.缓存的目的是为了应对普通对象数据库的读写限制,依托与nosql ...
- 纯CSS编写汉克狗
1,CSS中原生的变量定义语法是:--*,变量使用语法是:var(--*),其中*表示我们的变量名称:在CSS变量命名中,不能包含$,[,^,(,%等字符,普通字符局限在只要是“数字[0-9]”“字母 ...