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

1.2.3(10mo ago)4923.5k4MITPHPPHP ^8.2CI passing

Since Jun 24Pushed 8mo 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 1mo ago

READMEChangelog (8)Dependencies (7)Versions (9)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://camo.githubusercontent.com/d02884eaf8ce5ad313673cd1a82806aa92e76e4aa51c81a57043487973fce5d0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7370617469652f656c61737469637365617263682d7365617263682d737472696e672d7061727365722f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/spatie/elasticsearch-search-string-parser/actions?query=workflow%3Arun-tests+branch%3Amaster)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/8789e0bc9bf14cdf2e85fa5fa3270b03c054f33f118b8b21ff120925dee990e8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7370617469652f656c61737469637365617263682d7365617263682d737472696e672d7061727365722f436865636b253230262532306669782532307374796c696e673f6c6162656c3d636f64652532307374796c65)](https://github.com/spatie/elasticsearch-search-string-parser/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amaster)[![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 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
```

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

48

—

FairBetter than 95% of packages

Maintenance57

Moderate activity, may be stable

Popularity37

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 64.3% 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 ~209 days

Recently: every ~362 days

Total

8

Last Release

326d ago

Major Versions

0.0.2 → 1.0.02021-07-07

PHP version history (2 changes)0.0.1PHP ^8.0

1.2.3PHP ^8.2

### 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)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (16 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (15 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (7 commits)")[![juandelperal](https://avatars.githubusercontent.com/u/2414972?v=4)](https://github.com/juandelperal "juandelperal (6 commits)")[![madurapa](https://avatars.githubusercontent.com/u/4289578?v=4)](https://github.com/madurapa "madurapa (1 commits)")

---

Tags

elasticsearchsearchspatie

###  Code Quality

TestsPHPUnit

### 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

[ruflin/elastica

Elasticsearch Client

2.3k50.4M203](/packages/ruflin-elastica)[spatie/laravel-searchable

Pragmatically search through models and other sources

1.4k1.5M23](/packages/spatie-laravel-searchable)[mailerlite/laravel-elasticsearch

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

934529.3k2](/packages/mailerlite-laravel-elasticsearch)[jeroen-g/explorer

Next-gen Elasticsearch driver for Laravel Scout.

397612.3k](/packages/jeroen-g-explorer)[spatie/elasticsearch-query-builder

Build and execute an Elasticsearch search query using a fluent PHP API

183614.7k5](/packages/spatie-elasticsearch-query-builder)[spatie/laravel-site-search

A site search engine

300129.1k](/packages/spatie-laravel-site-search)

PHPackages © 2026

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