GROQ: How to match exact string subset and exclude partial matches (WW not UWW)?
The match operator in GROQ isn't the right tool for your use case. The match operator is designed for full-text search with tokenization, not exact string pattern matching. When you use match, special characters like hyphens (-) are treated as word separators, which is why your query isn't working as expected.
For matching exact substrings or patterns with punctuation, you should use GROQ string functions instead. Here are a few approaches:
Solution 1: Using string::split() (Recommended)
Since you want to match -WW but not -UWW, you can split on the hyphen and check the last segment:
*[array::compact(string::split(item, "-"))[-1] == "WW"]This splits "HDTL65-WW" into ["HDTL65", "WW"] and checks if the last element equals "WW".
Solution 2: Check for exact suffix pattern
You could filter by checking if the item ends with the exact pattern you want:
*[item match "WW" && !(item match "UWW")]However, this still relies on match's tokenization behavior and might not be reliable for all edge cases with punctuation.
Solution 3: More explicit string checking
A more explicit approach using string functions:
*[
item match "WW" &&
!string::startsWith(array::compact(string::split(item, "-"))[-1], "U")
]Why match doesn't work here
As explained in the match operator documentation, match tokenizes text by breaking it on word boundaries and special characters. So "HDTL65-WW" gets indexed as ['HDTL65', 'WW'], and "HDTL65-UWW" becomes ['HDTL65', 'UWW'].
When you use *[item match "-WW*"], the hyphen is treated as a separator (not part of the search term), so the query essentially becomes meaningless. And *[item match "WW*"] matches all three documents because they all contain tokens that start with or match "WW" (since "UWW" contains "WW" as part of the token).
For exact string matching with punctuation, always prefer the string namespace functions like string::split(), string::startsWith(), or combine them with array functions for more complex patterns.
Show original thread15 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.