MigrateTypeSenseSchema adds new fields and removes old fields from the existing collection schema in Typesense. This is useful when the schema has been updated, and fields need to be added or removed.
(ctx context.Context, collectionName string)
| 438 | // MigrateTypeSenseSchema adds new fields and removes old fields from the existing collection schema in Typesense. |
| 439 | // This is useful when the schema has been updated, and fields need to be added or removed. |
| 440 | func (t *TypesenseClient) MigrateTypeSenseSchema(ctx context.Context, collectionName string) error { |
| 441 | collection := t.Client.Collection(collectionName) |
| 442 | |
| 443 | currentSchemaResponse, err := collection.Retrieve(ctx) |
| 444 | if err != nil { |
| 445 | return fmt.Errorf("failed to retrieve current schema: %w", err) |
| 446 | } |
| 447 | |
| 448 | currentSchema := &api.CollectionSchema{ |
| 449 | Name: currentSchemaResponse.Name, |
| 450 | Fields: currentSchemaResponse.Fields, |
| 451 | } |
| 452 | |
| 453 | config, ok := collectionConfigs[collectionName] |
| 454 | if !ok { |
| 455 | return fmt.Errorf("unknown collection: %s", collectionName) |
| 456 | } |
| 457 | latestSchema := config.Schema |
| 458 | |
| 459 | newFields, _ := compareSchemas(currentSchema, latestSchema) |
| 460 | |
| 461 | for _, field := range newFields { |
| 462 | updateSchema := &api.CollectionUpdateSchema{ |
| 463 | Fields: []api.Field{field}, |
| 464 | } |
| 465 | |
| 466 | _, err := collection.Update(ctx, updateSchema) |
| 467 | if err != nil { |
| 468 | return fmt.Errorf("failed to add field %s: %w", field.Name, err) |
| 469 | } |
| 470 | logrus.Infof("Added new field %s to collection %s", field.Name, collectionName) |
| 471 | } |
| 472 | |
| 473 | return nil |
| 474 | } |
| 475 | |
| 476 | // compareSchemas compares the old schema with the new schema and returns: |
| 477 | // - newFields: fields present in new schema but not in old schema |
no test coverage detected