Skip to content

Dynamically filter JPA entities and Mongo collections with a user-friendly query syntax. Seamless integration with Spring APIs. Star to support the project! ⭐️

Notifications You must be signed in to change notification settings

turkraft/springfilter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Filter

Spring Filter Logo

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.

⚠️ About Release 3.0.0

Spring Filter 3.0.0 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 if you notice anything wrong. Consider supporting the project by sponsoring us.

You can access the older version in the 2.x.x branch.

Example (try it live)

/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

/* 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<Accident> accidents;
  @ElementCollection List<Integer> ratings;
  // ...
}

🚀 Yes we support booleans, dates, enums, functions, and even relations! Need something else? Tell us here.

Sponsor our project and gain the advantage of having your issues prioritized for prompt resolution.

Integrations and Usages

JPA Integration

<dependency>
  <groupId>com.turkraft.springfilter</groupId>
  <artifactId>jpa</artifactId>
  <version>3.1.7</version>
</dependency>
@GetMapping(value = "/search")
Page<Entity> search(@Filter Specification<Entity> 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

<dependency>
  <groupId>com.turkraft.springfilter</groupId>
  <artifactId>mongo</artifactId>
  <version>3.1.7</version>
</dependency>
@GetMapping(value = "/search")
Page<Entity> search(@Filter(entityClass = Entity.class) Query query, Pageable page) {
    return mongoTemplate.find(query.with(pageable), Entity.class);
}

Using MongoRepository

public interface EntityRepository extends MongoRepository<Entity, String> {
  @Query("?0")
  List<Employee> findAll(Document document);
  @Query("?0")
  Page<Employee> findAll(Document document, Pageable pageable);
}

@GetMapping(value = "/search")
Page<Entity> search(@Filter(entityClass = Entity.class) Document document, Pageable page) {
    return entityRepository.findAll(query, page);
}

Filter Builder

<dependency>
  <groupId>com.turkraft.springfilter</groupId>
  <artifactId>core</artifactId>
  <version>3.1.7</version>
</dependency>
@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.

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.

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

Contributing

Ideas and pull requests are always welcome. Google's Java Style is used for formatting.

Contributors

License

Distributed under the MIT license.

About

Dynamically filter JPA entities and Mongo collections with a user-friendly query syntax. Seamless integration with Spring APIs. Star to support the project! ⭐️

Topics

Resources

Stars

Watchers

Forks

Sponsor this project

 

Contributors 4

  •  
  •  
  •  
  •