Limit the Number of Items Returned from a GROQ Query

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 6 months ago
Updated 6 months 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.