GROQ ellipsis operator... and projections

Written by Lo Etheridge, Kapehe

On this week's Kap & Lauren learn GROQ - Part 5, we explored the ellipsis operator (... ), scope, chaining projections, and pickles. Kap and I are dill pickle lovers, but we welcome sweet pickle lovers with open arms! But enough about pickles, let's talk about the ellipsis operator.

Using the e-commerce sample dataset, we filtered through the candy products and pulled out the image [] array metadata, title, and price, but we wanted to get a count of categories associated with each candy bar. The ellipsis operator allowed us to use the count() function in our projection and still return all of the attributes without having to list them individually. Once you make a specific projection, only what you specify in the expression will return. This is where the ellipsis operator shines, it brings all the available attributes along for the ride when you are making a custom field or computation.

*[_type == "product"]{
  ...,
  defaultProductVariant{
    ...,
    "imageMetadata": images[]{
      asset->{
      metadata
      }
    }
  },
  "numberOfCategories": count(categories)
}{
  numberOfCategories,
  title,
  defaultProductVariant{
  	imageMetadata,
  	price
 }
}

Our final query shows the ... in action. We are filtering through the product document and using the ellipsis to return all of the product attributes so we can use them later.

PortableText [components.type] is missing "protip"

Kap and I found this to be quite tricky when we first learned about it. The defaultProductVariant object is nested projection where we are pulling out image metadata information using the custom field or alias, imageMetadata. Kap and I used the ellipsis operator (...) again so we could return all of the attributes of defaultProductVariant along with our custom field. The second use of the ellipsis operator allowed us to pull out the title and price in the last chained projection.

If you missed the stream, you can watch Kap & Lauren learn GROQ - Part 5 on YouTube. Follow us on Twitch and tune in for another episode of Kap & Lauren learn GROQ, we hope to see you there!