https://github.com/turkraft/springfilter
Dynamically filter JPA entities and Mongo collections with a user-friendly query syntax. Seamless integration with Spring APIs. Star to support the project! ⭐️
https://github.com/turkraft/springfilter
filter hibernate java jpa mongodb odata query search spring
Last synced: 4 months ago
JSON representation
Dynamically filter JPA entities and Mongo collections with a user-friendly query syntax. Seamless integration with Spring APIs. Star to support the project! ⭐️
- Host: GitHub
- URL: https://github.com/turkraft/springfilter
- Owner: turkraft
- Created: 2021-02-08T06:37:47.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2025-07-01T12:57:02.000Z (4 months ago)
- Last Synced: 2025-07-09T14:14:09.019Z (4 months ago)
- Topics: filter, hibernate, java, jpa, mongodb, odata, query, search, spring
- Language: Java
- Homepage: https://turkraft.com/springfilter
- Size: 1.11 MB
- Stars: 249
- Watchers: 8
- Forks: 38
- Open Issues: 21
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
Awesome Lists containing this project
README
# Spring Filter
Are you looking for an effortless way to dynamically filter entities? Look no further than Spring Filter. With Spring Filter, your API will benefit from a comprehensive search functionality. Even if you don't have a web API, you can still leverage the powerful filter builder to generate complex SQL or Mongo queries.
The library's modular design and seamless integration with Spring make it easy to extend with custom operators and functions, or even integrate it into a different platform. Say goodbye to the headache of generating valid queries in frontend applications, as JavaScript filter builders are also available to simplify the process.
:warning: About Release 3.0.0
> [Spring Filter 3.0.0](https://github.com/turkraft/springfilter/issues/254) is a new release built from the ground up. It includes much better integration with Spring, with many new features, enhancements and bug fixes.
> The language syntax didn't change, frontend applications will therefore not require any modification.
> The new `FilterBuilder` class is incompatible with the previous one and other breaking changes are present but the basic usage of the library remains similar.
> Please feel free to [create an issue](https://github.com/turkraft/spring-filter/issues) if you notice anything wrong. [Consider supporting the project by sponsoring us](https://github.com/sponsors/torshid).
> You can access the older version in the [2.x.x branch](https://github.com/turkraft/spring-filter/tree/2.x.x).
## Example ([try it live](https://springfilter-jpa.onrender.com/))
*/search?filter=* **average**(ratings) **>** 4.5 **and** brand.name **in** ['audi', 'land rover'] **and** (year **>** 2018 **or** km **<** 50000) and color **:** 'white' **and** accidents **is empty**
```java
/* Entity used in the query above */
@Entity public class Car {
@Id long id;
int year;
int km;
@Enumerated Color color;
@ManyToOne Brand brand;
@OneToMany List accidents;
@ElementCollection List ratings;
// ...
}
```
> :rocket: Yes we support booleans, dates, enums, functions, **and even relations**! Need something else? [Tell us here](https://github.com/turkraft/spring-filter/issues).
## [Sponsors](https://github.com/sponsors/torshid)
Sponsor our project and gain the advantage of having your issues prioritized for prompt resolution.
## Integrations and Usages
### JPA Integration
```xml
com.turkraft.springfilter
jpa
3.1.9
```
```java
@GetMapping(value = "/search")
Page search(@Filter Specification spec, Pageable page) {
return repository.findAll(spec, page);
}
```
The repository should implement `JpaSpecificationExecutor` in order to execute Spring's Specification, `SimpleJpaRepository` is a well known implementation. You can remove the `Pageable` argument and return a `List` if pagination and sorting are not needed.
### Mongo Integration
```xml
com.turkraft.springfilter
mongo
3.1.9
```
```java
@GetMapping(value = "/search")
Page search(@Filter(entityClass = Entity.class) Query query, Pageable page) {
return mongoTemplate.find(query.with(pageable), Entity.class);
}
```
#### Using MongoRepository
```java
public interface EntityRepository extends MongoRepository {
@Query("?0")
List findAll(Document document);
@Query("?0")
Page findAll(Document document, Pageable pageable);
}
@GetMapping(value = "/search")
Page search(@Filter(entityClass = Entity.class) Document document, Pageable page) {
return entityRepository.findAll(query, page);
}
```
### Filter Builder
```xml
com.turkraft.springfilter
core
3.1.9
```
```java
@Autowired FilterBuilder fb;
FilterNode filter = fb.field("year").equal(fb.input(2023)).and(fb.isNull(fb.field("category"))).get();
@Autowired ConversionService cs;
String query = cs.convert(filter, String.class); // year : 2023 and category is null
```
Please note that Spring's `ConversionService` is internally used when converting objects to strings and vice-versa.
Spring Filter does not enforce any pattern for dates and other types.
Customization should be done directly within Spring if required.
### JavaScript Query Builder
Instead of manually writing string queries in your frontend applications, you may use
the [JavaScript query builder](https://github.com/sisimomo/Spring-Filter-Query-Builder).
```javascript
import { sfAnd, sfEqual, sfGt, sfIsNull, sfLike, sfNot, sfOr } from 'spring-filter-query-builder';
const filter = sfAnd([
sfAnd([sfEqual('status', 'active'), sfGt('createdAt', '1-1-2000')]),
sfOr([sfLike('value', '*hello*'), sfLike('name', '*world*')]),
sfNot(sfOr([sfGt('id', 100), sfIsNull('category.order')])),
]);
const req = await fetch('http://api/person?filter=' + filter.toString());
```
### Angular Query Builder
Please see [documentation](https://github.com/68ociredef/spring-filter-ng).
## Syntax
### Fields
`field`, `field.nestedField`
### Inputs
`123`, `-321.123`, `true`, `false`, `'hello world'`, `'escape \' quote'`, `'1-01-2023'`
### Collections
`[1, 2, 3]`, `[field, ['x', 'y'], 99]`
### Functions
`f()`, `f(x)`, `f(x, y)`
### Placeholders
`` `place_holder` ``
### Priority
`x and (y or z)`
### Prefix Operators
`op expr`, `not ready`
### Infix Operators
`expr op expr`, `x and y`
### Postfix Operators
`expr op`, `field is null`
## Common Language
Below are listed the operators and functions which are supported by all integrations (JPA and Mongo).
Integrations may extend this common language.
### Logical Operators
Literal Description Example
and and's two expressions status : 'active' and createdAt > '1-1-2000'
or or's two expressions value ~ '*hello*' or name ~ '*world*'
not not's an expression not (id > 100 or category.order is null)
### Value Comparators
Literal Description Example
~ checks if the left (string) expression is similar to the right (string) expression catalog.name ~ '*electronic*'
~~ similar to the previous operator but case insensitive catalog.name ~~ 'ElEcTroNic*'
: checks if the left expression is equal to the right expression id : 5
! checks if the left expression is not equal to the right expression username ! 'torshid'
> checks if the left expression is greater than the right expression distance > 100
>: checks if the left expression is greater or equal to the right expression distance >: 100
< checks if the left expression is smaller than the right expression distance < 100
<: checks if the left expression is smaller or equal to the right expression distance <: 100
is null checks if an expression is null status is null
is not null checks if an expression is not null status is not null
is empty checks if the (collection) expression is empty children is empty
is not empty checks if the (collection) expression is not empty children is not empty
in checks if an expression is present in the right expressions status in ['initialized', 'active']
not in checks if an expression is not present in the right expressions status not in ['failed', 'closed']
### Functions
Name Description Example
size returns the collection's size size(accidents)
## Articles
* [Easily filter entities in your Spring API](https://torshid.medium.com/easily-filter-entities-in-your-spring-api-f433537cfd41)
## Contributing
Ideas and pull requests are always welcome.
[Google's Java Style](https://github.com/google/styleguide/blob/gh-pages/eclipse-java-google-style.xml)
is used for formatting.
## Contributors
* Thanks to [@marcopag90](https://github.com/marcopag90) and [@glodepa](https://github.com/glodepa)
for adding support to MongoDB.
* Thanks to [@sisimomo](https://github.com/sisimomo) for creating
the [JavaScript query builder](https://github.com/sisimomo/Spring-Filter-Query-Builder).
* Thanks to [@68ociredef](https://github.com/68ociredef) for creating
the [Angular query builder](https://github.com/68ociredef/spring-filter-ng).
## License
Distributed under the [MIT license](LICENSE).