From 575dc11cb2045c32b8fc0325de7bc321bd4728aa Mon Sep 17 00:00:00 2001
From: Eugen Rochko <eugen@zeonfederated.com>
Date: Wed, 2 Oct 2019 20:04:46 +0200
Subject: [PATCH] Fix needlessly indexing unsearchable statuses into
 ElasticSearch (#12041)

---
 app/chewy/statuses_index.rb |  8 ++++----
 app/models/status.rb        | 10 ++++++----
 2 files changed, 10 insertions(+), 8 deletions(-)

diff --git a/app/chewy/statuses_index.rb b/app/chewy/statuses_index.rb
index b7365d5cac..f5735421c7 100644
--- a/app/chewy/statuses_index.rb
+++ b/app/chewy/statuses_index.rb
@@ -31,19 +31,19 @@ class StatusesIndex < Chewy::Index
     },
   }
 
-  define_type ::Status.unscoped.without_reblogs.includes(:media_attachments) do
+  define_type ::Status.unscoped.kept.without_reblogs.includes(:media_attachments), delete_if: ->(status) { status.searchable_by.empty? } do
     crutch :mentions do |collection|
-      data = ::Mention.where(status_id: collection.map(&:id)).pluck(:status_id, :account_id)
+      data = ::Mention.where(status_id: collection.map(&:id)).where(account: Account.local).pluck(:status_id, :account_id)
       data.each.with_object({}) { |(id, name), result| (result[id] ||= []).push(name) }
     end
 
     crutch :favourites do |collection|
-      data = ::Favourite.where(status_id: collection.map(&:id)).pluck(:status_id, :account_id)
+      data = ::Favourite.where(status_id: collection.map(&:id)).where(account: Account.local).pluck(:status_id, :account_id)
       data.each.with_object({}) { |(id, name), result| (result[id] ||= []).push(name) }
     end
 
     crutch :reblogs do |collection|
-      data = ::Status.where(reblog_of_id: collection.map(&:id)).pluck(:reblog_of_id, :account_id)
+      data = ::Status.where(reblog_of_id: collection.map(&:id)).where(account: Account.local).pluck(:reblog_of_id, :account_id)
       data.each.with_object({}) { |(id, name), result| (result[id] ||= []).push(name) }
     end
 
diff --git a/app/models/status.rb b/app/models/status.rb
index 078a645663..3504ac3709 100644
--- a/app/models/status.rb
+++ b/app/models/status.rb
@@ -129,12 +129,14 @@ class Status < ApplicationRecord
   REAL_TIME_WINDOW = 6.hours
 
   def searchable_by(preloaded = nil)
-    ids = [account_id]
+    ids = []
+
+    ids << account_id if local?
 
     if preloaded.nil?
-      ids += mentions.pluck(:account_id)
-      ids += favourites.pluck(:account_id)
-      ids += reblogs.pluck(:account_id)
+      ids += mentions.where(account: Account.local).pluck(:account_id)
+      ids += favourites.where(account: Account.local).pluck(:account_id)
+      ids += reblogs.where(account: Account.local).pluck(:account_id)
     else
       ids += preloaded.mentions[id] || []
       ids += preloaded.favourites[id] || []
-- 
GitLab