Redis/Jedis 中使用 RediSearch 的完整指南
jedis Redis Java client 项目地址: https://gitcode.com/gh_mirrors/je/jedis
Redis 作为一款高性能的内存数据库,其 RediSearch 模块提供了强大的全文搜索功能。本文将详细介绍如何在 Java 项目中通过 Jedis 客户端使用 RediSearch 功能。
一、RediSearch 客户端初始化
使用 RediSearch 前,需要先创建 Jedis 客户端连接。根据你的 Redis 部署方式,可以选择以下两种初始化方法:
1. 单节点连接方式
适用于连接单个 Redis 实例:
JedisPooled client = new JedisPooled("localhost", 6379);
2. 集群连接方式
适用于 Redis 集群环境:
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("127.0.0.1", 7379));
nodes.add(new HostAndPort("127.0.0.1", 7380));
JedisCluster client = new JedisCluster(nodes);
二、索引创建与管理
1. 定义索引结构
RediSearch 需要预先定义索引结构(Schema),指定字段类型和属性:
Schema sc = new Schema()
.addTextField("title", 5.0) // 文本字段,权重5.0
.addTextField("body", 1.0) // 文本字段,权重1.0
.addNumericField("price"); // 数值字段
2. 创建索引
创建索引时可以指定索引选项和过滤条件:
IndexDefinition def = new IndexDefinition()
.setPrefixes(new String[]{"item:", "product:"}) // 只索引特定前缀的键
.setFilter("@price>100"); // 只索引价格大于100的文档
client.ftCreate("item-index", IndexOptions.defaultOptions().setDefinition(def), sc);
或者使用更简洁的 FTCreateParams 方式:
client.ftCreate("item-index",
FTCreateParams.createParams()
.prefix("item:", "product:")
.filter("@price>100"),
TextField.of("title").weight(5.0),
TextField.of("body"),
NumericField.of("price")
);
三、文档操作
1. 添加文档
可以使用标准的 Redis Hash 结构添加文档:
Map<String, Object> fields = new HashMap<>();
fields.put("title", "hello world");
fields.put("state", "NY");
fields.put("body", "lorem ipsum");
fields.put("price", 1337);
client.hset("item:hw", RediSearchUtil.toStringMap(fields));
或者使用更便捷的 hsetObject 方法:
client.hsetObject("item:hw", fields);
四、搜索查询
1. 基本搜索
构建查询对象并执行搜索:
Query q = new Query("hello world")
.addFilter(new Query.NumericFilter("price", 0, 1000)) // 价格范围过滤
.limit(0, 5); // 分页限制
SearchResult sr = client.ftSearch("item-index", q);
2. 使用 FTSearchParams 搜索
另一种更灵活的搜索方式:
SearchResult sr = client.ftSearch("item-index",
"hello world",
FTSearchParams.searchParams()
.filter("price", 0, 1000)
.limit(0, 5));
3. 聚合查询
RediSearch 支持强大的聚合功能:
AggregationBuilder ab = new AggregationBuilder("hello")
.apply("@price/1000", "k") // 计算字段转换
.groupBy("@state", Reducers.avg("@k").as("avgprice")) // 按州分组计算平均价格
.filter("@avgprice>=2") // 过滤结果
.sortBy(10, SortedField.asc("@state")); // 排序
AggregationResult ar = client.ftAggregate("item-index", ab);
五、最佳实践建议
- 索引设计:根据查询需求合理设计索引结构,为高频查询字段设置更高权重
- 批量操作:对于大量文档插入,考虑使用管道(pipeline)提高性能
- 查询优化:合理使用过滤条件和分页,避免返回过多不必要的数据
- 集群环境:在集群环境下,确保相关数据分布在相同节点上以提高查询效率
通过本文介绍的方法,你可以在 Java 应用中轻松集成 Redis 的全文搜索功能,为应用增加强大的搜索能力。RediSearch 特别适合需要高性能搜索的场景,如电商商品搜索、内容检索等。
jedis Redis Java client 项目地址: https://gitcode.com/gh_mirrors/je/jedis
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考