目录
- 引言
- docker-compose方式安装
- 用Go语言操作RediSearch
- RediSearch使用场景
引言
RediSearch是一个支持搜索功能的redis模块。本文对此模块进行了介绍,并用go语言实现了一个简单示例。
RediSearch提供了查询、二级索引、全文索引功能。你需要先在相关Redis条目上建立索引,然后才能使用RediSearch进行查询。
RediSearch使用了压缩算法和倒序索引算法,使得其在性能和内存占用上都有很好的表现。它可以支持精确匹配、模糊匹配、数字过滤等功能。
docker-compose方式安装
新建docker-compose.yml文件,内容如下:
# redis-stack version: '3.1' services: redis-stack: image: redis/redis-stack-server:latest ports: - 6380:6379 volumes: - ./data:/data
执行命令来启动容器:
docker-compose up -d
用Go语言操作RediSearch
redissearch-go是一个支持RediSearch的go语言客户端,使用起来很简单。下面写一个简单的示例:
func TestRedisSearch(t *testing.T) { // 连接 conn := redisearch.NewClient("localhost:6380", "tangshi") // 定义索引 sc := redisearch.NewSchema(redisearch.DefaultOptions).AddField(redisearch.NewTextFieldOptions("title", redisearch.TextFieldOptions{Weight: 5.0, Sortable: true})).AddField(redisearch.NewTextField("content")) // 删除现有索引 conn.Drop() // 创建索引 err := conn.CreateIndex(sc) assert.Equal(t, err, nil) // 添加文档 doc1 := redisearch.NewDocument("doc1", 1.0) doc1.Set("title", "春晓").Set("content", "春眠不觉晓,处处闻啼鸟。夜来风雨声,花落知多少。") doc2 := redisearch.NewDocument("doc2", 1.0) doc2.Set("title", "春夜喜雨").Set("content", "好雨知时节,当春乃发生。随风潜入夜,润物细无声。") doc3 := redisearch.NewDocument("doc3", 1.0) doc3.Set("title", "春夜洛城闻笛").Set("content", "谁家玉笛暗飞声,散入春风满洛城。此夜曲中闻折柳,何人不起故园情。") doc4 := redisearch.NewDocument("doc4", 1.0) doc4.Set("title", "江雪").Set("content", "千山鸟飞绝,万径人踪灭。孤舟蓑笠翁,独钓寒江雪。") doc5 := redisearch.NewDocument("doc5", 1.0) doc5.Set("title", "望庐山瀑布").Set("content", "日照香炉生紫烟,遥看瀑布挂前川。飞流直下三千尺,疑是银河落九天。") // 为索引添加文档 err = conn.IndexOptions(redisearch.DefaultIndexingOptions, []redisearch.Document{doc1, doc2, doc3, doc4, doc5}...) assert.Equal(t, err, nil) time.Sleep(time.Millisecond * 100) // 搜索 瀑布 docs, total, err := conn.Search(redisearch.NewQuery("*瀑布*").Limit(0, 5).SetReturnFields("title", "content")) assert.Equal(t, err, nil) assert.Equal(t, total, 1) assert.Equal(t, docs[0].Properties["title"], "望庐山瀑布") // 搜索 春 docs, total, err = conn.Search(redisearch.NewQuery("*春*").Limit(0, 5).SetReturnFields("title", "content").SetSortBy("title", true)) assert.Equal(t, err, nil) assert.Equal(t, total, 3) assert.Equal(t, docs[0].Properties["title"], "春夜喜雨") for _, item := range docs { t.Log(item.Properties["title"], item.Properties["content"]) } }
在上面的代码中,我们创建了一个名为tangshi的索引,然后添加了5个文档。接下来,我们分别搜索了 瀑布 和 春,并测试了搜索结果。
RediSearch使用场景
- 数据量不大,所有索引内容可以被放进内存中。由于redis的数据都存储在内存中,如果索引数据内容过大,可能不适合使用RediSearch。
- Ephemeral indexing,即临时索引,索引内容不需要长期存储。
如果有想详细了解的,可以查阅一下下面列出的参考资料。
参考资料
- RediSearch官方文档
- RediSearch官方github
- YouToBe上的RediSearch教程
- the case for ephemeral indexing
以上就是Go语言操作RediSearch进行搜索方法示例详解的详细内容,更多关于Go操作RediSearch搜索的资料请关注本网站其它相关文章!
您可能感兴趣的文章:
- 使用RediSearch实现在Redis中全文检索
- RediSearch加RedisJSON大于Elasticsearch的搜索存储引擎