How to perform a search and filter by exact prefix matching?

Last updated 22, Mar 2024

Question

How to perform a search and filter by exact prefix matching?

Answer

If you would like to request an exact phrase matching + prefix, then not return "Kowloon and New Kowloon" in the following example, the TEXT index type won't work.

FT.CREATE location_idx ON HASH PREFIX 1 location: SCHEMA Name AS name TEXT 

HSET location:1 Name "New York"
HSET location:2 Name "Newcastle" 
HSET location:3 Name "Kowloon and New Kowloon" 

This doesn't work:

FT.SEARCH location_idx "New*" RETURN 1 name
1) (integer) 3
2) "location:2"
3) 1) "name"
   2) "Newcastle"
4) "location:1"
5) 1) "name"
   2) "New York"
6) "location:3"
7) 1) "name"
   2) "Kowloon and New Kowloon"

The solution is to use a TAG field instead of TEXT. You shall define this index.

FT.CREATE location_idx ON HASH PREFIX 1 location: SCHEMA Name AS name TAG

The query syntax will be "@name:{New*}".

FT.SEARCH location\_idx "@name:{New\*}" RETURN 1 name
1) (integer) 2
2) "location:1"
3) 1) "name"
 2) "New York"
4) "location:2"
5) 1) "name"
 2) "Newcastle"

References

Learn more about the TAG field.