FIX: Reindex post for search when post is moved to a different topic.

FIX: Reindex post for search when post is moved to a different topic.

  • This is causing certain posts to appear in searches incorrectly as PostSearchData#raw_data contains the outdated title, category name and tag names.
diff --git a/app/services/search_indexer.rb b/app/services/search_indexer.rb
index 34b132c..2f496e1 100644
--- a/app/services/search_indexer.rb
+++ b/app/services/search_indexer.rb
@@ -134,7 +134,13 @@ class SearchIndexer
     category_name = topic.category&.name if topic
     tag_names = topic.tags.pluck(:name).join(' ') if topic
 
-    if Post === obj && (obj.saved_change_to_cooked? || force)
+    if Post === obj &&
+       (
+         obj.saved_change_to_cooked? ||
+         obj.saved_change_to_topic_id? ||
+         force
+       )
+
       if topic
         SearchIndexer.update_posts_index(obj.id, topic.title, category_name, tag_names, obj.cooked)
         SearchIndexer.update_topics_index(topic.id, topic.title, obj.cooked) if obj.is_first_post?
diff --git a/spec/services/search_indexer_spec.rb b/spec/services/search_indexer_spec.rb
index 3886eb0..097f419 100644
--- a/spec/services/search_indexer_spec.rb
+++ b/spec/services/search_indexer_spec.rb
@@ -81,4 +81,26 @@ describe SearchIndexer do
     raw_data = PostSearchData.where(post_id: post_id).pluck(:raw_data)[0]
     expect(raw_data).to eq("tester")
   end
+
+  describe '.index' do
+    let(:post) { Fabricate(:post) }
+
+    before do
+      SearchIndexer.enable
+    end
+
+    after do
+      SearchIndexer.disable
+    end
+
+    it 'should index posts correctly' do
+      expect { post }.to change { PostSearchData.count }.by(1)
+
+      expect { post.update!(raw: "this is new content") }
+        .to change { post.reload.post_search_data.raw_data }
+
+      expect { post.update!(topic_id: Fabricate(:topic).id) }
+        .to change { post.reload.post_search_data.raw_data }
+    end
+  end
 end

GitHub sha: d808f36f

1 Like

@SamSaffron Technically we need to reindex all the posts here. Do you know if we have a way of doing so?

1 Like

Yeah we have this, but I would like to wait maybe 3 weeks or so till we do a bump, let you finish your other tweaks:

see: discourse/reindex_search.rb at f8be43644b72bd36dd499c4c477cd440ceb0249f · discourse/discourse · GitHub

This commit has been mentioned on Discourse Meta. There might be relevant details there: