ElasticGraph Query API: Filtering
Use filter:
on a root query field to narrow down the returned results:
query FindArtist {
byName: artists(filter: {
name: {equalToAnyOf: ["U2"]}
}) {
nodes {
name
bio {
yearFormed
}
}
}
byBioYearFounded: artists(filter: {
bio: {yearFormed: {gt: 2000}}
}) {
nodes {
name
bio {
yearFormed
}
}
}
}
As shown here, filters have two basic parts:
- A field path: this specifies which field you want to filter on. When dealing with a nested field (e.g.
bio.yearFormed
), you’ll need to provide a nested object matching the field structure. - A filtering predicate: this specifies a filtering operator to apply at the field path.
Empty Filters
Filters with a value of null
or empty object ({}
) match all documents. When negated with not
, no documents are matched.
The filters in this query match all documents:
query EmptyFilters {
artists(filter: {
name: {equalToAnyOf: null}
bio: {yearFormed: {}}
}) {
nodes {
name
bio {
yearFormed
}
}
}
}
This particularly comes in handy when using query variables. It allows a query to flexibly support a wide array of filters without requiring them to all be used for an individual request.
query FindArtists(
$names: [String!] = null
$yearFormed_gt: Int = null
$albumNames: [String!] = null
) {
artists(filter: {
name: {equalToAnyOf: $names}
bio: {yearFormed: {gt: $yearFormed_gt}}
albums: {anySatisfy: {name: {equalToAnyOf: $albumNames}}}
}) {
nodes {
name
bio {
yearFormed
}
albums {
name
}
}
}
}