PHP code example of spatie / elasticsearch-query-builder
1. Go to this page and download the library: Download spatie/elasticsearch-query-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/ */
spatie / elasticsearch-query-builder example snippets
use Spatie\ElasticsearchQueryBuilder\Aggregations\MaxAggregation;
use Spatie\ElasticsearchQueryBuilder\Builder;
use Spatie\ElasticsearchQueryBuilder\Queries\MatchQuery;
$client = Elastic\Elasticsearch\ClientBuilder::create()->build();
$companies = (new Builder($client))
->index('companies')
->addQuery(MatchQuery::create('name', 'spatie', fuzziness: 3))
->addAggregation(MaxAggregation::create('score'))
->search();
use Spatie\ElasticsearchQueryBuilder\Queries\RangeQuery;
use Spatie\ElasticsearchQueryBuilder\Builder;
$client = Elastic\Elasticsearch\ClientBuilder::create()->build();
$builder = new Builder($client);
$builder->addQuery(RangeQuery::create('age')->gte(18));
$results = $builder->search(); // raw response from ElasticSearch
use Spatie\ElasticsearchQueryBuilder\Aggregations\TermsAggregation;
use Spatie\ElasticsearchQueryBuilder\Builder;
$results = (new Builder(Elastic\Elasticsearch\ClientBuilder::create()->build()))
->addAggregation(TermsAggregation::create('genres', 'genre'))
->search();
$genres = $results['aggregations']['genres']['buckets'];
use Spatie\ElasticsearchQueryBuilder\Sorts\NestedSort;
$builder
->addSort(
NestedSort::create('books', 'books.rating', NestedSort::ASC)
);
use Spatie\ElasticsearchQueryBuilder\Sorts\NestedSort;
use Spatie\ElasticsearchQueryBuilder\Queries\BoolQuery;
use Spatie\ElasticsearchQueryBuilder\Queries\TermQuery;
$builder
->addSort(
NestedSort::create(
'books',
'books.rating',
NestedSort::ASC
)->filter(BoolQuery::create()->add(TermQuery::create('books.category', 'comedy'))
);