Redisearch转义字符问题求助:含特殊字符关键词无法精确匹配
Hey there! I’ve run into this exact issue with RediSearch before—those special characters like hyphens can really throw off the default tokenizer. Let’s break down why your attempts weren’t working and fix it properly.
Why Your Queries Failed
RediSearch’s default tokenizer (usually the English one) treats hyphens as word separators, and the - also acts as a negation operator. So when you run ft.search "lolo-baba", it gets parsed as lolo OR -baba—looking for records with lolo and not baba, which is totally not what you want. Your escape attempts didn’t work because of shell escaping quirks and not targeting the specific field properly.
The Correct Solutions
Here are three reliable ways to get an exact match for lolo-baba:
1. Use the Exact Match Operator {}
This is the simplest method—RediSearch’s {} syntax treats the enclosed string as a single, un-tokenized value. No escaping needed!
FT.SEARCH your_index_name "@town={lolo-baba}"
Replace your_index_name with the name of your RediSearch index. This query will only return records where the town field exactly equals lolo-baba.
2. Field-Specific Exact Match with Proper Escaping
If you prefer using double quotes for exact phrases, you need to escape the hyphen and make sure your shell doesn’t mangle the escape characters. In redis-cli, use single quotes to wrap the entire query string to avoid shell escaping issues:
FT.SEARCH your_index_name '@town:"lolo\-baba"'
Or if you need to use double quotes, double-escape the hyphen:
FT.SEARCH your_index_name "@town:\"lolo\\-baba\""
3. Configure the Field with a Keyword Tokenizer (Long-Term Fix)
If you frequently need to query this field for exact matches with special characters, set the field to use the keyword tokenizer when creating your index. This stores the entire field value as a single token, so no splitting happens:
FT.CREATE your_index_name ON HASH PREFIX 1 Record_ SCHEMA name TEXT job TEXT town TEXT TOKENIZER keyword
After creating the index this way, a simple query like FT.SEARCH your_index_name "lolo-baba" will return the exact match you need, since town values aren’t split into tokens anymore.
Quick Recap of Your Attempts
ft.search "lolo-baba": Failed because it parsed the hyphen as a separator/negation, no field targeting.- Repeating the same query: Same issue, since the syntax wasn’t fixed.
ft.search "lolo\\-baba": Failed because you didn’t target thetownfield, and shell escaping might have messed up the hyphen escape.
Pick the method that fits your use case—option 1 is great for one-off queries, while option 3 is perfect if this field needs regular exact matching.
内容的提问来源于stack exchange,提问作者rain481526

