nzo / elastic-query-bundle
Search Elasticsearch from Symfony with a small, validated JSON query language
Package info
github.com/nayzo/NzoElasticQueryBundle
Type:symfony-bundle
pkg:composer/nzo/elastic-query-bundle
Requires
- php: >=8.1
- ext-json: *
- friendsofsymfony/elastica-bundle: ^7.2
- justinrainbow/json-schema: ^6.7.2
- symfony/config: ^6.4 || ^7.4 || ^8.0
- symfony/dependency-injection: ^6.4 || ^7.4 || ^8.0
- symfony/event-dispatcher: ^6.4 || ^7.4 || ^8.0
- symfony/framework-bundle: ^6.4 || ^7.4 || ^8.0
- symfony/http-kernel: ^6.4 || ^7.4 || ^8.0
- symfony/options-resolver: ^6.4 || ^7.4 || ^8.0
- symfony/security-core: ^6.4 || ^7.4 || ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.68
- nyholm/psr7: ^1.8
- phpstan/phpstan: ^1.12 || ^2.0
- phpunit/phpunit: ^9.6
- rector/rector: ^1.2 || ^2.0
- symfony/filesystem: ^6.4 || ^7.4 || ^8.0
- symfony/http-client: ^6.4 || ^7.4 || ^8.0
- symfony/security-bundle: ^6.4 || ^7.4 || ^8.0
Suggests
- symfony/security-bundle: Provides the authorization checker for role-protected searches
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-29 14:17:16 UTC
README
This Symfony bundle turns a small JSON query language into Elasticsearch searches, so clients can filter, sort and page through results without sending raw Elasticsearch queries. You choose which fields can be searched.
It uses FOSElasticaBundle to query the index and return model objects or, with hydration disabled and scores off, arrays.
Which version do I need?
| Your application | Elasticsearch (upstream support) | Bundle version | Install |
|---|---|---|---|
| PHP 8.1 or later, Symfony 6.4, 7.4 or 8 | 8 or 9, matching the installed Elastica major | 4 | composer require nzo/elastic-query-bundle:^4.0 |
| PHP 7.2.5 or later, Symfony 4.4 or 5 | 7 | 3 | composer require nzo/elastic-query-bundle:^3.1 |
The versions of Symfony you can install also depend on your PHP version. FOSElasticaBundle 7.2 does not support Symfony 7.0 through 7.3. Follow its requirements for the Elasticsearch client and persistence driver you use.
The Elasticsearch versions in the table reflect FOSElasticaBundle and Elastica support. This bundle's test suite boots a Symfony kernel and verifies the Elasticsearch queries and response handling using a simulated HTTP transport. It does not run against live Elasticsearch clusters.
The documentation for version 3 is on the 3.x branch. Upgrading? Start with UPGRADE-4.0.md.
Installation
composer require nzo/elastic-query-bundle:^4.0
If you use Symfony Flex, check that both bundles are registered and add any missing entry. Without Flex, register both bundles yourself:
// config/bundles.php return [ // ... FOS\ElasticaBundle\FOSElasticaBundle::class => ['all' => true], Nzo\ElasticQueryBundle\NzoElasticQueryBundle::class => ['all' => true], ];
Configure an Elasticsearch index with a FOSElastica model, finder and SearchRepository. This example assumes that Doctrine ORM is already configured and that App\Entity\Product has id, title and status properties:
# config/packages/fos_elastica.yaml fos_elastica: clients: default: hosts: ['%env(ELASTICSEARCH_URL)%'] indexes: public_catalog: index_name: shop-products properties: id: { type: keyword } title: type: text fields: sort: { type: keyword } status: { type: keyword } persistence: driver: orm model: App\Entity\Product provider: ~ finder: ~ repository: Nzo\ElasticQueryBundle\Repository\SearchRepository
Set ELASTICSEARCH_URL to the URL of your cluster and populate the index:
php bin/console fos:elastica:populate --index=public_catalog
Then list the fields you want to expose. Use the FOSElastica configuration key (public_catalog), not the physical index name (shop-products). Configure at most one searchable index per model. An index with no allowed fields is not searchable through this bundle.
# config/packages/nzo_elastic_query.yaml nzo_elastic_query: allowed_fields: public_catalog: [title, status] # Exact mapped fields allowed in filters and sorts default_page_number: 1 # First page to use when no page is supplied limit_per_page: 100 # Default page size items_max_limit: 1000 # Larger requested page sizes are capped here max_result_window: 10000 # Maximum number of hits reachable by paging max_query_bytes: 16384 # Maximum size of the query in bytes as JSON show_score: false # Request scores and pass them to setScoreElastic() if available allow_leading_wildcards: false # Allow patterns that start with * or ?
When a later configuration file defines the same index under allowed_fields, its list replaces the earlier list for that index. To disable an inherited index, set public_catalog: [] under allowed_fields in the later file. Omitting the key keeps the inherited list.
Usage
Inject ElasticQuerySearch into your service or controller. The bundle does not add an endpoint. This example makes the search available at POST /products/search and uses Symfony's authorization checker to require ROLE_PRODUCT_SEARCH:
use App\Entity\Product; use Nzo\ElasticQueryBundle\Query\ElasticQuerySearch; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Attribute\Route; final class ProductSearchController { public function __construct(private readonly ElasticQuerySearch $search) { } #[Route('/products/search', methods: ['POST'])] public function __invoke(Request $request): JsonResponse { $result = $this->search->search( $request->getContent(), Product::class, $request->query->getInt('page', 1), $request->query->getInt('limit', 20), ['role' => 'ROLE_PRODUCT_SEARCH'], ); return new JsonResponse([ 'items' => array_map(static fn (Product $product): array => [ 'id' => $product->getId(), 'title' => $product->getTitle(), ], $result['items']), 'totalItems' => $result['totalItems'], 'totalPages' => $result['totalPages'], ]); } }
The role option requires a configured symfony/security-bundle (or an application service named security.authorization_checker implementing AuthorizationCheckerInterface). If no checker is available, the protected search is denied. Omit access options only if you authorize the search elsewhere or intend it to be public.
Send JSON like this to the controller:
{
"query": {
"search": {
"and": [
{"field": "status", "match": "published"},
{"field": "title", "match": "desk"}
]
},
"sort": [{"field": "title", "order": "ASC"}]
}
}
You can also pass the same structure as a PHP array or a stdClass object. Invalid query syntax, known filter and field type mismatches, disallowed fields and invalid page numbers throw BadRequestHttpException (HTTP 400). Elasticsearch still validates mapping-specific details such as custom date formats. Backend failures are reported as server errors. If you need a JSON error body, configure it in your application.
Query language
searchis required. Use{}to match all documents ([]is also accepted for an empty search when passing a PHP array). Otherwise use anandororgroup. Each group takes one child object or a non-empty list of child objects, which may themselves be groups.- Each condition has a
fieldand one operator.matchandnotmatchaccept a string, number or boolean and use Elasticsearch'smatchquery.inandnotincompare exact terms and take a non-empty list of distinct scalar values. isnulltakes a boolean.truematches documents without an indexed value;falserequires an indexed value.gt,gte,lt,lteand inclusiverangeaccept numbers or dates such as2026-01-01and2026-01-01T12:30:00without a time zone.rangetakes two ordered numbers or two ordered dates.wildcardtakes a string pattern, for exampledesk*. Use it with a keyword field when you want to match the entire field value. Numeric, date and boolean fields do not support this operator. Prefer a literal prefix: patterns that start with*or?are more expensive.sortis optional and accepts an ordered list of{field, order}entries. Order isASCorDESC. Sorting atextfield requires a sortable.sortmultifield, as shown above. Dotted fields are validated against the mapping. For nested fields each condition produces its own Elasticsearch nested query; separate conditions in anandgroup can match different nested objects.
Pagination and scores
Pages start at 1. Pass null to use a configured default. The default page size cannot exceed items_max_limit, which cannot exceed max_result_window. Set max_result_window no higher than the Elasticsearch index's index.max_result_window.
The result contains items, the total matching hits (totalItems) and the number of reachable pages (totalPages, at least 1). A page that begins inside the window may have fewer items than requested. A page that begins outside the window is refused. With show_score: true, add a public setScoreElastic(float $score): void to your model if you want the bundle to assign the score when Elasticsearch returns one.
With hydrate: false in the FOSElastica transformer configuration, keep show_score: false to receive array rows in items. A search response reporting failed shards or a timeout is refused with HTTP 502, even if Elasticsearch returned HTTP 200.
Security
- Always select the model and any access options in application code. Do not read them from the search payload. Keep backend error details in server logs and disable debug mode in production.
allowed_fieldscontrols filters and sorting, not which documents or model properties the caller can read. Use a dedicated index or an application-enforced filter for tenant or record-level access. Only serialize properties the caller is allowed to see.- The bundle builds the Elasticsearch query from known operators and mapped fields. The request cannot supply raw Elasticsearch DSL. The payload limit, maximum of 100 groups and conditions combined, 8 levels below the root group, 10 sorts, 100 terms per list and 128 characters per wildcard help limit search cost. Apply request-body limits and rate limiting at your HTTP boundary as well.
License
This bundle is under the MIT license. See LICENSE.