hosmelq/search-syntax-parser
Composer 安装命令:
composer require hosmelq/search-syntax-parser
包简介
Parse search queries into structured data with field searches, boolean logic, ranges, lists, and adapters.
README 文档
README
Parse search queries into structured data with support for field searches, boolean logic, range comparisons, and multiple output formats.
Introduction
Use a concise, expressive query language to build structured queries. It supports field-specific searches, boolean operators, ranges, existence checks, and multi-value lists, and outputs to multiple formats via adapters.
use HosmelQ\SearchSyntaxParser\SearchParser; $result = SearchParser::query('age:>25 AND name:john')->build();
It returns a normalized PHP array describing the query.
Requirements
- PHP 8.2+
Installation & setup
Install the package via composer:
composer require hosmelq/search-syntax-parser
Basic usage
Getting started
Create a parser from a query string and build it using the default array adapter:
use HosmelQ\SearchSyntaxParser\SearchParser; $result = SearchParser::query('title:Coffee AND price:<10')->build();
Default adapter (array)
When no adapter is provided, build() uses the array adapter and returns a structured PHP array.
use HosmelQ\SearchSyntaxParser\SearchParser; $result = SearchParser::query('title:Coffee')->build(); // Array output [ 'field' => 'title', 'operator' => '=', 'type' => 'comparison', 'value' => 'Coffee', ]
Query types
Connectives (AND/OR)
Combine multiple terms with logical operators. When no connective is specified, AND is implied.
SearchParser::query('title:Coffee AND price:<10')->build(); // Explicit AND SearchParser::query('title:Coffee OR title:Tea')->build(); // OR operator SearchParser::query('title:Coffee price:<10')->build(); // Implicit AND
Comparators
Use field comparison operators to define the relationship between a field and its value:
SearchParser::query('price:>10')->build(); // Greater than SearchParser::query('price:>=10')->build(); // Greater than or equal SearchParser::query('price:<50')->build(); // Less than SearchParser::query('price:<=50')->build(); // Less than or equal SearchParser::query('status:!=sold')->build(); // Not equal
Comma-separated values
Use multi-value field searches as syntactic sugar for OR operations:
// Single field, multiple values SearchParser::query('status:ACTIVE,DRAFT,PENDING')->build(); // Equivalent to: status:ACTIVE OR status:DRAFT OR status:PENDING // Works with any operator SearchParser::query('status:!=SOLD,EXPIRED')->build(); // Equivalent to: status:!=SOLD OR status:!=EXPIRED // Can be combined with boolean logic SearchParser::query('status:ACTIVE,DRAFT AND price:>100')->build(); // Supports quoted values SearchParser::query('category:"Home & Garden","Sports & Outdoors"')->build();
Exists queries
Search for documents with non-null values in specified fields using wildcard syntax:
SearchParser::query('category:*')->build(); // Field has any value SearchParser::query('NOT discount:*')->build(); // Field doesn't exist
Range queries
Search within value ranges using boundary operators:
SearchParser::query('price:[10 TO 50]')->build(); // Numeric range SearchParser::query('date:[2025-01-01 TO 2025-12-31]')->build(); // Date range
Terms
Search using basic terms that match default searchable fields:
SearchParser::query('coffee')->build();
Modifiers (NOT)
Negate terms or subqueries using - or NOT:
SearchParser::query('NOT title:Coffee')->build(); // NOT modifier SearchParser::query('-title:Coffee')->build(); // - modifier (equivalent)
Field validation
Restrict which fields can be used and validate their values using AllowedField helpers:
use HosmelQ\SearchSyntaxParser\SearchParser; use HosmelQ\SearchSyntaxParser\Validation\AllowedField; $parser = SearchParser::query('age:25 AND status:ACTIVE')->allowedFields([ AllowedField::integer('age')->min(0), AllowedField::in('status', ['ACTIVE', 'DRAFT', 'PENDING']), AllowedField::string('name')->size(2), ]); $result = $parser->build(); // throws if any value is invalid or a field is not allowed
You can also map external field names to internal ones:
$parser = SearchParser::query('age:10')->allowedFields([ AllowedField::integer('age', 'user_age'), ]); $result = $parser->build(); // The array adapter will output the internal name "user_age" for the field
Array item validation (each and at)
For array fields, use each() to validate every item and at(index) to validate specific positions.
Per‑item rules with each():
use HosmelQ\SearchSyntaxParser\SearchParser; use HosmelQ\SearchSyntaxParser\Validation\AllowedField; $parser = SearchParser::query('tags:alpha,beta') ->allowedFields([ AllowedField::array('tags') ->max(5) ->each(fn ($rules) => $rules->string()->max(10)), ]); $result = $parser->build();
Index‑specific rules with at() (tuple‑like arrays):
use HosmelQ\SearchSyntaxParser\SearchParser; use HosmelQ\SearchSyntaxParser\Validation\AllowedField; $parser = SearchParser::query('location:37.7749,-122.4194') ->allowedFields([ AllowedField::array('location') ->size(2) ->at(0, fn ($rules) => $rules->numeric()->between(-90, 90)) ->at(1, fn ($rules) => $rules->numeric()->between(-180, 180)), ]); $result = $parser->build();
Custom adapters
Create custom output formats by implementing the adapter interface:
use HosmelQ\SearchSyntaxParser\Adapter\QueryAdapterInterface; use HosmelQ\SearchSyntaxParser\AST\Node\NodeInterface; use HosmelQ\SearchSyntaxParser\SearchParser; class EloquentAdapter implements QueryAdapterInterface { public function build(NodeInterface $ast): mixed { // Convert the AST to your preferred format return ['where' => ['name', 'john']]; } } $parser = SearchParser::query('name:john'); $parser->extend('eloquent', fn () => new EloquentAdapter()); $result = $parser->build('eloquent');
Error handling
Handle parsing errors with ParseException:
use HosmelQ\SearchSyntaxParser\Exception\ParseException; use HosmelQ\SearchSyntaxParser\SearchParser; try { SearchParser::query('invalid:syntax:here')->build(); } catch (ParseException $e) { echo "Parse error: " . $e->getMessage(); }
Testing
composer test
Changelog
Please see CHANGELOG.md for more information on what has changed recently.
Credits
License
The MIT License (MIT). Please see License File for more information.
hosmelq/search-syntax-parser 适用场景与选型建议
hosmelq/search-syntax-parser 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 785 次下载、GitHub Stars 达 7, 最近一次更新时间为 2025 年 08 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「DSL」 「tokenizer」 「ast」 「lexer」 「query-language」 「query-parser」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hosmelq/search-syntax-parser 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hosmelq/search-syntax-parser 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hosmelq/search-syntax-parser 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Library emulating the PHP internal reflection using just the tokenized source code.
Editable JSON AST with visitor traversal and formatting-preserving printing.
Feature complete, object oriented, composable, extendable Elasticsearch query DSL builder for PHP.
Parse Handlebars templates to a spec-compliant AST with PHP.
A program for performing lexical analysis, written in PHP
A simple library for make Lexer and Parsers to build a language
统计信息
- 总下载量: 785
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 7
- 点击次数: 21
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-08-12