如何在GROQ查询中实现文档tags对象数组的不区分大小写字符串匹配
The issue with your current query is that the in operator does exact string matching, which fails when the case of your target string doesn't perfectly match the tag values. Let's fix this with two reliable approaches for case-insensitive matching in GROQ:
1. Use Regular Expressions with the match Operator
GROQ supports regex matching via the match keyword, and you can add the i flag to enable case-insensitive matching. This is a clean way to match variations in capitalization:
*[_type == 'article' && tags[]->value match /js and ts/i] { ..., tags[] { value } }
How it works:
- The regex
/js and ts/iwill match any string that contains the sequence "js and ts" regardless of uppercase/lowercase combinations (like "JS and ts", "js and TS", etc.) - Note: I corrected
_type == 'articles'to_type == 'article'since your sample documents use the singulararticleas the_typevalue.
2. Normalize Case with lower() Function
Another approach is to convert both the tag values and your target string to lowercase, then use the in operator for exact matching on the normalized text:
*[_type == 'article' && 'js and ts' in tags[].lower(value)] { ..., tags[] { value } }
How it works:
lower(value)converts each tag'svalueto all lowercase characters- We compare against the lowercase version of your target string (
'js and ts'), ensuring case differences don't break the match
Both of these queries will return both of your sample articles, since they handle the case mismatch between "JS and ts" and "js and TS" correctly.
内容的提问来源于stack exchange,提问作者mahan

