像使用 Laravel Query 同樣的搜索 Elasticsearch

須要使用到ES大數據引擎,但無奈,不論是官方包仍是Github上都沒有找到本身想要的,那還說什麼呢,本身操刀來一份吧。Github地址:https://github.com/crcms/elasticsearchphp

Composer和安裝和Laravel下的加載laravel

Version Matrix

Elasticsearch Version crcms/elasticsearch Branch
>= 6.0 1.*
>= 5.0, < 6.0 0.*

Install

composer require crcms/elasticsearch

Laravel

Modify config / app.phpgit

'providers' => [
    CrCms\ElasticSearch\LaravelServiceProvider::class,
]

Pubishgithub

php artisan vendor:publish --provider="CrCms\ElasticSearch\LaravelServiceProvider"

直接開始,示例以下:app

Quickstart

Create

Route::get('test/create',function(\CrCms\ElasticSearch\Builder $builder){
    $result = $builder->index('index')->type('type')->create([
        'key' => 'value',
    ]);
    dump($result);
});

Update

Route::get('test/update',function(\CrCms\ElasticSearch\Builder $builder){
    $result = $builder->index('index')->type('type')->update('id',[
        'key' => 'value2',
    ]);
    dump($result);
});

Delete

Route::get('test/delete',function(\CrCms\ElasticSearch\Builder $builder){
    $result = $builder->index('index')->type('type')->delete('id');
    dump($result);
});

Select

Route::get('test/select',function(\CrCms\ElasticSearch\Builder $builder){
    $builder = $builder->index('index')->type('type');
    
    //SQL:select ... where id = 1 limit 1;
    $result = $builder->whereTerm('id',1)->first();
    
    //SQL:select ... where (key=1 or key=2) and key1=1
    $result = $builder->where(function (Builder $inQuery) {
        $inQuery->whereTerm('key',1)->orWhereTerm('key',2)
    })->whereTerm('key1',1)->get();
    
});

More

skip / takecomposer

$builder->take(10)->get(); // or limit(10)
$builder->offset(10)->take(10)->get(); // or skip(10)

term queryelasticsearch

$builder->whereTerm('key',value)->first();

match queryide

$builder->whereMatch('key',value)->first();

range query大數據

$builder->whereBetween('key',[value1,value2])->first();

where in queryui

$builder->whereIn('key',[value1,value2])->first();

logic query

$builder->whereTerm('key',value)->orWhereTerm('key2',value)->first();

nested query

$result = $builder->where(function (Builder $inQuery) {
    $inQuery->whereTerm('key',1)->orWhereTerm('key',2)
})->whereTerm('key1',1)->get();

更多的使用方法詳見Github

最後:若是對您有用請給個Star吧,更多的是歡迎拍磚,支持開源。

文章已同步於laravel-china

相關文章
相關標籤/搜索