添加依赖
- 创建一个spring boot 应用
- 添加依赖
<dependency>
<groupId>com.redislabs</groupId>
<artifactId>spring-redisearch</artifactId>
<version>3.0.1</version>
</dependency>
- spring-redisearch 内部采用ettuce作为客户端来驱动redis,同样的还有jedis 和redisson
Redisearch 操作
获取实例
- application 配置redis地址
spring:
redis:
host: 192.168.20.3
- 使用StatefulRediSearchConnection操作redis,在spring中直接注入即可
创建索引
- 通StatefulRediSearchConnection的sync方法获取一个redisearchCommands实例然后创建索引
- CreateOptions 用于构建创建索引时设置的选项
- Field 用于封装建立索引的字段
- redisearchCommands.create 用于创建索引
RediSearchCommands<String, String> sync = statefulRediSearchConnection.sync();
CreateOptions<String,String> book = CreateOptions.<String,String>builder().prefix("Book").build();
Field<String> title = Field.text("name").build();
Field<String> author = Field.text("author").build();
sync.create("books-index",book,title,author);
查询数据
- 同样使用redisearchCommands 提供的search方法查询
SearchResults<String, String> search = redisSearchCommands.search("books-index", fuzzy);
注意事项
- 熟悉StatefulRediSearchConnection、CreateOption、redisearchCommands相关的api
- 参考redis官网的相关redis命令,相应的组件中都有相应的封装
参考
https://www.educba.com/spring-boot-commandlinerunner/
https://redis.io/commands/ft.create/