求助:如何使用spring-lettucemod创建JSON类型RedisSearch索引
解决spring-lettucemod创建RedisSearch JSON类型索引的方法
- 首先确保你的Redis服务器已安装并启用RedisSearch和RedisJSON模块,这是创建JSON类型索引的前提。
- 在spring-lettucemod中,创建JSON类型索引需要在
CreateOptions里显式指定索引基于JSON类型,而非默认的Hash。你可以通过on(DataType.JSON)方法配置:
// 示例:创建JSON类型的RedisSearch索引 RedisModulesCommands commands = connection.sync(); CreateOptions createOptions = CreateOptions.builder() .on(DataType.JSON) // 指定索引基于JSON类型 .prefix("user:") // 匹配要索引的JSON键前缀 .build(); // 定义JSON字段映射,如提取$.name作为text字段、$.age作为numeric字段 commands.ftCreate("user-idx", createOptions, Field.text("name").path("$.name"), Field.numeric("age").path("$.age") );
- 若使用Spring Data Redis的高阶封装
RedisSearchTemplate,同样需指定DataType.JSON:
RedisSearchTemplate searchTemplate = new RedisSearchTemplate(connectionFactory); SearchIndexDefinition indexDefinition = new SearchIndexDefinition("user-idx") .withPrefix("user:") .onDataType(DataType.JSON) .addField(Field.text("name").path("$.name")) .addField(Field.numeric("age").path("$.age")); searchTemplate.createIndex(indexDefinition);
- 注意:如果你的spring-lettucemod版本较旧,需升级到支持RedisJSON索引的版本(比如Spring Boot Starter Data Redis 2.6+,对应lettucemod版本匹配)。
内容的提问来源于stack exchange,提问作者Samuel_liu
相关产品推荐
相关产品推荐

