├── src ├── Directives │ ├── GroupDirective.php │ ├── BaseDirective.php │ ├── PatternDirective.php │ ├── ColumnGroupDirective.php │ ├── DateKeyValuePatternDirective.php │ ├── DateRangeKeyValuePatternDirective.php │ ├── FuzzyValueBaseDirective.php │ └── FuzzyKeyValuePatternDirective.php ├── SearchHit.php ├── SearchResults.php ├── Suggestion.php ├── Support │ └── Regex.php ├── Concerns │ └── ForwardsCalls.php ├── SearchQuery.php └── SearchExecutor.php ├── CHANGELOG.md ├── LICENSE.md ├── .php_cs.dist.php ├── composer.json ├── .php-cs-fixer.cache └── README.md /src/Directives/GroupDirective.php: -------------------------------------------------------------------------------- 1 | useSuggestions = true; 31 | 32 | return $this; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Directives/PatternDirective.php: -------------------------------------------------------------------------------- 1 | useSuggestions = true; 28 | 29 | return $this; 30 | } 31 | 32 | public function canApply(string $pattern, array $values = []): bool 33 | { 34 | return true; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `elasticsearch-search-string-parser` will be documented in this file. 4 | 5 | ## 1.2.3 - 2025-06-27 6 | 7 | ### What's Changed 8 | 9 | * Laravel 11 and 12 compatibility by @juandelperal in https://github.com/spatie/elasticsearch-search-string-parser/pull/7 10 | 11 | ### New Contributors 12 | 13 | * @juandelperal made their first contribution in https://github.com/spatie/elasticsearch-search-string-parser/pull/7 14 | 15 | **Full Changelog**: https://github.com/spatie/elasticsearch-search-string-parser/compare/1.2.2...1.2.3 16 | 17 | ## 1.2.2 - 2023-02-20 18 | 19 | - Add support for Laravel 10 20 | 21 | ## 1.2.1 - 2022-02-02 22 | 23 | - Add support for Laravel 9 24 | 25 | ## 1.2.0 - 2021-08-22 26 | 27 | - allow meta data in directive suggestions 28 | 29 | ## 1.1.0 - 2021-07-29 30 | 31 | - add support for `beforeApply` 32 | 33 | ## 1.0.1 - 2021-07-07 34 | 35 | - fix spatie/elasticsearch-query-builder dependency constraint 36 | 37 | ## 1.0.0 - 2021-07-07 38 | 39 | - initial release 40 | -------------------------------------------------------------------------------- /src/Support/Regex.php: -------------------------------------------------------------------------------- 1 | 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Concerns/ForwardsCalls.php: -------------------------------------------------------------------------------- 1 | {$method}(...$parameters); 14 | } catch (Error | BadMethodCallException $e) { 15 | $pattern = '~^Call to undefined method (?P[^:]+)::(?P[^\(]+)\(\)$~'; 16 | 17 | if (! preg_match($pattern, $e->getMessage(), $matches)) { 18 | throw $e; 19 | } 20 | 21 | if ($matches['class'] != get_class($object) || 22 | $matches['method'] != $method) { 23 | throw $e; 24 | } 25 | 26 | static::throwBadMethodCallException($method); 27 | } 28 | } 29 | 30 | protected static function throwBadMethodCallException(string $method): void 31 | { 32 | throw new BadMethodCallException(sprintf( 33 | 'Call to undefined method %s::%s()', 34 | static::class, 35 | $method 36 | )); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /.php_cs.dist.php: -------------------------------------------------------------------------------- 1 | in([ 5 | __DIR__ . '/src', 6 | __DIR__ . '/tests', 7 | ]) 8 | ->name('*.php') 9 | ->notName('*.blade.php') 10 | ->ignoreDotFiles(true) 11 | ->ignoreVCS(true); 12 | 13 | return (new PhpCsFixer\Config()) 14 | ->setRules([ 15 | '@PSR2' => true, 16 | 'array_syntax' => ['syntax' => 'short'], 17 | 'ordered_imports' => ['sort_algorithm' => 'alpha'], 18 | 'no_unused_imports' => true, 19 | 'not_operator_with_successor_space' => true, 20 | 'trailing_comma_in_multiline' => true, 21 | 'phpdoc_scalar' => true, 22 | 'unary_operator_spaces' => true, 23 | 'binary_operator_spaces' => true, 24 | 'blank_line_before_statement' => [ 25 | 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], 26 | ], 27 | 'phpdoc_single_line_var_spacing' => true, 28 | 'phpdoc_var_without_name' => true, 29 | 'class_attributes_separation' => [ 30 | 'elements' => [ 31 | 'method' => 'one', 32 | ], 33 | ], 34 | 'method_argument_space' => [ 35 | 'on_multiline' => 'ensure_fully_multiline', 36 | 'keep_multiple_spaces_after_comma' => true, 37 | ], 38 | 'single_trait_insert_per_statement' => true, 39 | ]) 40 | ->setFinder($finder); 41 | -------------------------------------------------------------------------------- /src/Directives/ColumnGroupDirective.php: -------------------------------------------------------------------------------- 1 | groupableFields); 19 | } 20 | 21 | public function apply(Builder $builder, string $pattern, array $values, int $patternOffsetStart, int $patternOffsetEnd): void 22 | { 23 | $field = $values[0]; 24 | 25 | $aggregation = TermsAggregation::create('_grouping', "{$field}.keyword") 26 | ->aggregation(TopHitsAggregation::create('top_hit', 1)); 27 | 28 | $builder->addAggregation($aggregation); 29 | } 30 | 31 | public function pattern(): string 32 | { 33 | return '/group:(?.*?)(?:$|\s)/i'; 34 | } 35 | 36 | public function transformToHits(array $results): array 37 | { 38 | return array_map( 39 | fn (array $bucket) => new SearchHit( 40 | $bucket['top_hit']['hits']['hits'][0]['_source'], 41 | $bucket 42 | ), 43 | $results['aggregations']['_grouping']['buckets'] 44 | ); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Directives/DateKeyValuePatternDirective.php: -------------------------------------------------------------------------------- 1 | parseDate($values['value']); 23 | 24 | if (! $value) { 25 | return; 26 | } 27 | 28 | $day = $value->format('Y-m-d'); 29 | 30 | $builder->addQuery( 31 | RangeQuery::create($this->field) 32 | ->gte("{$day}||/d") 33 | ->lt("{$day}||+1d/d"), 34 | 'filter' 35 | ); 36 | } 37 | 38 | public function pattern(): string 39 | { 40 | return "/{$this->key}:(?\d{4}\-\d{2}-\d{2}|today)(?:$|\s)/i"; 41 | } 42 | 43 | protected function parseDate(string $date, string $format = 'Y-m-d'): ?DateTimeImmutable 44 | { 45 | if ($date === 'today') { 46 | return new DateTimeImmutable(); 47 | } 48 | 49 | $dateTime = DateTimeImmutable::createFromFormat($format, $date); 50 | 51 | if (! $dateTime || $dateTime->format($format) !== $date) { 52 | return null; 53 | } 54 | 55 | return $dateTime; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "spatie/elasticsearch-search-string-parser", 3 | "description": "Build Elasticsearch queries based of a query string", 4 | "keywords": [ 5 | "spatie" 6 | ], 7 | "homepage": "https://github.com/spatie/elasticsearch-search-string-parser", 8 | "license": "MIT", 9 | "authors": [ 10 | { 11 | "name": "Alex Vanderbist", 12 | "email": "alex.vanderbist@gmail.com", 13 | "role": "Developer" 14 | }, 15 | { 16 | "name": "Ruben Van Assche", 17 | "email": "ruben@spatie.be", 18 | "role": "Developer" 19 | } 20 | ], 21 | "require": { 22 | "php": "^8.2", 23 | "elasticsearch/elasticsearch": "^7.12", 24 | "illuminate/collections": "^11.0|^12.0", 25 | "spatie/elasticsearch-query-builder": "^1.0" 26 | }, 27 | "require-dev": { 28 | "brianium/paratest": "^6.2|^7.0|^7.8", 29 | "larapack/dd": "^1.1", 30 | "phpunit/phpunit": "^10.0|^11.0", 31 | "spatie/phpunit-snapshot-assertions": "^5.0" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "Spatie\\ElasticsearchStringParser\\": "src" 36 | } 37 | }, 38 | "autoload-dev": { 39 | "psr-4": { 40 | "Spatie\\ElasticsearchStringParser\\Tests\\": "tests" 41 | } 42 | }, 43 | "scripts": { 44 | "psalm": "vendor/bin/psalm", 45 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 46 | }, 47 | "config": { 48 | "sort-packages": true, 49 | "allow-plugins": { 50 | "php-http/discovery": true 51 | } 52 | }, 53 | "minimum-stability": "dev", 54 | "prefer-stable": true 55 | } 56 | -------------------------------------------------------------------------------- /src/Directives/DateRangeKeyValuePatternDirective.php: -------------------------------------------------------------------------------- 1 | validateDateTime($values['value'])) { 24 | return; 25 | } 26 | 27 | $dateTime = new DateTimeImmutable($values['value']); 28 | $dateTimeString = $dateTime->format(DateTimeImmutable::ATOM); 29 | 30 | $rangeQuery = RangeQuery::create($this->field); 31 | 32 | match ($values['range'] ?? false) { 33 | '>' => $rangeQuery->gt($dateTimeString), 34 | '>=' => $rangeQuery->gte($dateTimeString), 35 | '<' => $rangeQuery->lt($dateTimeString), 36 | '<=' => $rangeQuery->lte($dateTimeString), 37 | default => null, 38 | }; 39 | 40 | $builder->addQuery($rangeQuery, 'filter'); 41 | } 42 | 43 | public function pattern(): string 44 | { 45 | return "/{$this->key}:(?[<>]=?)(?.*?)(?:$|\s)/i"; 46 | } 47 | 48 | protected function validateDateTime(string $value): bool 49 | { 50 | try { 51 | new DateTimeImmutable($value); 52 | 53 | return true; 54 | } catch (Exception) { 55 | return false; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Directives/FuzzyValueBaseDirective.php: -------------------------------------------------------------------------------- 1 | fuzziness = $fuzziness; 31 | 32 | return $this; 33 | } 34 | 35 | public function apply(Builder $builder, string $value): void 36 | { 37 | if (empty($value)) { 38 | return; 39 | } 40 | 41 | $builder->addQuery(MultiMatchQuery::create($value, $this->fields, $this->fuzziness)); 42 | 43 | if ($this->useSuggestions === false) { 44 | return; 45 | } 46 | 47 | foreach ($this->fields as $field) { 48 | $builder->addAggregation(TermsAggregation::create("_{$field}_suggestions", "{$field}.keyword")); 49 | } 50 | } 51 | 52 | public function transformToSuggestions(array $results): array 53 | { 54 | if ($this->useSuggestions === false) { 55 | return []; 56 | } 57 | 58 | $validAggregations = array_map( 59 | fn (string $field) => "_{$field}_suggestions", 60 | $this->fields 61 | ); 62 | 63 | return collect($results['aggregations'] ?? []) 64 | ->filter(fn (array $aggregation, string $name) => in_array($name, $validAggregations)) 65 | ->flatMap(fn (array $aggregation) => array_map( 66 | fn (array $bucket) => Suggestion::fromBucket($bucket), 67 | $aggregation['buckets'] 68 | )) 69 | ->toArray(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Directives/FuzzyKeyValuePatternDirective.php: -------------------------------------------------------------------------------- 1 | addQuery(MultiMatchQuery::create($values['value'], $this->fields, $this->fuzziness)); 32 | 33 | if ($this->useSuggestions === false) { 34 | return; 35 | } 36 | 37 | foreach ($this->fields as $field) { 38 | $builder->addAggregation(TermsAggregation::create("_{$field}_suggestions", "{$field}.keyword")); 39 | } 40 | } 41 | 42 | public function pattern(): string 43 | { 44 | return "/{$this->key}:(?.*?)(?:$|\s)/i"; 45 | } 46 | 47 | public function transformToSuggestions(array $results): array 48 | { 49 | if ($this->useSuggestions === false) { 50 | return []; 51 | } 52 | 53 | $validAggregations = array_map( 54 | fn (string $field) => "_{$field}_suggestions", 55 | $this->fields 56 | ); 57 | 58 | return collect($results['aggregations'] ?? []) 59 | ->filter(fn (array $aggregation, string $name) => in_array($name, $validAggregations)) 60 | ->flatMap(fn (array $aggregation) => array_map( 61 | fn (array $bucket) => Suggestion::fromBucket($bucket), 62 | $aggregation['buckets'] 63 | )) 64 | ->toArray(); 65 | } 66 | 67 | public function setFuzziness(string | int | null $fuzziness): self 68 | { 69 | $this->fuzziness = $fuzziness; 70 | 71 | return $this; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/SearchQuery.php: -------------------------------------------------------------------------------- 1 | builder = $builder; 33 | } 34 | 35 | public static function forClient( 36 | Client $client 37 | ): static { 38 | return new static(new Builder($client)); 39 | } 40 | 41 | /** 42 | * This directive will be applied to the remainder of the search query 43 | * after all other directive have been applied and removed from the 44 | * search string. 45 | * 46 | * @param \Spatie\ElasticsearchStringParser\Directives\BaseDirective $filter 47 | * 48 | * @return $this 49 | */ 50 | public function baseDirective(BaseDirective $filter): static 51 | { 52 | $this->baseDirective = $filter; 53 | 54 | return $this; 55 | } 56 | 57 | public function patternDirectives(PatternDirective ...$patternDirectives): static 58 | { 59 | $this->patternDirectives = $patternDirectives; 60 | 61 | return $this; 62 | } 63 | 64 | public function beforeApplying(Closure $closure): static 65 | { 66 | $this->beforeApplying = $closure; 67 | 68 | return $this; 69 | } 70 | 71 | public function search(string $query): SearchResults 72 | { 73 | $searchExecutor = new SearchExecutor( 74 | clone $this->builder, 75 | $this->patternDirectives, 76 | $this->baseDirective, 77 | $this->beforeApplying, 78 | ); 79 | 80 | return $searchExecutor($query); 81 | } 82 | 83 | public function getBuilder(): Builder 84 | { 85 | return $this->builder; 86 | } 87 | 88 | public function __call(string $method, array $arguments) 89 | { 90 | $this->forwardCallTo($this->builder, $method, $arguments); 91 | 92 | return $this; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /.php-cs-fixer.cache: -------------------------------------------------------------------------------- 1 | {"php":"8.4.12","version":"3.87.1","indent":" ","lineEnding":"\n","rules":{"blank_line_after_namespace":true,"braces_position":true,"class_definition":true,"constant_case":true,"control_structure_braces":true,"control_structure_continuation_position":true,"elseif":true,"function_declaration":true,"indentation_type":true,"line_ending":true,"lowercase_keywords":true,"method_argument_space":{"on_multiline":"ensure_fully_multiline","keep_multiple_spaces_after_comma":true},"no_break_comment":true,"no_closing_tag":true,"no_multiple_statements_per_line":true,"no_space_around_double_colon":true,"no_spaces_after_function_name":true,"no_trailing_whitespace":true,"no_trailing_whitespace_in_comment":true,"single_blank_line_at_eof":true,"single_class_element_per_statement":{"elements":["property"]},"single_import_per_statement":true,"single_line_after_imports":true,"single_space_around_construct":{"constructs_followed_by_a_single_space":["abstract","as","case","catch","class","do","else","elseif","final","for","foreach","function","if","interface","namespace","private","protected","public","static","switch","trait","try","use_lambda","while"],"constructs_preceded_by_a_single_space":["as","else","elseif","use_lambda"]},"spaces_inside_parentheses":true,"statement_indentation":true,"switch_case_semicolon_to_colon":true,"switch_case_space":true,"visibility_required":{"elements":["method","property"]},"encoding":true,"full_opening_tag":true,"array_syntax":{"syntax":"short"},"ordered_imports":{"sort_algorithm":"alpha"},"no_unused_imports":true,"not_operator_with_successor_space":true,"trailing_comma_in_multiline":true,"phpdoc_scalar":true,"unary_operator_spaces":true,"binary_operator_spaces":true,"blank_line_before_statement":{"statements":["break","continue","declare","return","throw","try"]},"phpdoc_single_line_var_spacing":true,"phpdoc_var_without_name":true,"class_attributes_separation":{"elements":{"method":"one"}},"single_trait_insert_per_statement":true},"hashes":{"src\/Suggestion.php":"44d7a8336fb43509b3040f03100c9c0f","src\/Concerns\/ForwardsCalls.php":"1002a4eacec0fd46aa90bcf2620117e5","src\/SearchResults.php":"7d2c620d5d92be035975e01ba7c24f9a","src\/Support\/Regex.php":"3716202672bfc4653a440351e91fa64a","src\/Directives\/ColumnGroupDirective.php":"75dbb14f18e28abce2b3f435b4de388f","src\/Directives\/FuzzyValueBaseDirective.php":"a4b6fa89c5f94db33cdd9aad7bb1973a","src\/Directives\/FuzzyKeyValuePatternDirective.php":"6e6413aa268eafad652e8a9094f31464","src\/Directives\/GroupDirective.php":"53599d598f63008c8e749a19bcaddd75","src\/Directives\/PatternDirective.php":"7b7a0f613fc1a83899968030d1424fa8","src\/Directives\/DateRangeKeyValuePatternDirective.php":"4c310cb005c094f20943a5007676b1a0","src\/Directives\/BaseDirective.php":"e06d58f93105fe45e01f72db6d947a8d","src\/Directives\/DateKeyValuePatternDirective.php":"897049ea748a3832ead9f6cd5919da3e","src\/SearchHit.php":"20827219096ab59c4ecd1196b7ee0da1","src\/SearchQuery.php":"a15ba70aa0f14fb9123c4ef27686af5d","src\/SearchExecutor.php":"631fb5885544dc26a719404fe81145a2","tests\/TestCase.php":"3fb3025997c645e163c31d04a932743c","tests\/Support\/PayloadFactory.php":"5cd628c4c7659b7b6305ff67685b864a","tests\/Fakes\/FakeElasticSearchClient.php":"c33655e42dcb2cfc7588a0e7da680d79","tests\/stubs\/FlareContextGroupDirective.php":"6be3f110557023c43de6930a95c1076f","tests\/stubs\/Data\/ErrorOccurrenceHit.php":"0898475bfa0141680a8134da844bdbe6","tests\/stubs\/Data\/ErrorOccurrenceGrouping.php":"906c85d364fa4db7e6b834f1e85be809","tests\/stubs\/Data\/ErrorOccurrence.php":"8c607a6f456a8f61c6fe16fffbc3d214","tests\/stubs\/FlareGroupDirective.php":"724b37cd66db469db9b420f3c250c015","tests\/SearchQueryTest.php":"269ebc77fd2fd09b6d46de2e576e6bd5"}} -------------------------------------------------------------------------------- /src/SearchExecutor.php: -------------------------------------------------------------------------------- 1 | applyQueryToBuilder($query); 29 | 30 | if ($this->groupDirective) { 31 | $this->builder->size(0); 32 | $this->builder->from(0); 33 | } 34 | 35 | $results = $this->builder->search(); 36 | 37 | $hits = $this->groupDirective 38 | ? $this->groupDirective->transformToHits($results) 39 | : array_map( 40 | fn (array $hit) => new SearchHit($hit['_source']), 41 | $results['hits']['hits'] 42 | ); 43 | 44 | $suggestions = collect($this->appliedDirectives) 45 | ->mapWithKeys(fn (BaseDirective | PatternDirective $directive, string $matchedPattern) => [ 46 | $matchedPattern => $directive->transformToSuggestions($results), 47 | ]) 48 | ->toArray(); 49 | 50 | return new SearchResults( 51 | $hits, 52 | $suggestions, 53 | $this->groupDirective !== null, 54 | $results 55 | ); 56 | } 57 | 58 | protected function applyQueryToBuilder(string $query): void 59 | { 60 | foreach ($this->patternDirectives as $directive) { 61 | $this->applyDirective($directive, $query); 62 | } 63 | 64 | $patterns = array_map( 65 | fn (PatternDirective $directive) => $directive->pattern(), 66 | $this->patternDirectives 67 | ); 68 | 69 | $queryWithoutDirectives = trim(preg_replace($patterns, '', $query)); 70 | 71 | if ($this->baseDirective && $this->baseDirective->canApply($queryWithoutDirectives)) { 72 | $this->baseDirective->apply($this->builder, $queryWithoutDirectives); 73 | 74 | $this->appliedDirectives[$queryWithoutDirectives] = $this->baseDirective; 75 | } 76 | } 77 | 78 | protected function applyDirective(PatternDirective $directive, string $query): void 79 | { 80 | $matchCount = Regex::mb_preg_match_all($directive->pattern(), $query, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE); 81 | 82 | if (! $matchCount) { 83 | return; 84 | } 85 | 86 | collect($matches) 87 | ->map(fn (array $match) => array_merge( 88 | array_map(fn ($matchGroup) => $matchGroup[0], $match), 89 | [ 90 | 'pattern_offset_start' => $match[0][1], 91 | 'pattern_offset_end' => $match[0][1] + mb_strlen($match[0][0]), 92 | ] 93 | )) 94 | ->filter(fn (array $match) => $directive->canApply(array_shift($match), $match)) 95 | ->each(function (array $match) use ($directive) { 96 | if ($directive instanceof GroupDirective) { 97 | if ($this->groupDirective) { 98 | return; 99 | } else { 100 | $this->groupDirective = $directive; 101 | } 102 | } 103 | $directiveForMatch = clone $directive; 104 | $fullMatch = array_shift($match); 105 | $offsetEnd = array_pop($match); 106 | $offsetStart = array_pop($match); 107 | 108 | if ($this->beforeApplying) { 109 | ($this->beforeApplying)($directiveForMatch, $fullMatch, $match, $offsetStart, $offsetEnd); 110 | } 111 | 112 | $directiveForMatch->apply($this->builder, $fullMatch, $match, $offsetStart, $offsetEnd); 113 | 114 | $this->appliedDirectives[$fullMatch] = $directiveForMatch; 115 | }); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Parse custom search strings and execute them using ElasticSearch 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/elasticsearch-search-string-parser.svg?style=flat-square)](https://packagist.org/packages/spatie/elasticsearch-search-string-parser) 4 | [![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/spatie/elasticsearch-search-string-parser/run-tests?label=tests)](https://github.com/spatie/elasticsearch-search-string-parser/actions?query=workflow%3Arun-tests+branch%3Amaster) 5 | [![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/spatie/elasticsearch-search-string-parser/Check%20&%20fix%20styling?label=code%20style)](https://github.com/spatie/elasticsearch-search-string-parser/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amaster) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/spatie/elasticsearch-search-string-parser.svg?style=flat-square)](https://packagist.org/packages/spatie/elasticsearch-search-string-parser) 7 | 8 | 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. 9 | 10 | ```php 11 | use Elasticsearch\ClientBuilder; 12 | use Spatie\ElasticsearchStringParser\SearchQuery; 13 | 14 | $subjects = SearchQuery::forClient(ClientBuilder::create()) 15 | ->baseDirective(new SubjectBaseDirective()) 16 | ->patternDirectives( 17 | new CompanyDirective(), 18 | new UserDirective(), 19 | ) 20 | ->search('deadly neurotoxin company:aperture @glados'); 21 | ``` 22 | 23 | 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. 24 | 25 | ## Support us 26 | 27 | [](https://spatie.be/github-ad-click/elasticsearch-search-string-parser) 28 | 29 | We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source) 30 | . You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). 31 | 32 | We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are 33 | using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received 34 | postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). 35 | 36 | ## Installation 37 | 38 | You can install the package via composer: 39 | 40 | ```bash 41 | composer require spatie/elasticsearch-search-string-parser 42 | ``` 43 | 44 | ## How it works: directives 45 | 46 | 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... 47 | 48 | Let's dive into the inner workings of the package by dissecting an example search string and its parser: 49 | 50 | ```php 51 | $searchString = 'cheap neurotoxin company:aperture deadly @glados'; 52 | 53 | SearchQuery::forClient(ClientBuilder::create()) 54 | ->baseDirective(new SubjectBaseDirective()) 55 | ->patternDirectives( 56 | new CompanyDirective(), 57 | new UserDirective(), 58 | )->search($searchString); 59 | ``` 60 | 61 | 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. 62 | 63 | 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. 64 | 65 | 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: 66 | 67 | ``` 68 | cheap neurotoxin deadly @glados 69 | ``` 70 | 71 | 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: 72 | 73 | ``` 74 | cheap neurotoxin deadly 75 | ``` 76 | 77 | 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. 78 | 79 | ## Usage 80 | 81 | ```php 82 | $elasticsearch-search-string-parser = new Spatie\ElasticsearchStringParser(); 83 | echo $elasticsearch-search-string-parser->echoPhrase('Hello, Spatie!'); 84 | ``` 85 | 86 | ## Testing 87 | 88 | ```bash 89 | composer test 90 | ``` 91 | 92 | ## Changelog 93 | 94 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 95 | 96 | ## Contributing 97 | 98 | Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details. 99 | 100 | ## Security Vulnerabilities 101 | 102 | Please review [our security policy](../../security/policy) on how to report security vulnerabilities. 103 | 104 | ## Credits 105 | 106 | - [Alex Vanderbist](https://github.com/AlexVanderbist) 107 | - [Ruben Van Assche](https://github.com/rubenvanassche) 108 | - [All Contributors](../../contributors) 109 | 110 | ## License 111 | 112 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 113 | --------------------------------------------------------------------------------