Skip to main content

More complex queries

Say you run a fantastic movie community like The Movie Database. You have already implemented some basic features (see Basic Queries). Now you want to run sophisticated queries.

Complex sorting

You want to display a list of the three highest rated movies on the homepage.

query BestMovies {
movies(orderBy: { reviews: { rating: { AVG: DESC } } }, first: 3) {
identifier
}
}

Retrieving data from external APIs

You want to display the title of the best two movies and their links on the homepage.

query BestMoviesExternalInformation {
movies(orderBy: { reviews: { rating: { AVG: DESC } } }, first: 3) {
identifier
original_title
homepage
}
}

In your domain model, a movie is considered a target. You do not wish to store its data but reference it instead. original_title and homepage come from an external API accessible via the Reactions GraphQL API. In this case, you are running a query on The Movie Database.

Aggregations

You're also interested in the average rating of these movies and how many reviews were written on each movie.

query BestMoviesAverageRating {
movies(orderBy: { reviews: { rating: { AVG: DESC } } }, first: 3) {
identifier
original_title
homepage
reviewsAggregations {
rating {
AVG
}
COUNT
}
}
}

Complex filtered sorting

You're not interested in what people thought 10 years ago: instead, you want to see what movies people enjoyed in 2019. Let's see how to sort the movies by the average rating given by users in 2019.

query BestMovies2019 {
movies(
orderBy: {
reviews: {
rating: { AVG: DESC }
where: { AND: { GTE: { created: "2019-01-01T00:00:00.000Z" }, LT: { created: "2020-01-01T00:00:00.000Z" } } }
}
}
first: 3
) {
identifier
original_title
homepage
reviewsAggregations(
where: { AND: { GTE: { created: "2019-01-01T00:00:00.000Z" }, LT: { created: "2020-01-01T00:00:00.000Z" } } }
) {
rating {
AVG
}
COUNT
}
}
}