feat: 類似度算出バッチ修正,ほか(#228) (#232)

#228

#228

#228

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #232
This commit was merged in pull request #232.
This commit is contained in:
2026-01-22 23:30:08 +09:00
parent 86209dcc84
commit f6de272f55
18 changed files with 553 additions and 76 deletions
+1 -23
View File
@@ -1,28 +1,6 @@
namespace :post_similarity do
desc '関聯投稿テーブル作成'
task calc: :environment do
dot = -> a, b { (a.keys & b.keys).sum { |k| a[k] * b[k] } }
norm = -> v { Math.sqrt(v.values.sum { |e| e * e }) }
cos = -> a, b do
na = norm.(a)
nb = norm.(b)
if na.zero? || nb.zero?
0.0
else
dot.(a, b) / na / nb
end
end
posts = Post.includes(:tags).to_a
posts.each_with_index do |post, i|
existence_of_tags = post.tags.index_with(1)
((i + 1)...posts.size).each do |j|
target_post = posts[j]
existence_of_target_tags = target_post.tags.index_with(1)
PostSimilarity.find_or_initialize_by(post:, target_post:).tap { |ps|
ps.cos = cos.(existence_of_tags, existence_of_target_tags)
}.save!
end
end
Similarity::Calc.call(Post, :tags)
end
end
+1 -23
View File
@@ -1,28 +1,6 @@
namespace :tag_similarity do
desc '関聯タグ・テーブル作成'
task calc: :environment do
dot = -> a, b { (a.keys & b.keys).sum { |k| a[k] * b[k] } }
norm = -> v { Math.sqrt(v.values.sum { |e| e * e }) }
cos = -> a, b do
na = norm.(a)
nb = norm.(b)
if na.zero? || nb.zero?
0.0
else
dot.(a, b) / na / nb
end
end
tags = Tag.includes(:posts).to_a
tags.each_with_index do |tag, i|
existence_of_posts = tag.posts.index_with(1)
((i + 1)...tags.size).each do |j|
target_tag = tags[j]
existence_of_target_posts = target_tag.posts.index_with(1)
TagSimilarity.find_or_initialize_by(tag:, target_tag:).tap { |ts|
ts.cos = cos.(existence_of_posts, existence_of_target_posts)
}.save!
end
end
Similarity::Calc.call(Tag, :posts)
end
end