insertWithAutoCreateCollection 插入向量,如果集合不存在则自动创建
(ctx context.Context, collection string, record vectorstore.VectorRecord, dimension int)
| 871 | |
| 872 | // insertWithAutoCreateCollection 插入向量,如果集合不存在则自动创建 |
| 873 | func (s *EmbeddingService) insertWithAutoCreateCollection(ctx context.Context, collection string, record vectorstore.VectorRecord, dimension int) error { |
| 874 | // 尝试直接插入 |
| 875 | err := s.vectorStore.Insert(ctx, collection, []vectorstore.VectorRecord{record}) |
| 876 | if err == nil { |
| 877 | return nil |
| 878 | } |
| 879 | |
| 880 | // 检查是否是集合不存在的错误 |
| 881 | if vsErr, ok := err.(*vectorstore.VectorStoreError); ok { |
| 882 | if vsErr.Code == vectorstore.ErrCodeCollectionNotFound || vsErr.Code == vectorstore.ErrCodeUnknown { |
| 883 | // 尝试创建集合 |
| 884 | collectionConfig := vectorstore.CollectionConfig{ |
| 885 | Name: collection, |
| 886 | Dimension: dimension, |
| 887 | Metric: "cosine", |
| 888 | IndexType: "HNSW", |
| 889 | } |
| 890 | |
| 891 | logger.SysLogf("集合不存在,正在创建集合: %s", collection) |
| 892 | if createErr := s.vectorStore.CreateCollection(ctx, collectionConfig); createErr != nil && !vectorstore.IsExistsError(createErr) { |
| 893 | return fmt.Errorf("创建集合失败: %v", createErr) |
| 894 | } |
| 895 | |
| 896 | // 重新尝试插入 |
| 897 | if insertErr := s.vectorStore.Insert(ctx, collection, []vectorstore.VectorRecord{record}); insertErr != nil { |
| 898 | return fmt.Errorf("创建集合后插入向量失败: %v", insertErr) |
| 899 | } |
| 900 | return nil |
| 901 | } |
| 902 | } |
| 903 | |
| 904 | // 其他错误,使用重试机制 |
| 905 | return s.insertWithRetry(ctx, collection, record) |
| 906 | } |
| 907 | |
| 908 | // insertWithRetry 带重试机制的插入 |
| 909 | func (s *EmbeddingService) insertWithRetry(ctx context.Context, collection string, record vectorstore.VectorRecord) error { |
no test coverage detected