PHPackages                             spatie/elasticsearch-search-string-parser - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. spatie/elasticsearch-search-string-parser

ActiveLibrary[Search &amp; Filtering](/categories/search)

spatie/elasticsearch-search-string-parser
=========================================

Build Elasticsearch queries based of a query string

2.0.0(1mo ago)5023.7k4MITPHPPHP ^8.3CI passing

Since Jun 24Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/spatie/elasticsearch-search-string-parser)[ Packagist](https://packagist.org/packages/spatie/elasticsearch-search-string-parser)[ Docs](https://github.com/spatie/elasticsearch-search-string-parser)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-elasticsearch-search-string-parser/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (21)Versions (12)Used By (0)

Parse custom search strings and execute them using ElasticSearch
================================================================

[](#parse-custom-search-strings-and-execute-them-using-elasticsearch)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d78c5740931d1c6ffbca25a2e50f9ea1dd17d04da955959379bf1a60be044395/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f656c61737469637365617263682d7365617263682d737472696e672d7061727365722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/elasticsearch-search-string-parser)[![GitHub Tests Action Status](https://github.com/spatie/elasticsearch-search-string-parser/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/elasticsearch-search-string-parser/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://github.com/spatie/elasticsearch-search-string-parser/actions/workflows/fix-php-code-style-issues.yml/badge.svg)](https://github.com/spatie/elasticsearch-search-string-parser/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/dcdb1898cc3a45d09631461ff27c1355df9fe025881b03bdb3f7ec961b523059/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f656c61737469637365617263682d7365617263682d737472696e672d7061727365722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/elasticsearch-search-string-parser)

This package allows you to convert a search string like `foo bar status:active @john.doe` to its corresponding ElasticSearch request. Any custom *directives* like `status:active` and `@john.doe` can be added using regex and the [`spatie/elasticsearch-query-builder`](https://github.com/spatie/elasticsearch-query-builder). There's also basic support for grouping directives (e.g. `group_by:project`) and providing auto-completion suggestions for certain directives.

```
use Elastic\Elasticsearch\ClientBuilder;
use Spatie\ElasticsearchStringParser\SearchQuery;

$subjects = SearchQuery::forClient(ClientBuilder::create())
    ->baseDirective(new SubjectBaseDirective())
    ->patternDirectives(
        new CompanyDirective(),
        new UserDirective(),
    )
    ->search('deadly neurotoxin company:aperture @glados');
```

In the example above, an ElasticSearch request is executed with the appropriate parameters set to search for results with the given company (`aperture`), user (`glados`) and subject string (`deadly neurotoxin`). The returned value is a `\Spatie\ElasticsearchStringParser\SearchResults` object that contains search results and suggestions for the applied directives.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/40a288e1423c9b3337e3be6d16813bf8a083566aa58fd9c8bece4be9519d93e6/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f656c61737469637365617263682d7365617263682d737472696e672d7061727365722e6a70673f743d31)](https://spatie.be/github-ad-click/elasticsearch-search-string-parser)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/elasticsearch-search-string-parser
```

This package requires Elasticsearch 8 and the matching `elasticsearch/elasticsearch` 8.x PHP client. If you're still on Elasticsearch 7, use the `1.x` release of this package.

How it works: directives
------------------------

[](#how-it-works-directives)

When creating a search string parser, you decide how each part of the search string is parsed by defining *directives*. When a directive is found in the search string, it is applied to the underlying ElasticSearch. Directives can be used to add basic match queries but also to add sorts, aggregations, facets, etc...

Let's dive into the inner workings of the package by dissecting an example search string and its parser:

```
$searchString = 'cheap neurotoxin company:aperture deadly @glados';

SearchQuery::forClient(ClientBuilder::create())
    ->baseDirective(new SubjectBaseDirective())
    ->patternDirectives(
        new CompanyDirective(),
        new UserDirective(),
    )->search($searchString);
```

A search string parser can have multiple `PatternDirective`s and at most one `BaseDirective`. In the example search string there are two pattern directives: `company:aperture` and `@glados`. These will be parsed by the `CompanyDirective` and `UserDirective`. The remaining string (`cheap nearotoxin deadly`) will be processed by the base directive.

To do this, we'll loop over all configured pattern directives. Each patter directive has a regular expression it looks for. If one of the directives finds a match in the search string, it will be applied and the match will be removed from the search string. The process is then repeated for the next match or the next pattern directive.

Back to our example: the `CompanyDirective` is configured to match `company:(.*)`. In the example string, this regex pattern will match `company:aperture`. This means the `CompanyDirective` will be applied and a query for `company_name="aperture"` will be added to the ElasticSearch builder. Finally, the directive is removed from the search string, leaving us with the following string:

```
cheap neurotoxin deadly @glados

```

As there are no other matches for the `CompanyDirective`, we'll look for the `UserDirective` next. The user directive will search for `@(.*)` and thus match `@glados`. The `UserDirective` will now apply its queries to the ElasticSearch builder and remove the matches string. We're left with:

```
cheap neurotoxin deadly

```

There are no pattern directives left to apply. The entire remaining string is then passed to the `SubjectBaseDirective`. This base directive then decides what to do with the remaining search string, for example, using it for a fuzzy search on the subject field.

Usage
-----

[](#usage)

```
$elasticsearch-search-string-parser = new Spatie\ElasticsearchStringParser();
echo $elasticsearch-search-string-parser->echoPhrase('Hello, Spatie!');
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Alex Vanderbist](https://github.com/AlexVanderbist)
- [Ruben Van Assche](https://github.com/rubenvanassche)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

59

—

FairBetter than 98% of packages

Maintenance94

Actively maintained with recent releases

Popularity38

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 60.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~200 days

Recently: every ~395 days

Total

10

Last Release

32d ago

Major Versions

0.0.2 → 1.0.02021-07-07

1.3.0 → 2.0.02026-06-02

PHP version history (3 changes)0.0.1PHP ^8.0

1.2.3PHP ^8.2

2.0.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (81 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (20 commits)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (16 commits)")[![juandelperal](https://avatars.githubusercontent.com/u/2414972?v=4)](https://github.com/juandelperal "juandelperal (8 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (7 commits)")[![madurapa](https://avatars.githubusercontent.com/u/4289578?v=4)](https://github.com/madurapa "madurapa (1 commits)")

---

Tags

elasticsearchsearchspatie

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/spatie-elasticsearch-search-string-parser/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-elasticsearch-search-string-parser/health.svg)](https://phpackages.com/packages/spatie-elasticsearch-search-string-parser)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k54.9M11.7k](/packages/illuminate-database)[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[illuminate/support

The Illuminate Support package.

630113.0M41.5k](/packages/illuminate-support)[mailerlite/laravel-elasticsearch

An easy way to use the official PHP ElasticSearch client in your Laravel applications.

936603.4k2](/packages/mailerlite-laravel-elasticsearch)[spatie/laravel-searchable

Pragmatically search through models and other sources

1.4k1.6M31](/packages/spatie-laravel-searchable)[unopim/unopim

UnoPim Laravel PIM

10.5k2.4k](/packages/unopim-unopim)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
