@@ -60,30 +60,29 @@ def tags
6060 . joins ( :topic_tags , :tags )
6161 . where ( id : candidate_ids )
6262 . where ( "tags.id IN (?)" , DiscourseTagging . visible_tags ( @user . guardian ) . pluck ( :id ) )
63- . group ( "topics.id, tags.id, tags.name" ) # Group by topics.id and tags.id
63+ . group ( "topics.id" )
6464 . order ( "array_position(ARRAY#{ candidate_ids } , topics.id)" )
65- . pluck (
66- "tags.id" ,
67- "tags.name" ,
68- "tags.#{ count_column } " ,
69- "MIN(array_position(ARRAY#{ candidate_ids } , topics.id))" , # Get minimum index for ordering
70- )
71- . uniq # Ensure unique tags per topic
65+ . pluck ( "array_agg(tags.name)" )
66+ . map ( &:uniq )
7267 . map
73- . with_index do |( id , name , count , index ) , idx |
74- {
75- id : id ,
76- name : name ,
77- count : count ,
78- score : 1 / ( candidates [ idx ] . last + 1 ) , # Inverse of the distance for score
79- }
68+ . with_index { |tag_list , index | { tags : tag_list , score : candidates [ index ] . last } }
69+ . flat_map { |c | c [ :tags ] . map { |t | { name : t , score : c [ :score ] } } }
70+ . map do |c |
71+ c [ :score ] = 1 / ( c [ :score ] + 1 ) # inverse of the distance
72+ c
8073 end
81- . group_by { |tag | tag [ :name ] }
82- . map do |name , tags |
83- tags . first . merge ( score : tags . sum { |t | t [ :score ] } )
84- end # Aggregate scores per tag
85- . sort_by { |tag | -tag [ :score ] }
74+ . group_by { |c | c [ :name ] }
75+ . map { |name , scores | { name : name , score : scores . sum { |s | s [ :score ] } } }
76+ . sort_by { |c | -c [ :score ] }
8677 . take ( 5 )
78+ . then do |tags |
79+ models = Tag . where ( name : tags . map { _1 [ :name ] } ) . index_by ( &:name )
80+ tags . map do |tag |
81+ tag [ :id ] = models . dig ( tag [ :name ] ) &.id
82+ tag [ :count ] = models . dig ( tag [ :name ] ) &.public_send ( count_column ) || 0
83+ tag
84+ end
85+ end
8786 end
8887
8988 private
0 commit comments