|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/binary" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "math" |
| 9 | + "os" |
| 10 | + "os/signal" |
| 11 | + "strconv" |
| 12 | + "syscall" |
| 13 | + |
| 14 | + "github.com/pterm/pterm" |
| 15 | + "github.com/redis/go-redis/v9" |
| 16 | + |
| 17 | + "github.com/qdrant/go-client/qdrant" |
| 18 | + |
| 19 | + "github.com/qdrant/migration/pkg/commons" |
| 20 | +) |
| 21 | + |
| 22 | +type MigrateFromRedisCmd struct { |
| 23 | + Redis commons.RedisConfig `embed:"" prefix:"redis."` |
| 24 | + Qdrant commons.QdrantConfig `embed:"" prefix:"qdrant."` |
| 25 | + Migration commons.MigrationConfig `embed:"" prefix:"migration."` |
| 26 | + IdField string `prefix:"qdrant." help:"Field storing Redis IDs in Qdrant." default:"__id__"` |
| 27 | + |
| 28 | + targetHost string |
| 29 | + targetPort int |
| 30 | + targetTLS bool |
| 31 | +} |
| 32 | + |
| 33 | +func (r *MigrateFromRedisCmd) Parse() error { |
| 34 | + var err error |
| 35 | + r.targetHost, r.targetPort, r.targetTLS, err = parseQdrantUrl(r.Qdrant.Url) |
| 36 | + if err != nil { |
| 37 | + return fmt.Errorf("failed to parse target URL: %w", err) |
| 38 | + } |
| 39 | + |
| 40 | + return nil |
| 41 | +} |
| 42 | + |
| 43 | +func (r *MigrateFromRedisCmd) Validate() error { |
| 44 | + return validateBatchSize(r.Migration.BatchSize) |
| 45 | +} |
| 46 | + |
| 47 | +func (r *MigrateFromRedisCmd) Run(globals *Globals) error { |
| 48 | + pterm.DefaultHeader.WithFullWidth().Println("Redis Vector to Qdrant Data Migration") |
| 49 | + |
| 50 | + err := r.Parse() |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("failed to parse input: %w", err) |
| 53 | + } |
| 54 | + |
| 55 | + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 56 | + defer stop() |
| 57 | + |
| 58 | + rdb := redis.NewClient(&redis.Options{ |
| 59 | + Addr: r.Redis.Addr, |
| 60 | + Username: r.Redis.Username, |
| 61 | + Password: r.Redis.Password, |
| 62 | + DB: r.Redis.DB, |
| 63 | + Protocol: r.Redis.Protocol, |
| 64 | + Network: r.Redis.Network, |
| 65 | + ClientName: r.Redis.ClientName, |
| 66 | + }) |
| 67 | + defer rdb.Close() |
| 68 | + |
| 69 | + targetClient, err := connectToQdrant(globals, r.targetHost, r.targetPort, r.Qdrant.APIKey, r.targetTLS) |
| 70 | + if err != nil { |
| 71 | + return fmt.Errorf("failed to connect to Qdrant target: %w", err) |
| 72 | + } |
| 73 | + defer targetClient.Close() |
| 74 | + |
| 75 | + targetCollectionExists, err := targetClient.CollectionExists(ctx, r.Qdrant.Collection) |
| 76 | + if err != nil { |
| 77 | + return fmt.Errorf("failed to check if collection exists: %w", err) |
| 78 | + } |
| 79 | + if !targetCollectionExists { |
| 80 | + return fmt.Errorf("target collection '%s' does not exist in Qdrant", r.Qdrant.Collection) |
| 81 | + } |
| 82 | + |
| 83 | + err = commons.PrepareOffsetsCollection(ctx, r.Migration.OffsetsCollection, targetClient) |
| 84 | + if err != nil { |
| 85 | + return fmt.Errorf("failed to prepare migration marker collection: %w", err) |
| 86 | + } |
| 87 | + |
| 88 | + displayMigrationStart("redis", r.Redis.Index, r.Qdrant.Collection) |
| 89 | + |
| 90 | + sourcePointCount, err := r.countRedisDocuments(ctx, rdb) |
| 91 | + if err != nil { |
| 92 | + return fmt.Errorf("failed to count documents in Redis index: %w", err) |
| 93 | + } |
| 94 | + |
| 95 | + err = r.migrateData(ctx, rdb, targetClient, sourcePointCount) |
| 96 | + if err != nil { |
| 97 | + return fmt.Errorf("failed to migrate data: %w", err) |
| 98 | + } |
| 99 | + |
| 100 | + targetPointCount, err := targetClient.Count(ctx, &qdrant.CountPoints{ |
| 101 | + CollectionName: r.Qdrant.Collection, |
| 102 | + Exact: qdrant.PtrOf(true), |
| 103 | + }) |
| 104 | + if err != nil { |
| 105 | + return fmt.Errorf("failed to count points in target: %w", err) |
| 106 | + } |
| 107 | + |
| 108 | + pterm.Info.Printfln("Target collection has %d points\n", targetPointCount) |
| 109 | + |
| 110 | + return nil |
| 111 | +} |
| 112 | + |
| 113 | +func (r *MigrateFromRedisCmd) countRedisDocuments(ctx context.Context, rdb *redis.Client) (uint64, error) { |
| 114 | + info, err := rdb.FTInfo(ctx, r.Redis.Index).Result() |
| 115 | + if err != nil { |
| 116 | + return 0, fmt.Errorf("failed to get Redis index info: %w", err) |
| 117 | + } |
| 118 | + |
| 119 | + pterm.Info.Printfln("Found Redis index '%s' with %d documents", r.Redis.Index, info.NumDocs) |
| 120 | + return uint64(info.NumDocs), nil |
| 121 | +} |
| 122 | + |
| 123 | +func (r *MigrateFromRedisCmd) migrateData(ctx context.Context, rdb *redis.Client, targetClient *qdrant.Client, sourcePointCount uint64) error { |
| 124 | + batchSize := r.Migration.BatchSize |
| 125 | + |
| 126 | + var currentOffset uint64 = 0 |
| 127 | + |
| 128 | + if !r.Migration.Restart { |
| 129 | + _, offsetStored, err := commons.GetStartOffset(ctx, r.Migration.OffsetsCollection, targetClient, r.Redis.Index) |
| 130 | + if err != nil { |
| 131 | + return fmt.Errorf("failed to get start offset: %w", err) |
| 132 | + } |
| 133 | + currentOffset = offsetStored |
| 134 | + } |
| 135 | + |
| 136 | + bar, _ := pterm.DefaultProgressbar.WithTotal(int(sourcePointCount)).Start() |
| 137 | + displayMigrationProgress(bar, currentOffset) |
| 138 | + |
| 139 | + info, err := rdb.FTInfo(ctx, r.Redis.Index).Result() |
| 140 | + if err != nil { |
| 141 | + return fmt.Errorf("failed to get index info: %w", err) |
| 142 | + } |
| 143 | + |
| 144 | + attrTypes := make(map[string]string) |
| 145 | + for _, attr := range info.Attributes { |
| 146 | + attrTypes[attr.Identifier] = attr.Type |
| 147 | + } |
| 148 | + |
| 149 | + for { |
| 150 | + res, err := rdb.FTSearchWithArgs(ctx, r.Redis.Index, "*", &redis.FTSearchOptions{ |
| 151 | + LimitOffset: int(currentOffset), |
| 152 | + Limit: int(batchSize), |
| 153 | + }).Result() |
| 154 | + if err != nil { |
| 155 | + return fmt.Errorf("failed to search Redis: %w", err) |
| 156 | + } |
| 157 | + |
| 158 | + count := len(res.Docs) |
| 159 | + if count == 0 { |
| 160 | + break |
| 161 | + } |
| 162 | + |
| 163 | + targetPoints := make([]*qdrant.PointStruct, 0, count) |
| 164 | + |
| 165 | + for i := 0; i < count; i++ { |
| 166 | + doc := res.Docs[i] |
| 167 | + |
| 168 | + parsedFields := make(map[string]interface{}) |
| 169 | + vectorMap := make(map[string]*qdrant.Vector) |
| 170 | + |
| 171 | + for fieldName, rawVal := range doc.Fields { |
| 172 | + attrType := attrTypes[fieldName] |
| 173 | + |
| 174 | + if attrType == redis.SearchFieldTypeVector.String() { |
| 175 | + vec := bytesToFloats([]byte(rawVal)) |
| 176 | + vectorMap[fieldName] = qdrant.NewVectorDense(vec) |
| 177 | + } else { |
| 178 | + parsedFields[fieldName] = parseFieldValue(attrType, rawVal) |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + point := &qdrant.PointStruct{ |
| 183 | + Id: arbitraryIDToUUID(doc.ID), |
| 184 | + Vectors: qdrant.NewVectorsMap(vectorMap), |
| 185 | + } |
| 186 | + |
| 187 | + payload := qdrant.NewValueMap(parsedFields) |
| 188 | + payload[r.IdField] = qdrant.NewValueString(doc.ID) |
| 189 | + point.Payload = payload |
| 190 | + |
| 191 | + targetPoints = append(targetPoints, point) |
| 192 | + } |
| 193 | + |
| 194 | + if len(targetPoints) > 0 { |
| 195 | + _, err = targetClient.Upsert(ctx, &qdrant.UpsertPoints{ |
| 196 | + CollectionName: r.Qdrant.Collection, |
| 197 | + Points: targetPoints, |
| 198 | + Wait: qdrant.PtrOf(true), |
| 199 | + }) |
| 200 | + if err != nil { |
| 201 | + return fmt.Errorf("failed to insert data into target: %w", err) |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + currentOffset += uint64(count) |
| 206 | + // Just a placeholder ID for offset tracking. |
| 207 | + // We're only using the offset count |
| 208 | + offsetId := qdrant.NewIDNum(0) |
| 209 | + err = commons.StoreStartOffset(ctx, r.Migration.OffsetsCollection, targetClient, r.Redis.Index, offsetId, currentOffset) |
| 210 | + if err != nil { |
| 211 | + return fmt.Errorf("failed to store offset: %w", err) |
| 212 | + } |
| 213 | + |
| 214 | + bar.Add(count) |
| 215 | + } |
| 216 | + |
| 217 | + pterm.Success.Printfln("Data migration finished successfully") |
| 218 | + return nil |
| 219 | +} |
| 220 | + |
| 221 | +func bytesToFloats(b []byte) []float32 { |
| 222 | + if len(b)%4 != 0 { |
| 223 | + log.Printf("Warning: byte slice length %d is not a multiple of 4, truncating", len(b)) |
| 224 | + b = b[:len(b)-(len(b)%4)] |
| 225 | + } |
| 226 | + |
| 227 | + fs := make([]float32, len(b)/4) |
| 228 | + for i := 0; i < len(fs); i++ { |
| 229 | + bits := binary.LittleEndian.Uint32(b[i*4 : (i+1)*4]) |
| 230 | + fs[i] = math.Float32frombits(bits) |
| 231 | + } |
| 232 | + return fs |
| 233 | +} |
| 234 | + |
| 235 | +func parseFieldValue(attrType string, val string) interface{} { |
| 236 | + // redis.SearchFieldTypeVector is handled |
| 237 | + // before invoking this function. |
| 238 | + if attrType == redis.SearchFieldTypeNumeric.String() { |
| 239 | + f, _ := strconv.ParseFloat(val, 64) |
| 240 | + return f |
| 241 | + } |
| 242 | + return val |
| 243 | +} |
0 commit comments