hgaol commented on code in PR #1510:
URL: https://github.com/apache/answer/pull/1510#discussion_r2890462439


##########
internal/repo/embedding/embedding_repo.go:
##########
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package embedding
+
+import (
+       "context"
+       "encoding/json"
+       "math"
+       "sort"
+
+       "github.com/apache/answer/internal/base/data"
+       "github.com/apache/answer/internal/entity"
+       "github.com/segmentfault/pacman/log"
+       "xorm.io/builder"
+)
+
+// EmbeddingRepo defines the interface for embedding data access.
+type EmbeddingRepo interface {
+       Upsert(ctx context.Context, emb *entity.Embedding) error
+       GetByObjectID(ctx context.Context, objectID, objectType string) 
(*entity.Embedding, bool, error)
+       GetAll(ctx context.Context) ([]*entity.Embedding, error)
+       SearchSimilar(ctx context.Context, queryVector []float32, topK int) 
([]SimilarResult, error)
+       DeleteByObjectID(ctx context.Context, objectID, objectType string) error
+       Count(ctx context.Context) (int64, error)
+}
+
+// SimilarResult holds a similarity search result.
+type SimilarResult struct {
+       ObjectID   string  `json:"object_id"`
+       ObjectType string  `json:"object_type"`
+       Metadata   string  `json:"metadata"`
+       Score      float64 `json:"score"`
+}
+
+type embeddingRepo struct {
+       data *data.Data
+}
+
+// NewEmbeddingRepo creates a new EmbeddingRepo.
+func NewEmbeddingRepo(data *data.Data) EmbeddingRepo {
+       return &embeddingRepo{data: data}
+}
+
+// Upsert inserts or updates an embedding by (object_id, object_type).
+func (r *embeddingRepo) Upsert(ctx context.Context, emb *entity.Embedding) 
error {
+       existing := &entity.Embedding{}
+       exist, err := r.data.DB.Context(ctx).
+               Where(builder.Eq{"object_id": emb.ObjectID, "object_type": 
emb.ObjectType}).
+               Get(existing)
+       if err != nil {
+               log.Errorf("check embedding existence failed: %v", err)
+               return err
+       }
+
+       if exist {
+               emb.ID = existing.ID
+               _, err = r.data.DB.Context(ctx).ID(existing.ID).
+                       Cols("content_hash", "metadata", "embedding", 
"dimensions", "updated_at").
+                       Update(emb)
+               if err != nil {
+                       log.Errorf("update embedding failed: %v", err)
+                       return err
+               }
+               return nil
+       }
+
+       _, err = r.data.DB.Context(ctx).Insert(emb)
+       if err != nil {
+               log.Errorf("insert embedding failed: %v", err)
+               return err
+       }
+       return nil
+}
+
+// GetByObjectID returns an embedding by object ID and type.
+func (r *embeddingRepo) GetByObjectID(ctx context.Context, objectID, 
objectType string) (*entity.Embedding, bool, error) {
+       emb := &entity.Embedding{}
+       exist, err := r.data.DB.Context(ctx).
+               Where(builder.Eq{"object_id": objectID, "object_type": 
objectType}).
+               Get(emb)
+       if err != nil {
+               log.Errorf("get embedding failed: %v", err)
+               return nil, false, err
+       }
+       return emb, exist, nil
+}
+
+// GetAll returns all embeddings.
+func (r *embeddingRepo) GetAll(ctx context.Context) ([]*entity.Embedding, 
error) {
+       var list []*entity.Embedding
+       err := r.data.DB.Context(ctx).Find(&list)
+       if err != nil {
+               log.Errorf("get all embeddings failed: %v", err)
+               return nil, err
+       }
+       return list, nil
+}
+
+// SearchSimilar performs brute-force cosine similarity search in Go.
+func (r *embeddingRepo) SearchSimilar(ctx context.Context, queryVector 
[]float32, topK int) ([]SimilarResult, error) {

Review Comment:
   First of all, thank you @LinkinStars for the careful review! The goal of 
this PR is also to make it clear, so feel free to raise your concern and 
suggestions!
   
   > The biggest issue with this approach lies here: all data queries are 
performed in-memory. While this works for small datasets, it is undoubtedly 
unacceptable for large-scale data.
   >
   > Therefore, my suggestion is that if users are using PostgreSQL, they could 
directly utilize PostgreSQL + pgvector to store vector data and perform 
searches within the database.
   
   It makes sense. It's better to save vectors in vector DB. And I think it 
could support multiple vector DBs, while still support saving in main database 
or memory for test purpose. WDYT?
   
   > Furthermore, a more 'ideal' approach would be to expose this component as 
a plugin, allowing user Q&A data to be synchronized to external systems. This 
design is similar to how search plugins operate. For instance, an Elasticsearch 
(ES) plugin synchronizes Q&A data to ES for retrieval. The benefit of a 
plugin-based implementation is extensibility: users aren't restricted to the 
built-in database and can use their own custom vector databases. The required 
interfaces would likely mirror those of a search plugin, such as a data 
synchronization interface and a search interface.
   
   About plugin, do you mean make all the functionalities as a plugin, or just 
the storage for vectors? Per your statement, I assume the later one?
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to