|
| 1 | +# Filtering |
| 2 | + |
| 3 | +Resources can be filtered by attributes using the `filter` query parameter. |
| 4 | +By default, all attributes are filterable. |
| 5 | +The filtering strategy we have selected, uses the following form. |
| 6 | + |
| 7 | +``` |
| 8 | +?filter[attribute]=value |
| 9 | +``` |
| 10 | + |
| 11 | +For operations other than equality, the query can be prefixed with an operation identifier. |
| 12 | +Examples can be found in the table below. |
| 13 | + |
| 14 | +| Operation | Prefix | Example | |
| 15 | +|-------------------------------|---------------|------------------------------------------| |
| 16 | +| Equals | `eq` | `?filter[attribute]=eq:value` | |
| 17 | +| Not Equals | `ne` | `?filter[attribute]=ne:value` | |
| 18 | +| Less Than | `lt` | `?filter[attribute]=lt:10` | |
| 19 | +| Greater Than | `gt` | `?filter[attribute]=gt:10` | |
| 20 | +| Less Than Or Equal To | `le` | `?filter[attribute]=le:10` | |
| 21 | +| Greater Than Or Equal To | `ge` | `?filter[attribute]=ge:10` | |
| 22 | +| Like (string comparison) | `like` | `?filter[attribute]=like:value` | |
| 23 | +| In Set | `in` | `?filter[attribute]=in:value1,value2` | |
| 24 | +| Not In Set | `nin` | `?filter[attribute]=nin:value1,value2` | |
| 25 | +| Is Null | `isnull` | `?filter[attribute]=isnull:` | |
| 26 | +| Is Not Null | `isnotnull` | `?filter[attribute]=isnotnull:` | |
| 27 | + |
| 28 | +Filters can be combined and will be applied using an AND operator. |
| 29 | +The following are equivalent query forms to get articles whose ordinal values are between 1-100. |
| 30 | + |
| 31 | +```http |
| 32 | +GET /api/articles?filter[ordinal]=gt:1,lt:100 HTTP/1.1 |
| 33 | +Accept: application/vnd.api+json |
| 34 | +``` |
| 35 | +```http |
| 36 | +GET /api/articles?filter[ordinal]=gt:1&filter[ordinal]=lt:100 HTTP/1.1 |
| 37 | +Accept: application/vnd.api+json |
| 38 | +``` |
| 39 | + |
| 40 | +## Custom Filters |
| 41 | + |
| 42 | +You can customize the filter implementation by overriding the method in the `DefaultEntityRepository`. |
| 43 | + |
| 44 | +```c# |
| 45 | +public class AuthorRepository : DefaultEntityRepository<Author> |
| 46 | +{ |
| 47 | + public AuthorRepository( |
| 48 | + AppDbContext context, |
| 49 | + ILoggerFactory loggerFactory, |
| 50 | + IJsonApiContext jsonApiContext) |
| 51 | + : base(context, loggerFactory, jsonApiContext) |
| 52 | + { } |
| 53 | + |
| 54 | + public override IQueryable<TEntity> Filter( |
| 55 | + IQueryable<TEntity> authors, |
| 56 | + FilterQuery filterQuery) |
| 57 | + // if the filter key is "query" (filter[query]), |
| 58 | + // find Authors with matching first or last names |
| 59 | + // for all other filter keys, use the base method |
| 60 | + => filter.Attribute.Is("query") |
| 61 | + ? authors.Where(a => |
| 62 | + a.First.Contains(filter.Value) |
| 63 | + || a.Last.Contains(filter.Value)) |
| 64 | + : base.Filter(authors, filter); |
| 65 | +} |
| 66 | +``` |
| 67 | + |
0 commit comments