一、前言
这部分是Elasticsearch-php
的实操篇,更多的是在框架中的测试。博主这边用的是Yii2.0
框架。
基础篇:https://blog.youkuaiyun.com/LJFPHP/article/details/89113776
二、正文
1、首先是配置hosts
(1) 如果是本地测试:
$hosts = [
'localhost:9200', // IP + Port
];
(2) 也可以通过hosts限制用户:
$hosts = [
'http://user:pass@localhost:9200', // HTTP Basic Authentication
'http://user2:pass2@other-host.com:9200' // Different credentials on different host
];
2、索引相关操作:
(1) 创建索引
$params = [
'index' => 'my_index'
];
$response = $client->indices()->create($params);
(2) 查看索引
$params = ['index' => 'my_index'];
$response = $client->indices()->getSettings($params);
(3) 修改索引
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_replicas' => 0,
'refresh_interval' => -1
]
]
];
$response = $client->indices()->putSettings($params);
(4) 删除索引:
$params = ['index' => 'my_index'];
$response = $client->indices()->delete($params);
这部分看起来很像是mysql的增删改查,但返回的数据和数据库不一样,返回的都是es的标准对象数组。
3、索引的映射操作
(1) 在创建索引的时候,就可以设置mappings。这里的mappings可以理解为数据库的字段,我们在设置的时候,会指定字段名称,字段类型等。
更改或者创建索引的映射:
$params = [
'index' => 'my_index',
'type' => 'my_type2',
'body' => [
'my_type2' => [
'_source' => [
'enabled' => true
],
'properties' => [
'first_name' => [
'type' => 'string',
'analyzer' => 'standard'
],
'age' => [
'type' => 'integer'
]
]
]
]
];
$client->indices()->putMapping($params);
(2) Get Mappings API
返回索引和类型的映射细节。
$params = ['index' => 'my_index'];
$response = $client->indices()->getMapping($params);
关于索引的操作都在: \Elasticsearch\Namespaces\Indices.php 文件下
4、索引文档:
当创建好索引和mapping之后,我们需要把文档加入到索引中去:
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id', //可以不指定id,不指定的话,es会自动生成一个随机字符串,
//‘routing’=>'xxxxx',
'body' => [ 'testField' => 'abc']
];
$response = $client->index($params);
自动生成的id,长度为20
个字符,URL安全,base64
编码,GUID
,分布式系统并行生成时不可能会发生冲突。如果需要添加Routing等参数,可以写在index和type的后面。如上
批量索引,批量数据导入等,参考bulk索引:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
5、查询:
查询是重头戏,这里的查询,根据文档来看,就类似于我们平时用的sql语句,拆分一下就可以了
例如:
sql:
SELECT product
FROM products
WHERE (price = 20 OR productID = "XHDK-A-1293-#fJ3")
AND (price != 30)
这种情况下,我们需要 bool
(布尔)过滤器。 这是个 复合过滤器(compound filter
) ,它可以接受多个其他过滤器作为参数,并将这些过滤器结合成各式各样的布尔(逻辑)组合。
ES搜索:
GET /my_store/products/_search
{
"query" : {
"filtered" : { //我们仍然需要一个 filtered 查询将所有的东西包起来
"filter" : {
"bool" : {
"should" : [
{ "term" : {"price" : 20}}, //在 should 语句块里面的两个 term 过滤器与 bool 过滤器是父子关系,两个 term 条件需要匹配其一。
{ "term" : {"productID" : "XHDK-A-1293-#fJ3"}}
],
"must_not" : {
"term" : {"price" : 30} //如果一个产品的价格是 30 ,那么它会自动被排除,因为它处于 must_not 语句里面。
}
}
}
}
}
}
以上只是个简单的例子,我们在实际开发中,肯定会用到很多复杂的组合,且学且珍惜吧。
参考ES手册:https://www.elastic.co/guide/cn/elasticsearch/guide/current/combining-filters.html