探索如何在同一个Redis实例中同时使用向量功能和缓存功能,实现资源的最优利用
docker run -p 6379:6379 --name redis-stack redis/redis-stack:latest
HSET docs:01 doc_embedding <vector_bytes> category sports
JSON.SET docs:01 $ '{"doc_embedding":[0.34,0.63,-0.54,-0.69,0.98,0.61], "category": "sports"}'
import io.lettuce.core.RedisClient; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; /** * @author lengleng */ public class LettuceVectorExample { public static void main(String[] args) { // 创建 Redis 客户端 RedisClient redisClient = RedisClient.create("redis://localhost:6379"); StatefulRedisConnection<String, String> connection = redisClient.connect(); RedisCommands<String, String> commands = connection.sync(); // 创建包含向量字段的索引 String createIndex = "FT.CREATE myIndex ON HASH PREFIX 1 doc: SCHEMA embedding VECTOR FLAT 6 TYPE FLOAT32 DIM 4 DISTANCE_METRIC COSINE"; commands.sendCommand("FT.CREATE", "myIndex", "ON", "HASH", "PREFIX", "1", "doc:", "SCHEMA", "embedding", "VECTOR", "FLAT", "6", "TYPE", "FLOAT32", "DIM", "4", "DISTANCE_METRIC", "COSINE"); // 存储向量数据 float[] vector = {0.1f, 0.2f, 0.3f, 0.4f}; String vectorStr = floatArrayToString(vector); // 转换为字符串表示 commands.hset("doc:1", "embedding", vectorStr); // 执行向量搜索(KNN) float[] queryVector = {0.15f, 0.25f, 0.35f, 0.45f}; String query = "(@embedding:[VECTOR_RANGE 0.5 " + floatArrayToString(queryVector) + "])=>{$KNN: 1}"; String result = commands.sendCommand("FT.SEARCH", "myIndex", query).toString(); System.out.println("Search result: " + result); // 关闭连接 connection.close(); redisClient.shutdown(); } // 辅助方法:将 float 数组转换为字符串 private static String floatArrayToString(float[] vector) { StringBuilder sb = new StringBuilder(); for (float v : vector) { sb.append(v).append(" "); } return sb.toString().trim(); } }