PHP code example of shortcodes / scout-elasticsearch-driver

1. Go to this page and download the library: Download shortcodes/scout-elasticsearch-driver 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/ */

    

shortcodes / scout-elasticsearch-driver example snippets




namespace App;

use ScoutElastic\IndexConfigurator;

class MyIndexConfigurator extends IndexConfigurator
{
    // It's not obligatory to determine name. By default it'll be a snaked class name without `IndexConfigurator` part.
    protected $name = 'my_index';  
    
    // You can specify any settings you want, for example, analyzers. 
    protected $settings = [
        'analysis' => [
            'analyzer' => [
                'es_std' => [
                    'type' => 'standard',
                    'stopwords' => '_spanish_'
                ]
            ]    
        ]
    ];
}



namespace App;

use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    use Searchable;

    protected $indexConfigurator = MyIndexConfigurator::class;

    protected $searchRules = [
        //
    ];

    // Here you can specify a mapping for a model fields.
    protected $mapping = [
        'properties' => [
            'text' => [
                'type' => 'text',
                'fields' => [
                    'raw' => [
                        'type' => 'text',
                        'index' => 'not_analyzed',
                    ]
                ]
            ],
        ]
    ];
}

// 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('phone') 
    ->with(['makers', 'company'])
    ->paginate();

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('*')->orderByScript([
    'script' => [
        'lang' => 'groovy',
        'inline' => "
            def rank = 1;
            if (doc['price'].value) {
                rank += doc['total_view'].value*1+doc['total_like'].value*4+doc['total_download'].value*64;
            } else {
                rank += doc['total_view'].value*1+doc['total_like'].value*8+doc['total_download'].value*16;
            }
            return rank;
        "
    ],
    'type' => 'number',
    'order' => 'desc'
])->paginate();

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

App\MyModel::search('*')
    ->aggregate();

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

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



namespace App;

use ScoutElastic\SearchRule;

class MySearchRule extends SearchRule
{
    // This method returns an array, describes how to highlight the results.
    // If null is returned, no highlighting will be used. 
    public function buildHighlightPayload()
    {
        return [
            'fields' => [
                'name' => [
                    'type' => 'plain'
                ]
            ]
        ];
    }
    
    // This method returns an array, that represents bool query.
    public function buildQueryPayload()
    {
        return [
            'must' => [
                'match' => [
                    'name' => $this->builder->query
                ]
            ]
        ];
    }
}

return [
   'must' => [
       'query_string' => [
           'query' => $this->builder->query
       ]
   ]
];



namespace App;

use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    use Searchable;
    
    // You can set several rules for one model. In this case, the first not empty result will be returned.
    protected $searchRules = [
        MySearchRule::class
    ];
}

// You can set either a SearchRule class
App\MyModel::search('Brazil')
    ->rule(App\MySearchRule::class)
    ->get();
    
// or a callable
App\MyModel::search('Brazil')
    ->rule(function($builder) {
        return [
            'must' => [
                'match' => [
                    'Country' => $builder->query
                ]
            ]
        ];
    })
    ->get();



namespace App;

use ScoutElastic\AggregateRule;

class MyAggregateRule extends AggregateRule
{
    // This method returns an array that represents a content of bool query.
    public function buildAggregatePayload()
    {
        return [
            'icon_count' => [
                'terms' => [
                    'field' => 'icon_id',
                    'size' => 15
                ]
            ],
            'style_count' => [
                'terms' => [
                    'field' => 'style_id',
                    'size' => 7
                ]
            ],
            'category_count' => [
                'terms' => [
                    'field' => 'category_id',
                    'size' => 39
                ]
            ]
        ];
    }
}



namespace App;

use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    use Searchable;
    
    // You can set several rules for one model. In this case, the first not empty result will be returned.
    protected $aggregateRules = [
        MyAggregateRule::class
    ];
}



namespace App;

use ScoutElastic\SuggestRule;

class MySuggestRule extends SuggestRule
{
    // This method returns an array that represents a content of bool query.
    public function buildSuggestPayload()
    {
        $query = $this->builder->query;

        if (empty($query)) {
            return null;
        }

        return [
            'text' => $query,
            'autocomplete' => [
                'prefix' => $query,
                'completion' => [
                    'field' => 'name.suggest_autocomplete',
                    'size' => 7
                ],
            ],
            'phrase-suggest' => [
                'phrase' => [
                    'field' => 'name.suggest_phrase.trigram',
                    'gram_size' => 3,
                    'direct_generator' => [
                        [
                            'field' => 'name.suggest_phrase.trigram',
                            'suggest_mode' => 'always'
                        ],
                        [
                            'field' => 'name.suggest_phrase.reverse',
                            'suggest_mode' => 'always',
                            'pre_filter' => 'reverse',
                            'post_filter' => 'reverse'
                        ],
                    ],
                    'highlight' => [
                        'pre_tag' => '<em>',
                        'post_tag' => '</em>'
                    ]
                ]
            ]
        ];
    }
}



namespace App;

use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    use Searchable;
    
    // You can set several rules for one model. In this case, the first not empty result will be returned.
    protected $suggestRules = [
        MySuggestRule::class
    ];
}



namespace App;

use ScoutElastic\HightlightRule;

class MyHightlightRule extends HightlightRule
{
    // This method returns an array that represents a content of bool query.
    public function buildHightlightPayload()
    {
        return [
            'fields' => [
                'name' => [
                    'force_source' => true
                ]
            ]
        ];
    }
}



namespace App;

use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    use Searchable;
    
    // You can set several rules for one model. In this case, the first not empty result will be returned.
    protected $hightlightRules = [
        MyHightlightRule::class
    ];
}

To retrieve highlight, use model `highlight` attribute:


    App\MyModel::search('Brazil')
        ->explain();
    

    App\MyModel::search('Brazil')
        ->profile();
    

App\MyModel::search('Brazil')
    ->buildPayload();

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"

php artisan make:index-configurator MyIndexConfigurator

php artisan elastic:create-index App\\MyIndexConfigurator

php artisan make:searchable-model MyModel --index-configurator=MyIndexConfigurator

php artisan elastic:update-mapping App\\MyModel

php artisan make:aggregate-rule MyAggregateRule

php artisan make:suggest-rule MySuggestRule

php artisan make:hightlight-rule MyHightlightRule