H-137: fix computed article distance mapping (#22)

Co-authored-by: Rogee <rogee@ipao.vip>
This commit is contained in:
Rogee
2026-08-14 22:40:48 +08:00
committed by GitHub
co-authored by rogee
parent 849304ac87
commit 97ca3bc472
3 changed files with 12 additions and 3 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ type Article struct {
AssociatedArticleID *uint `gorm:"index" json:"associated_article_id,omitempty"` // translations: root article
Meta json.RawMessage `gorm:"type:jsonb;serializer:json" json:"meta"`
CustomAttributes json.RawMessage `gorm:"type:jsonb;serializer:json" json:"custom_attributes"`
SemanticDistance *float64 `gorm:"column:semantic_distance;->;-:migration" json:"-"`
SemanticDistance *float64 `gorm:"-" json:"-"`
Portal Portal `gorm:"foreignKey:PortalID" json:"portal,omitempty"`
Category *Category `gorm:"foreignKey:CategoryID" json:"category,omitempty"`
@@ -65,7 +65,10 @@ func (r *ArticleEmbeddingRepo) SearchByEmbedding(ctx context.Context, portalID u
limit = 10
}
var articles []model.Article
var rows []struct {
model.Article
Distance *float64 `gorm:"column:semantic_distance"`
}
// Join articles with article_embeddings, compute cosine distance on vector_embedding column.
// pgvector cosine distance operator: <=> (for vector type)
err := r.db.WithContext(ctx).Raw(`
@@ -75,9 +78,14 @@ func (r *ArticleEmbeddingRepo) SearchByEmbedding(ctx context.Context, portalID u
AND a.deleted_at IS NULL AND ae.deleted_at IS NULL
ORDER BY semantic_distance
LIMIT ?
`, embedding, portalID, limit).Scan(&articles).Error
`, embedding, portalID, limit).Scan(&rows).Error
if err != nil {
return nil, err
}
articles := make([]model.Article, len(rows))
for i := range rows {
articles[i] = rows[i].Article
articles[i].SemanticDistance = rows[i].Distance
}
return articles, nil
}
@@ -139,6 +139,7 @@ func TestArticleEmbeddingRepo_SearchByEmbedding_ExcludesSoftDeletedArticleAndEmb
before, err := repo.SearchByEmbedding(context.Background(), portal.ID, embedding, 10)
require.NoError(t, err)
require.Len(t, before, 3)
require.NotNil(t, before[0].SemanticDistance)
require.NoError(t, db.Delete(&articles[1]).Error)
require.NoError(t, repo.DeleteByArticleID(context.Background(), articles[2].ID))