>elasticsearch版本必須 >= 7.0
<br/>
## createIndex - 創建索引
~~~
use \api\Es;
// @param 索引名稱
// @param 字段
// @param setting
Es::createIndex('index', [
'field1' => [
'type' => 'text'
],
'field2' => [
'type' => 'keyword'
],
'field3' => [
'type' => 'text',
// 字段分詞方式
'analyzer' => 'standard'
]
]);
~~~
## deleteIndex - 刪除索引
~~~
use \api\Es;
// @param 要刪除的索引名稱
Es::deleteIndex('index');
~~~
## getMapping - 獲取索引映射信息
~~~
use \api\Es;
// @param 索引名稱
Es::getMapping('index');
~~~
## putMapping - 設置索引字段映射,注意:已經設置過的無法修改
~~~
use \api\Es;
// @param 索引名稱
// @param 字段
Es::putMapping('index', [
'field' => [
'type' => 'text'
]
]);
~~~
## select - 設置查詢字段
~~~
use \api\Es;
// 不設置則查詢所有字段,類似SQL里的 select *
Es::select('field1, field2');
~~~
## from - 指定操作的索引
~~~
use \api\Es;
Es::from('index');
// 也可以簡寫,如下
es('index');
~~~
## where - 查詢條件
~~~
use \api\Es;
Es::where([
'must' => [
[
'match' => ['title' => '索引']
],
[
'range' => [
'timestamp' => ['gt' => 1525760500]
]
]
]
]);
~~~
## order - 排序
~~~
use \api\Es;
Es::order([
'timestamp' => 'desc' // 升序用 asc
]);
~~~
## limit - 查詢條數
~~~
use \api\Es;
// 查詢10條
Es::limit(10);
// 查詢10到20條
Es::limit(10, 10);
~~~
## get - 根據_id快速查詢一條
~~~
$data = es('index')->get(1);
~~~
## all - 查詢多條
~~~
$data = es('index')->select('name, title')->where([
'must' => [
[
'match' => ['title' => '索引']
],
[
'match' => ['name' => 'phpcan']
]
]
])->order([
'timestamp' => 'desc'
])->limit(10, 10)->all();
// 指定查詢后的高亮字段是title
$data = es('index')->select('name, title')->where([
'must' => [
[
'match' => ['title' => '索引']
],
[
'match' => ['name' => 'phpcan']
]
]
])->order([
'timestamp' => 'desc'
])->limit(10, 10)->all([
'title'
]);
~~~
## add - 插入數據
>插入數據時會自動加上 timestamp 字段用來表示數據索引的時間
~~~
// 插入后會返回insertid
$id = es('index')->add([
'title' => 'title',
'name' => 'phpcan'
]);
// 批量插入,第二個參數設置為TRUE表示批量插入操作
es('index')->add([
[
'title' => 'title',
'name' => 'phpcan'
],
[
'title' => 'title',
'name' => 'phpcan'
],
[
'title' => 'title',
'name' => 'phpcan'
],
[
'title' => 'title',
'name' => 'phpcan'
],
[
'title' => 'title',
'name' => 'phpcan'
]
], TRUE);
~~~
## edit - 更新數據
> 注意:更新操作只能通過主鍵來完成
~~~
// @param 主鍵ID
// @param 更新的內容
es('index')->edit(1, [
'title' => 'new title',
'name' => 'new name'
]);
~~~
## delete - 刪除數據
~~~
// 返回刪除的數據條數
$count = es('index')->where([
'must' => [
[
'match' => ['_id' => 1]
]
]
])->delete();
~~~