TracksMastering Content OperationsCoursesBetween GROQ and a hard placeChained projections
Between GROQ and a hard place
Markdown Version

Chained projections

Log in to watch a video walkthrough of this lesson
Log in
Video thumbnail
Write sequential projections to transform responses into different shapes
Log in to mark your progress for each Lesson and Task

So far you have only written a single projection after a each filter. It is possible to chain projections, where each projection only contains the attributes of the previous one.

Query for an event with a headline and venue to return a title string for the event
*[
_type == "event"
&& defined(headline)
&& defined(venue)
][0]{
headline->{name},
venue->{name}
}{
"title": headline.name + " at " + venue.name
}

You might think about this as using each projection to create a variable which can be used in the next projection.

In the example above we know headline and venue are defined because that has been added to the filter.

But the same query can be even more flexible and handle instances where data could be missing.

Query for any event and render an appropriate title string using select()
*[_type == "event"][0]{
headline->{name},
venue->{name}
}{
"title": select(
headline.name && venue.name => headline.name + " at " + venue.name,
headline.name => headline.name,
venue.name => venue.name,
"Untitled event"
)
}

The select() GROQ function will return the first item that returns true. In this instance, any event that has both a headline and venue will return the complete string. Otherwise fall back to either the headline name, or venue name, or a string "Untitled event."

When you need to use dynamic values in GROQ queries you turn to parameters, let's look at those in the next lesson.

You have 2 uncompleted tasks in this lesson
0 of 2