Limit the Number of Items Returned from a GROQ Query

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

When working with large datasets, or when you simply want the first couple of results, it's essential to understand how to slice an Array using GROQ. The syntax is simple and can be used on any Array from your JSON, it's mainly a matter of knowing where you want your start index and end index of the Array of results you want to return.

John Lindquist: [0:00] Before we dive into any more advanced queries, let's learn how to limit our results so they don't turn into hugely intensive operations. We're going to come in between our filter and our projection. Let's split this with some new lines here just to be absolutely clear.

[0:13] We'll use the brackets and say, let's grab the item at position zero, and rerun. You can see, we get the very first item as our result.

[0:22] If we want items one through five or zero through four, because it's zero-based, will do zero through four, run that again, and you can see we get zero through four or five results. If you want zero up until four, so stop before four, you can add another period there so you only get four results instead of five.

[0:45] We can keep on moving the positions of these. If we want two through four, then you can see we get our three results. Let's actually clear out our filter and clear out the selected property there. Let's just get the IDs and names back, and run this again.

[1:02] You can see that two through four is ID of three through five, because in our dataset, our data starts at an ID of one. Zero through four would be ID one through five in our dataset.

[1:17] That's pretty much it. Anytime you want to change the start index or the end index, or if you want it inclusive or non-inclusive, it all happens right here. Any time you want to get rid of it, just remove that and you'll get all the results back.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today