|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "log" |
| 9 | + "os" |
| 10 | + |
| 11 | + "github.com/typesense/typesense-go/v4/typesense/api" |
| 12 | + "github.com/typesense/typesense-go/v4/typesense/api/pointer" |
| 13 | +) |
| 14 | + |
| 15 | +// ImportDocumentsFromJSONL imports documents from a JSONL file in bulk |
| 16 | +// This is the production-ready way to load initial data |
| 17 | +func ImportDocumentsFromJSONL(ctx context.Context, collectionName, filePath string) error { |
| 18 | + log.Printf("Starting bulk import from %s to collection '%s'...", filePath, collectionName) |
| 19 | + |
| 20 | + // Read the JSONL file |
| 21 | + file, err := os.Open(filePath) |
| 22 | + if err != nil { |
| 23 | + return fmt.Errorf("failed to open file: %w", err) |
| 24 | + } |
| 25 | + defer file.Close() |
| 26 | + |
| 27 | + // Parse each line as a JSON document |
| 28 | + scanner := bufio.NewScanner(file) |
| 29 | + var documents []interface{} |
| 30 | + lineCount := 0 |
| 31 | + |
| 32 | + for scanner.Scan() { |
| 33 | + var doc map[string]interface{} |
| 34 | + if err := json.Unmarshal(scanner.Bytes(), &doc); err != nil { |
| 35 | + log.Printf("Warning: skipping invalid JSON line: %v", err) |
| 36 | + continue |
| 37 | + } |
| 38 | + documents = append(documents, doc) |
| 39 | + lineCount++ |
| 40 | + } |
| 41 | + |
| 42 | + if err := scanner.Err(); err != nil { |
| 43 | + return fmt.Errorf("error reading file: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + log.Printf("Read %d documents from file", lineCount) |
| 47 | + |
| 48 | + // Import documents in bulk using the import API |
| 49 | + // BatchSize controls how many documents are processed at once |
| 50 | + importParams := &api.ImportDocumentsParams{ |
| 51 | + BatchSize: pointer.Int(100), // Process in batches of 100 |
| 52 | + } |
| 53 | + |
| 54 | + // The Import method accepts []interface{} containing document maps |
| 55 | + results, err := Client.Collection(collectionName).Documents().Import( |
| 56 | + ctx, |
| 57 | + documents, |
| 58 | + importParams, |
| 59 | + ) |
| 60 | + |
| 61 | + if err != nil { |
| 62 | + return fmt.Errorf("bulk import failed: %w", err) |
| 63 | + } |
| 64 | + |
| 65 | + // Count successes and failures |
| 66 | + successCount := 0 |
| 67 | + failureCount := 0 |
| 68 | + |
| 69 | + for _, result := range results { |
| 70 | + if result.Success { |
| 71 | + successCount++ |
| 72 | + } else { |
| 73 | + failureCount++ |
| 74 | + // Log first few errors for debugging |
| 75 | + if failureCount <= 5 { |
| 76 | + log.Printf("Import error: %s", result.Error) |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + log.Printf("Bulk import completed: %d succeeded, %d failed", successCount, failureCount) |
| 82 | + |
| 83 | + if failureCount > 0 && failureCount > lineCount/2 { |
| 84 | + // Only error if more than half failed |
| 85 | + return fmt.Errorf("bulk import had too many failures: %d out of %d", failureCount, lineCount) |
| 86 | + } |
| 87 | + |
| 88 | + return nil |
| 89 | +} |
| 90 | + |
| 91 | +// CheckCollectionDocumentCount returns the number of documents in a collection |
| 92 | +func CheckCollectionDocumentCount(ctx context.Context, collectionName string) (int, error) { |
| 93 | + collection, err := Client.Collection(collectionName).Retrieve(ctx) |
| 94 | + if err != nil { |
| 95 | + return 0, fmt.Errorf("failed to retrieve collection: %w", err) |
| 96 | + } |
| 97 | + |
| 98 | + return int(*collection.NumDocuments), nil |
| 99 | +} |
| 100 | + |
| 101 | +// InitializeDataIfEmpty checks if collection is empty and imports data if needed |
| 102 | +// This is idempotent - safe to run on every startup |
| 103 | +func InitializeDataIfEmpty(ctx context.Context, collectionName, dataFilePath string) error { |
| 104 | + log.Printf("Checking if collection '%s' needs data initialization...", collectionName) |
| 105 | + |
| 106 | + // Check current document count |
| 107 | + count, err := CheckCollectionDocumentCount(ctx, collectionName) |
| 108 | + if err != nil { |
| 109 | + return fmt.Errorf("failed to check document count: %w", err) |
| 110 | + } |
| 111 | + |
| 112 | + if count > 0 { |
| 113 | + log.Printf("Collection '%s' already has %d documents, skipping import", collectionName, count) |
| 114 | + return nil |
| 115 | + } |
| 116 | + |
| 117 | + log.Printf("Collection '%s' is empty, importing data from %s", collectionName, dataFilePath) |
| 118 | + |
| 119 | + // Import data |
| 120 | + if err := ImportDocumentsFromJSONL(ctx, collectionName, dataFilePath); err != nil { |
| 121 | + return fmt.Errorf("failed to import data: %w", err) |
| 122 | + } |
| 123 | + |
| 124 | + // Verify import |
| 125 | + newCount, err := CheckCollectionDocumentCount(ctx, collectionName) |
| 126 | + if err != nil { |
| 127 | + return fmt.Errorf("failed to verify import: %w", err) |
| 128 | + } |
| 129 | + |
| 130 | + log.Printf("Data import successful: collection '%s' now has %d documents", collectionName, newCount) |
| 131 | + return nil |
| 132 | +} |
0 commit comments