Skip to content

Commit 25bd64f

Browse files
ismail1432dunglas
authored andcommitted
Add example for the Custom ElasticSearch Filter (#741)
* Add example for the Custom ElasticSearch Filter I don't know if this example is very good but it works like a charm in my case and I use it. * Update filters.md
1 parent c7d5ac8 commit 25bd64f

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

core/filters.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -974,6 +974,33 @@ A constant score query filter is basically a class implementing the `ApiPlatform
974974
and the `ApiPlatform\Core\Bridge\Elasticsearch\DataProvider\Filter\FilterInterface`. API Platform includes a convenient
975975
abstract class implementing this last interface and providing utility methods: `ApiPlatform\Core\Bridge\Elasticsearch\DataProvider\Filter\AbstractFilter`.
976976

977+
Suppose you want to use the [match filter](https://api-platform.com/docs/core/filters/#match-filter) on a property named `$fullName` and you want to add the [and operator](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html#query-dsl-match-query-boolean) to your query:
978+
979+
```php
980+
<?php
981+
// api/src/ElasticSearch/AndOperatorFilterExtension.php
982+
983+
namespace App\ElasticSearch;
984+
985+
use ApiPlatform\Core\Bridge\Elasticsearch\DataProvider\Extension\RequestBodySearchCollectionExtensionInterface;
986+
987+
class AndOperatorFilterExtension implements RequestBodySearchCollectionExtensionInterface
988+
{
989+
public function applyToCollection(array $requestBody, string $resourceClass, ?string $operationName = null, array $context = []): array
990+
{
991+
$requestBody['query'] = $requestBody['query'] ?? [];
992+
$andQuery = [
993+
'query' => $context['filters']['fullName'],
994+
'operator' => 'and',
995+
];
996+
997+
$requestBody['query']['constant_score']['filter']['bool']['must'][0]['match']['full_name'] = $andQuery;
998+
999+
return $requestBody;
1000+
}
1001+
}
1002+
```
1003+
9771004
### Using Doctrine ORM Filters
9781005

9791006
Doctrine ORM features [a filter system](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/filters.html) that allows the developer to add SQL to the conditional clauses of queries, regardless the place where the SQL is generated (e.g. from a DQL query, or by loading associated entities).

0 commit comments

Comments
 (0)