Unlock seamless workflows and faster delivery with our latest releases ā€“ get the details

Can you write a conditional GROQ request based on document fields in Sanity.io?

6 replies
Last updated: Feb 27, 2023
Is it possible to write a conditional groq request based on document fields? E.g. if I want to query for a specific field only if a filter is set (the filter is set in another document reference, so it can't be done with JS).
Feb 21, 2023, 3:49 PM
To give a little more context, here's a code example with just one filter. This works, but it becomes a total mess if I add more filters and they are going to be combined.

"models": select(
  type == "brand" => select(
    filterVehicleGroup != null => *[_type == "model" && brand._ref == ^.brand._ref && vehicleGroup == ^.filterVehicleGroup] | order(_createdAt desc) {
      "_key": _id,
      ${MODEL_CONTENT}
    },
    *[_type == "model" && brand._ref == ^.brand._ref] | order(_createdAt desc) {
      "_key": _id,
      ${MODEL_CONTENT}
    },
  ),
  type == "selected" => selected[]-> {
    _key,
    ${MODEL_CONTENT}
  }
)
Feb 21, 2023, 3:52 PM
Where in this query are you trying to add the additional filter?
Feb 21, 2023, 8:58 PM
This is just an example where
filterVehicleGroup
is the filter. The idea is to add multiple filters in the same way, where it adds it to the query if it's set or not equal to "all", like this for each filter:

filterFieldNameInDoc == filterValue
Feb 22, 2023, 1:59 PM
user M
I see that you have liked my message, and it's for sure a lot of messages to follow up on, but is it possible to add filters like this in GROQ without using select to check if there is null to exclude the filtering?
Feb 23, 2023, 1:58 PM
Did some more research and found a solution. Will paste it below if anyone else has a similar question šŸ˜Š

*[_type == "model"
  && ($filter1 == null || filter1 == $filter1) 
  && ($filter2 == null || filter2 == $filter2) 
  && ($filter3 == null || filter3 == $filter3) 
  && ($filter4 == null || filter4 == $filter4) 
  && ($filter5 == null || filter5 == $filter5)
]
Feb 23, 2023, 2:08 PM
Thanks for sharing your solution!
Feb 27, 2023, 5:12 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?