百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
E

elasticsearch-query-builder

> 数据库
开源

使用流畅的 PHP API 构建和执行 Elasticsearch 搜索查询

182 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

使用流畅的 PHP API 构建和执行 Elasticsearch 搜索查询

Build and execute ElasticSearch queries using a fluent PHP API


This package is a lightweight query builder for ElasticSearch. It was specifically built for our elasticsearch-search-string-parser so it covers most use-cases but might lack certain features. We're always open for PRs if you need anything specific!

php
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();

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

bash
composer require spatie/elasticsearch-query-builder

Note If you're using elasticsearch/elasticsearch v7 you need to use v1 of this package.

Basic usage

The only class you really need to interact with is the Spatie\ElasticsearchQueryBuilder\Builder class. It requires an \Elastic\Elasticsearch\Client passed in the constructor. Take a look at the ElasticSearch SDK docs to learn more about connecting to your ElasticSearch cluster.

The Builder class contains some methods to add queries, aggregations, sorts, fields and some extras for pagination. You can read more about these methods below. Once you've fully built-up the query you can use $builder->search() to execute the query or $builder->getPayload() to get the raw payload for ElasticSearch.

php
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

Multi-Search Queries

Multi-Search queries are also available using the MultiBuilder class.

Adding queries

The $builder->addQuery() method can be used to add any of the available Query types to the builder. The available query types can be found below or in the src/Queries directory of this repo. Every Query has a static create() method to pass its most important parameters.

The following query types are available:

ExistsQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\ExistsQuery::create('terms_and_conditions');

FuzzyQuery

https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-fuzzy-query

php
\Spatie\ElasticsearchQueryBuilder\Queries\FuzzyQuery::create('name', 'john', fuzziness: 2, boost: 1.5, rewrite: 'constant_score_blended');

GeoshapeQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-geo-shape-query.html;

php
\Spatie\ElasticsearchQueryBuilder\Queries\GeoshapeQuery::create(
  'location',
  \Spatie\ElasticsearchQueryBuilder\Queries\GeoshapeQuery::TYPE_POLYGON,
  [[1.0, 2.0]],
  \Spatie\ElasticsearchQueryBuilder\Queries\GeoShapeQuery::RELATION_INTERSECTS,
);

IdsQuery

https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-ids-query

php
\Spatie\ElasticsearchQueryBuilder\Queries\IdsQuery::create(['user123', 'post456']);

MatchAllQuery

https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-match-all-query

MatchNoneQuery

https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-match-all-query#query-dsl-match-none-query

php
\Spatie\ElasticsearchQueryBuilder\Queries\MatchAllQuery::create(boost: 1.2);

MatchQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\MatchQuery::create('name', 'john doe', fuzziness: 2, boost: 5.0);

MatchPhraseQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\MatchPhraseQuery::create('name', 'john doe', slop: 2,zeroTermsQuery: "none",analyzer: "my_analyzer");

MultiMatchQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\MultiMatchQuery::create('john', ['email', 'email'], fuzziness: 'auto');
php
\Spatie\ElasticsearchQueryBuilder\Queries\MatchNoneQuery::create();

NestedQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\NestedQuery::create(
    'user',
    new \Spatie\ElasticsearchQueryBuilder\Queries\MatchQuery('name', 'john')
);
NestedQuery InnerHits

https://www.elastic.co/guide/en/elasticsearch/reference/current/inner-hits.html

…

RangeQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\RangeQuery::create('age')
    ->gte(18)
    ->lte(1337);

RegexpQuery

https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-regexp-query

php
\Spatie\ElasticsearchQueryBuilder\Queries\RegexpQuery::create('name', 'joh.*', flags: 'ALL', maxDeterminizedStates: 10000, rewrite: 'constant_score');

TermQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\TermQuery::create('user.id', 'flx');

TermsQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\TermsQuery::create('user.id', ['flx', 'fly'], boost: 5.0);

WildcardQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\WildcardQuery::create('user.id', '*doe');

PercolateQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-percolate-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\PercolateQuery::create('query', ['title' => 'foo', 'body' => 'bar']);

BoolQuery

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

php
\Spatie\ElasticsearchQueryBuilder\Queries\BoolQuery::create()
    ->add($matchQuery, 'must_not')
    ->add($existsQuery, 'must_not');

collapse

The collapse feature allows grouping search results by a specific field while retrieving top documents from each group using inner_hits. This is useful for avoiding duplicate entities in search results while still accessing grouped data.

https://www.elastic.co/guide/en/elasticsearch/reference/current/collapse-search-results.html

…

Chaining multiple queries

Multiple addQuery() calls can be chained on one Builder. Under the hood they'll be added to a BoolQuery with occurrence type must. By passing a second argument to the addQuery() method you can select a different occurrence type:

php
$builder
    ->addQuery(
        MatchQuery::create('name', 'billie'),
        'must_not' // available types: must, must_not, should, filter
    )
    ->addQuery(
        MatchQuery::create('team', 'eillish')
    );

More information on the boolean query and its occurrence types can be found in the ElasticSearch docs.

Adding aggregations

The $builder->addAggregation() method can be used to add any of the available Aggregations to the builder. The available aggregation types can be found below or in the src/Aggregations directory of this repo. Every Aggregation has a static create() method to pass its most important parameters and sometimes some extra methods.

php
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'];

The following query types are available:

CardinalityAggregation

php
\Spatie\ElasticsearchQueryBuilder\Aggregations\CardinalityAggregation::create('team_agg', 'team_name');

AvgAggregation

https://www.elastic.co/docs/reference/aggregations/search-aggregations-metrics-avg-aggregation

php
\Spatie\ElasticsearchQueryBuilder\Aggregations\AvgAggregation::create('avg_price', 'price');

FilterAggregation

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html

php
\Spatie\ElasticsearchQuery

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPelasticsearchphp

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库