首先我们需要先去安装elasticsearch的SDK
composer require elasticsearch/elasticsearch #安装PHP Client for Elasticsearch
然后封装自己的类
<?php
namespace App\Library\own;
use Elasticsearch\ClientBuilder;
/**
*
*/
class ElasticSearch
{
private static $client;
public function __construct()
{
if (!self::$client) {
self::$client = ClientBuilder::create()->setHosts(['xx.xx.xx.xx'])->build();
}
}
/**
* [createIndex 创建一个索引,类似MySQL的一个库]
* @param [type] $index [description]
* @return [type] [description]
*/
public function createIndex($index)
{
$params = [
'index' => $index,
'body' => [
'settings' => [
'number_of_shards' => 5,
'number_of_replicas' => 1
]
]
];
$response = self::$client->indices()->create($params);
return $response;
}
/**
* [createDoc 新建一条数据]
* @param [type] $index [索引]
* @param [type] $type [类型]
* @param [type] $id [数据ID 可以不要,elasticsearch会自动给你创建一个]
* @param [type] $body [数据]
* @return [type] [description]
*/
public function createDoc($index, $type, $id, $body)
{
$params = [
'index' => $index,
'type' => $type,
'id' => $id,
'body' => $body
];
$response = self::$client->index($params);
return $response;
}
/**
* [getDoc 获取一条数据]
* @param [type] $index [索引位置]
* @param [type] $type [类型]
* @param [type] $id [数据ID]
* @ignore 如果想忽略异常 可以配置ignore参数
* @return [type] [description]
*/
public function getDoc($index, $type, $id)
{
$params = [
'index' => $index,
'type' => $type,
'id' => $id,
'client' => [
'ignore' => 404
]
];
$response = self::$client->get($params);
return $response;
}
/**
* [search 执行搜索]
* @param [type] $index [description]
* @param [type] $type [description]
* @param [type] $body [description]
* @return [type] [description]
*/
public function search($index, $type, $body)
{
$params = [
'index' => $index,
'type' => $type,
'body' => $body,
'client' => [
'ignore' => [400, 404]
]
];
$response = self::$client->search($params);
return $response;
}
}
一个简单的匹配查询并且根据id倒序
$body = [
'query' => [
'match' => [
'title' => 'Linux'
]
],
'sort' => [
['id' => ['order' => 'desc']]
]
];
#这个查询就等同于 SELECT * FROM article WHERE title LIKE '%Linux%' ORDER BY id DESC
$esClient = new ElasticSearch();
$result = $esClient->search('test', 'article', $body);
$body = [
'query' => [
'constant_score' => [
'filter' => [
'range' => [
'id' => [
[
'gt' => 15,
'lt' => 19
]
]
]
]
]
]
];
#这个查询就等同于 SELECT * FROM article WHERE id> 15 AND id < 19
$body = [
'query' => [
'bool' => [
'filter' => [
'term' => [
'id' => 15
]
],
'must' => [
'match_all' => new \StdClass()
]
],
]
];
#这个查询就等同于 SELECT * FROM article WHERE id = 15
$body = [
'query' => [
'bool' => [
'must' => [
[
'term' => [
'title' => 'Linux下面的ab工具压测详细参数'
]
],
[
'term' => [
'id' => 19
]
]
]
]
]
];
#这个查询就等同于 SELECT * FROM article WHERE title = 'Linux下面的ab工具压测详细参数' AND id = 19
以上只是个别的用法,其他的可以参考这里
已有 1 位网友参与,快来吐槽:
发表评论