PHP code example of ensi / laravel-elastic-query

1. Go to this page and download the library: Download ensi/laravel-elastic-query 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/ */

    

ensi / laravel-elastic-query example snippets


use Ensi\LaravelElasticQuery\ElasticIndex;

class ProductsIndex extends ElasticIndex
{
    protected string $name = 'test_products';
    protected string $tiebreaker = 'product_id';
}

$searchQuery = ProductsIndex::query();

$hits = $searchQuery
             ->where('rating', '>=', 5)
             ->whereDoesntHave('offers', fn(BoolQuery $query) => $query->where('seller_id', 10)->where('active', false))
             ->sortBy('rating', 'desc')
             ->sortByNested('offers', fn(SortableQuery $query) => $query->where('active', true)->sortBy('price', mode: 'min'))
             ->take(25)
             ->get();

$searchQuery->where('field', 'value');
$searchQuery->where('field', '>', 'value'); // supported operators: `=` `!=` `>` `<` `>=` `<=`
$searchQuery->whereNot('field', 'value'); // equals `where('field', '!=', 'value')`

$searchQuery->whereIn('field', ['value1', 'value2']);
$searchQuery->whereNotIn('field', ['value1', 'value2']);

$searchQuery->whereNull('field');
$searchQuery->whereNotNull('field');

$searchQuery->whereHas('nested_field', fn(BoolQuery $subQuery) => $subQuery->where('field_in_nested', 'value'));
$searchQuery->whereDoesntHave(
    'nested_field',
    function (BoolQuery $subQuery) {
        $subQuery->whereHas('nested_field', fn(BoolQuery $subQuery2) => $subQuery2->whereNot('field', 'value'));
    }
);

$searchQuery->whereMatch('field_one', 'query string');
$searchQuery->whereMultiMatch(['field_one^3', 'field_two'], 'query string', MatchType::MOST_FIELDS);
$searchQuery->whereMultiMatch([], 'query string');  // search by all text fields

$searchQuery->sortBy('field', SortOrder::DESC, SortMode::MAX, MissingValuesMode::FIRST); // field is from main document
$searchQuery->sortByNested(
    'nested_field',
    fn(SortableQuery $subQuery) => $subQuery->where('field_in_nested', 'value')->sortBy('field')
);

$searchQuery->minSortBy('field', 'asc');
$searchQuery->maxSortBy('field', 'asc');
$searchQuery->avgSortBy('field', 'asc');
$searchQuery->sumSortBy('field', 'asc');
$searchQuery->medianSortBy('field', 'asc');

$page = $searchQuery->paginate(15, 45);

$page = $searchQuery->cursorPaginate(10);
$pageNext = $searchQuery->cursorPaginate(10, $page->next);

$aggQuery = ProductsIndex::aggregate();

/** @var \Illuminate\Support\Collection $aggs */
$aggs = $aggQuery
            ->where('active', true)
            ->terms('codes', 'code')
            ->count('product_count', 'product_id')
            ->nested(
                'offers',
                fn(AggregationsBuilder $builder) => $builder->where('seller_id', 10)->minmax('price', 'price')
            );
            

$aggQuery->terms('agg_name', 'field', 25);

$aggQuery->minmax('agg_name', 'field');

$aggQuery->count('agg_name', 'field');

$aggQuery->nested('nested_field', function (AggregationsBuilder $builder) {
    $builder->terms('name', 'field_in_nested');
});

$aggQuery->composite(function (AggregationsBuilder $builder) {
    $builder->where('field', 'value')
        ->whereHas('nested_field', fn(BoolQuery $query) => $query->where('field_in_nested', 'value2'))
        ->terms('field1', 'agg_name1')
        ->minmax('field2', 'agg_name2');
});

$sugQuery = ProductsIndex::suggest();

/** @var \Illuminate\Support\Collection $suggests */
$suggests = $sugQuery->phrase('suggestName', 'name.trigram')
    ->text('glves')
    ->size(1)
    ->shardSize(3)
    ->get();
            

$sugQuery = ProductsIndex::suggest()->text('glves');

$sugQuery->phrase('suggestName1', 'name.trigram')->size(1)->shardSize(3);
    
$sugQuery->phrase('suggestName2', 'name.trigram');
    
/** @var \Illuminate\Support\Collection $suggests */
$suggests = $sugQuery->get();
            

$aggQuery->term('suggestName', 'name.trigram')->text('glves')->...->get();

$aggQuery->phrase('suggestName', 'name.trigram')->text('glves')->...->get();

$index = new ProductsIndex();

$index->isCreated(); // Check if index are created 
$index->create(); // Create index with structure from settings() method
$index->bulk(); // Send bulk request
$index->get(); // Send get request
$index->documentDelete(); // Send documentDelete request
$index->deleteByQuery(); // Send deleteByQuery request
$index->termvectors(); // Send termvectors request

$index->catIndices();
$index->indicesDelete();
$index->indicesRefresh();
$index->indicesReloadSearchAnalyzers();

ElasticQuery::enableQueryLog();

/** @var \Illuminate\Support\Collection|Ensi\LaravelElasticQuery\Debug\QueryLogRecord[] $records */
$records = ElasticQuery::getQueryLog();

ElasticQuery::disableQueryLog();

return [
    'connection' => [
    
        // ..

        'http_async_client' => [HttpClientOptionsBuilder::class, 'getAsyncClient'],
    ],
];

use Http\Adapter\Guzzle7\Client as GuzzleAdapter;
use Http\Client\HttpAsyncClient;

class HttpClientOptionsBuilder
{
    public static function getAsyncClient(): HttpAsyncClient
    {
        return GuzzleAdapter::createWithConfig([]);
    }
}


use Ensi\LaravelElasticQuery\ElasticQuery;

ElasticQuery::getClient()->setAsync(true);

// With async
$promises = [
    'key1' => FirstIndex::query()->get(),
    'key2' => FirstIndex::suggest()->paginate(/* ... */),
];

$results = [];
foreach ($promises as $key => $promise) {
    $results[$key] = $promise->wait();
}

$firstResponse = $results['key1'];

ElasticQuery::getClient()->setAsync(false);

// Without async
$firstResponse = FirstIndex::query()->get()
bash
php artisan vendor:publish --provider="Ensi\LaravelElasticQuery\ElasticQueryServiceProvider"