👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Troubleshooting a Groq query for counting items in a hierarchy

17 replies
Last updated: Jul 7, 2021
Hi all, so I have a
country
,
region
,
breakItem
hierarchy and from the currently viewed
country
I'm trying to
count
the breakItems within it. Not having much luck with htis groq query though...

"brk_total": count(*[_type == "breakItem" && region->country[0]._ref == ^._id]),

The
region->country[0]
structure is all good, so I'm not sure what's going on. Any ideas? Thanks!
Jul 7, 2021, 12:30 PM
That should work, but I don’t know your schema. I assume
country
is an array? Is it always the first country? I.e., what about the other items in the list?
Jul 7, 2021, 12:38 PM
Country is an array, in this use case it’s always the first item in it so that’s all good.
Jul 7, 2021, 12:41 PM
Ok. Can you show more of your query? For example, I assume you`re doing something like:
*[_type == "country"] {
  "brk_total": count(*[_type == "breakItem" && region->country[0]._ref == ^._id])
}
So
^
is the country document?
Jul 7, 2021, 1:03 PM
Also, can you make sure that you’re using API version
v2021-03-25
or later?
v1
 has significant bugs related to the
->
operator.
Jul 7, 2021, 1:04 PM
Sure, had planned to but am just caught up a second… nearly there. Thanks so much for getting back to me 🤙
Jul 7, 2021, 1:05 PM
Right, so, relevant part of the query...

*[_type == "country" && !(_id in path("drafts.**")) && slug.current == "southern-california-usa"][0] {
	  "reg_total": count(*[_type == "region" && country[0]._ref == ^._id]),
	  "brk_total": count(*[_type == "breakItem" && region->country[0]._ref == ^._id]),
    "continent": continent[]->.cnt_name[0],
  }
Jul 7, 2021, 1:15 PM
^
is indeed the country document 👍
Jul 7, 2021, 1:16 PM
Boom, it was the API version! Thanks so much 🤙Are there any breaking changes between V1 & v2021-03-25?
Jul 7, 2021, 1:23 PM
Great!
Jul 7, 2021, 2:08 PM
Jul 7, 2021, 2:08 PM
Thanks
user L
, will check that out!
Jul 7, 2021, 2:13 PM
I'm running
groq
queries in Studio/Vision which seems to be tied to V1 of the API. Anyway to change that? Sorry for all the questions 😬
Jul 7, 2021, 2:14 PM
Great!
Jul 7, 2021, 2:08 PM
Jul 7, 2021, 2:08 PM
No problem! If you’re on a recent version of the Vision plugin, there should be a dropdown.
Jul 7, 2021, 2:16 PM
Ahh, on a more old skool version as we were having strange scrolling issues with one of the updates. Haven't looked to see if they've been fixed but will look into it again. Thanks again mate, top man 🤘
Jul 7, 2021, 2:18 PM
If not, make sure to report it!
Jul 7, 2021, 2:26 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?