PHP code example of archerzdip / hyperf-elasticsearch

1. Go to this page and download the library: Download archerzdip/hyperf-elasticsearch library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

archerzdip / hyperf-elasticsearch example snippets




namespace App\ElasticIndexConfigurator;

use ArcherZdip\ScoutElastic\IndexConfigurator;
use ArcherZdip\ScoutElastic\Traits\Migratable;

class MyIndexConfigurator extends IndexConfigurator
{
    use Migratable;

    protected $name = 'my_index';

    /**
     * @var array
     */
    protected $settings = [
        'analysis' => [
            'analyzer' => [
                'es_std' => [
                    'type' => 'standard',
                    'stopwords' => '_spanish_'
                ]
            ]    
        ]
    ];
}

// set query string
App\MyModel::search('phone')
    // specify columns to select
    ->select(['title', 'price'])
    // filter 
    ->where('color', 'red')
    // sort
    ->orderBy('price', 'asc')
    // collapse by field
    ->collapse('brand')
    // set offset
    ->from(0)
    // set limit
    ->take(10)
    // get results
    ->get();

App\MyModel::search('phone') 
    ->count();

App\MyModel::search('phone') 
    ->with('makers')
    ->get();

App\MyModel::search('*')
    ->where('id', 1)
    ->get();

App\MyModel::search('Brazil')
    ->rule(App\MySearchRule::class)
    ->get();

App\MyModel::search('*')
    ->whereRegexp('name.raw', 'A.+')
    ->where('age', '>=', 30)
    ->whereExists('unemployed')
    ->get();

App\MyModel::search('sales')
    ->minScore(1.0)
    ->get();

$model = App\MyModel::search('sales')
    ->orderRaw([
       '_geo_distance' =>  [
           'coordinates' => [
               'lat'   =>  51.507351,
               'lon'   =>  -0.127758
           ],
           'order'     =>  'asc',
           'unit'      =>  'm'
       ]
    ])
    ->get();

// To retrieve sort result, use model `sortPayload` attribute:
$model->sortPayload;

App\MyModel::searchRaw([
    'query' => [
        'bool' => [
            'must' => [
                'match' => [
                    '_all' => 'Brazil'
                ]
            ]
        ]
    ]
]);

## 直接返回ES数据
App\MyModel::search("test")->raw();

shell
php bin/hyperf.php vendor:publish archerzdip/hyperf-elasticsearch
shell script
php bin/hyperf.php make:index-configurator MyIndexConfigurator
shell script
php bin/hyperf.php make:searchable-model MyModel

php bin/hyperf.php make:search-rule MySearchRule