PHP code example of bonu / php-elasticsearch-builder

1. Go to this page and download the library: Download bonu/php-elasticsearch-builder 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/ */

    

bonu / php-elasticsearch-builder example snippets


use Elastic\Elasticsearch\ClientBuilder;
use Bonu\ElasticsearchBuilder\QueryBuilder;
use Bonu\ElasticsearchBuilder\Query\TermQuery;
use Bonu\ElasticsearchBuilder\Query\BoolQuery;
use Bonu\ElasticsearchBuilder\Query\MatchQuery;

$builder = new QueryBuilder('products')
    ->query(new TermQuery('ean', 'foo_bar_123')->boost(12))
    ->query(new BoolQuery()
        ->should(new MatchQuery('name', 'foo'))
        ->should(new MatchQuery('description', 'bar'))
        ->boost(5)
    )
    ->size(20);

$client = ClientBuilder::create()->build();
$products = $client->search($builder->build());

use Bonu\ElasticsearchBuilder\Query\BoolQuery;
use Bonu\ElasticsearchBuilder\Query\TermQuery;
use Bonu\ElasticsearchBuilder\Query\CompositeQuery;

class PubliclyVisibleProductsQuery extends CompositeQuery
{
    /**
     * @inheritDoc
     */
    public function query(): QueryInterface
    {
        return new BoolQuery()
            ->must(new TermQuery('is_active', true))
            ->mustNot(new TermQuery('is_out_of_stock', false));
    }
}

$builder = new QueryBuilder('products')
    ->query(new PubliclyVisibleProductsQuery());

use Bonu\ElasticsearchBuilder\Query\TermQuery;

new TermQuery('field', 'value')->boost(10)

use Bonu\ElasticsearchBuilder\Query\TermsQuery;

new TermsQuery('status', ['active', 'pending'])->boost(5)

use Bonu\ElasticsearchBuilder\Query\ExistsQuery;

new ExistsQuery('field')

use Bonu\ElasticsearchBuilder\Query\MatchQuery;

// Default operator is OR
new MatchQuery('field', 'some text')
    ->boost(2)
    ->analyzer('standard')

// With AND operator
new MatchQuery('field', 'some text', MatchQuery::OPERATOR_AND)

use Bonu\ElasticsearchBuilder\Query\MatchPhraseQuery;

// Optional third argument is slop
new MatchPhraseQuery('field', 'exact phrase', 2)
    ->boost(1.5)
    ->analyzer('standard')

use Bonu\ElasticsearchBuilder\Query\BoolQuery;
use Bonu\ElasticsearchBuilder\Query\TermQuery;
use Bonu\ElasticsearchBuilder\Query\MatchQuery;

new BoolQuery()
    ->must(new TermQuery('status', 'active'))
    ->filter(new TermQuery('stock', 1))
    ->should(new MatchQuery('title', 'awesome product'))
    ->mustNot(new TermQuery('blocked', true))
    ->boost(3)

use Bonu\ElasticsearchBuilder\Query\NestedQuery;
use Bonu\ElasticsearchBuilder\Query\MatchQuery;

// Query nested field path, inner query must be provided via ->query()
new NestedQuery('variants')
    ->query(new MatchQuery('variants.name', 'red'))

use Bonu\ElasticsearchBuilder\Query\NumericRangeQuery;
use Bonu\ElasticsearchBuilder\Query\DatetimeRangeQuery;

new NumericRangeQuery('price', gte: 100)
    ->boost(10);

new DatetimeRangeQuery('created_at', lt: date('Y-m-d'), format: 'yyyy-MM-dd', timeZone: 'Europe/Prague')
    ->boost(20);

use Bonu\ElasticsearchBuilder\Aggregation\TermsAggregation;
use Bonu\ElasticsearchBuilder\Aggregation\NestedAggregation;
use Bonu\ElasticsearchBuilder\Aggregation\CompositeAggregation;

class CategoryBrandAggregation extends CompositeAggregation
{
    /**
     * @param string|\Stringable $name
     */
    public function __construct(
        private readonly string | Stringable $name,
    ) {}

    /**
     * @inheritDoc
     */
    public function aggregation(): AggregationInterface
    {
        return new NestedAggregation($this->name, 'products')
            ->aggregation(new TermsAggregation('by_brand', 'products.brand_id'));
    }
}

use Bonu\ElasticsearchBuilder\Query\TermQuery;
use Bonu\ElasticsearchBuilder\Aggregation\TermsAggregation;
use Bonu\ElasticsearchBuilder\Aggregation\ContainerAggregation;

// Container with a filter
new ContainerAggregation('my_container')
    ->query(new TermQuery('status', 'active'))
    ->aggregation(new TermsAggregation('by_brand', 'brand.keyword'));

// Global container
new ContainerAggregation('global_container')
    ->asGlobal()
    ->aggregation(new TermsAggregation('all_brands', 'brand.keyword'));

use Bonu\ElasticsearchBuilder\Aggregation\TermsAggregation;
use Bonu\ElasticsearchBuilder\Query\TermQuery;

// Top 10 brands, filtered to active products
new TermsAggregation('by_brand', 'brand.keyword')
    ->size(10)
    ->query(new TermQuery('status', 'active'));

// Make the aggregation global (ignores the top-level query)
new TermsAggregation('all_categories', 'category.keyword')
    ->asGlobal();

use Bonu\ElasticsearchBuilder\Aggregation\StatsAggregation;
use Bonu\ElasticsearchBuilder\Query\TermQuery;

// Basic stats for the price field, filtered by currency
new StatsAggregation('price_stats', 'price')
    ->query(new TermQuery('currency', 'USD'));

// Make the aggregation global (ignores the top-level query)
new StatsAggregation('global_price_stats', 'price')
    ->asGlobal();

use Bonu\ElasticsearchBuilder\Aggregation\NestedAggregation;

new NestedAggregation('categories', 'products')
    ->aggregation(new StatsAggregation('product_price', 'products.price'))

use Bonu\ElasticsearchBuilder\Aggregation\MultiTermsAggregation;

new MultiTermsAggregation('foo', ['product', 'category'])
    ->size(10)
    ->query(new TermQuery('status', 'active'));

use Bonu\ElasticsearchBuilder\Aggregation\HistogramAggregation;

// Prices in $10 intervals
new HistogramAggregation('price_histogram', 'price', 10);

// With custom interval and min_doc_count
new HistogramAggregation('price_histogram', 'price', 50, 1);

use Bonu\ElasticsearchBuilder\Aggregation\SumAggregation;
use Bonu\ElasticsearchBuilder\Query\TermQuery;

// Sum of all prices
new SumAggregation('total_price', 'price');

// Filtered sum
new SumAggregation('active_total', 'price')
    ->query(new TermQuery('status', 'active'));

// Global sum (ignores the top-level query)
new SumAggregation('global_total', 'price')
    ->asGlobal();

use Bonu\ElasticsearchBuilder\Aggregation\CardinalityAggregation;

// Count unique values
new CardinalityAggregation('unique_brands', 'brand.keyword');

// With precision threshold for better accuracy on high-cardinality fields
new CardinalityAggregation('unique_brands', 'brand.keyword', 1000);

// Filtered cardinality
new CardinalityAggregation('active_unique_brands', 'brand.keyword')
    ->query(new TermQuery('status', 'active'));

use Bonu\ElasticsearchBuilder\Aggregation\DateHistogramAggregation;

// Monthly buckets using calendar interval
new DateHistogramAggregation('sales_over_time', 'date', calendarInterval: 'month');

// Fixed 30-day intervals with date format
new DateHistogramAggregation('monthly_sales', 'date', fixedInterval: '30d', format: 'yyyy-MM-dd');

// With all options: calendar interval, min_doc_count, format, time zone, offset
new DateHistogramAggregation(
    'hourly_activity',
    'timestamp',
    calendarInterval: 'hour',
    minDocCount: 1,
    format: 'yyyy-MM-dd HH:mm',
    timeZone: 'Europe/Prague',
    offset: '+6h',
);


use Bonu\ElasticsearchBuilder\Sort\FieldSort;
use Bonu\ElasticsearchBuilder\Sort\SortDirectionEnum;

new FieldSort('my_field', SortDirectionEnum::ASC)


use Bonu\ElasticsearchBuilder\Sort\ScoreSort;
use Bonu\ElasticsearchBuilder\Sort\SortDirectionEnum;

new ScoreSort(SortDirectionEnum::DESC)
bash
composer