Redis 在原生状态下并不支持全文检索功能,在特定场景下,可以借助RediSearch来处理文本数据。
Docker安装
sudo docker run -p 6379:6379 redis/redis-stack-server:latest
插入文档,为了使用全文搜索功能,必须将文档存储在哈希中
hset post:1 title "hello world" body "this is a cool document"
hset post:2 title "goodbye everybody" body "this is the best document"
Redis hset 语法:HSET key field value [field value ...]
创建索引,索引名为post_index,以 post: 前缀开头的所有哈希键。索引字段为 title 和 body,并且索引立即生效
FT.CREATE post_index prefix 1 post: SCHEMA title TEXT body TEXT
搜索索引,参数是索引名称和需要搜索的关键词
FT.SEARCH post_index "world"
搜索特定字段,需在字段前加上@标识
ft.search post_index "@title:world"
这个功能比较实用,RAG应用中也会应用到。
搜索结果分页,使用 LIMIT 关键词
ft.search post_index "world" LIMIT 10, 5
部分搜索,使用 * 标识
ft.search post_index "good*"
模糊匹配,使用 % 标识
ft.search post_index "%wold%"