about summary refs log tree commit diff
path: root/app
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2016-10-15 16:43:52 +0200
committerEugen Rochko <eugen@zeonfederated.com>2016-10-15 16:46:15 +0200
commit7075cef8f99f715fbf77a67e45bbc1e7edcada42 (patch)
treee2db2fa465489effb8d19cb06b649bd990e18d56 /app
parent492a682e34d66dd3046ed08f7aee80fb5317f777 (diff)
Adding sort by node rank to follow suggestions and fallback to most influential users
Diffstat (limited to 'app')
-rw-r--r--app/models/follow_suggestion.rb43
1 files changed, 40 insertions, 3 deletions
diff --git a/app/models/follow_suggestion.rb b/app/models/follow_suggestion.rb
index 108a948a2..4f06db69c 100644
--- a/app/models/follow_suggestion.rb
+++ b/app/models/follow_suggestion.rb
@@ -1,10 +1,47 @@
 class FollowSuggestion
   def self.get(for_account_id, limit = 6)
     neo = Neography::Rest.new
-    account_ids = neo.execute_query('START a=node:account_index(Account={id}) MATCH (a)-[:follows]->(b)-[:follows]->(c) WHERE a <> c AND NOT (a)-[:follows]->(c) RETURN DISTINCT c.account_id', id: for_account_id)
-    Account.where(id: account_ids['data'].map(&:first) - Block.where(account_id: for_account_id).pluck(:target_account_id)).limit(limit) unless account_ids.empty?
+
+    query = <<END
+START a=node:account_index(Account={id})
+MATCH (a)-[:follows]->(b)-[:follows]->(c)
+WHERE a <> c
+AND NOT (a)-[:follows]->(c)
+RETURN DISTINCT c.account_id
+ORDER BY c.nodeRank
+LIMIT {limit}
+END
+
+    results = neo.execute_query(query, id: for_account_id, limit: limit)
+
+    return fallback(for_account_id, limit) if results.empty?
+
+    map_to_accounts(for_account_id, results)
   rescue Neography::NeographyError, Excon::Error::Socket => e
     Rails.logger.error e
-    []
+    return []
+  end
+
+  private
+
+  def self.fallback(for_account_id, limit)
+    neo     = Neography::Rest.new
+    query   = 'MATCH (a) WHERE a.account_id <> {id} RETURN a.account_id ORDER BY a.nodeRank DESC LIMIT {limit}'
+    results = neo.execute_query(query, id: for_account_id, limit: limit)
+
+    map_to_accounts(for_account_id, results)
+  rescue Neography::NeographyError, Excon::Error::Socket => e
+    Rails.logger.error e
+    return []
+  end
+
+  def self.map_to_accounts(for_account_id, results)
+    return [] if results.empty?
+
+    account_ids  = results['data'].map(&:first)
+    blocked_ids  = Block.where(account_id: for_account_id).pluck(:target_account_id)
+    accounts_map = Account.where(id: account_ids - blocked_ids).map { |a| [a.id, a] }.to_h
+
+    account_ids.map { |id| accounts_map[id] }.compact
   end
 end