【问题标题】:how do I speed up this ugly query?如何加快这个丑陋的查询?
【发布时间】:2013-10-30 16:26:38
【问题描述】:

我正在尝试向用户显示当前用户正在关注的个人资料中包含公司/技能/学校的其他用户。创建个人资料中具有此类属性的用户列表后,我想按与每个返回用户关联的相关公司/技能/学校的数量对其进行排序,以在列表顶部显示最相关的用户。

虽然这可行,但它非常丑陋并且可以预见的缓慢,我不知道从哪里开始清理它。一些指针将不胜感激。

def term_helper(terms,user)
  relevant_terms = []
  terms.each do |term|
    if user.positions.any? { |w| w.company.downcase.include?(term.downcase) rescue nil || w.industry.downcase.include?(term.downcase) rescue nil }
      relevant_terms << term
    end
    if user.educations.any? { |w| w.school.downcase.include?(term.downcase) rescue nil }
      relevant_terms << term
    end
    if user.held_skills.any? { |w| w.name.downcase.include?(term.downcase) rescue nil } 
      relevant_terms << term
    end
  end
  relevant_terms
end

def search
  if current_user
    followed_companies = current_user.followed_companies.pluck(:name)
    followed_skills = current_user.followed_skills.pluck(:name)
    @terms = (followed_companies + followed_skills).uniq
    full_list = []
    full_list_with_terms = {}
    users = []
    @terms.each do |term|
      full_list += User.text_search(term).uniq
      # using pg_search gem here
    end
    full_list.each_with_index do |user,index|
      terms = term_helper(@terms,user)
      full_list_with_terms[index] = {"user" => user, "term_count" => terms.count}
    end
    full_list_with_terms = full_list_with_terms.sort_by {|el| el[1]["term_count"]}
    full_list_with_terms.each do |el|
      users << el[1]["user"]
    end
    @matches = users.uniq.reverse.paginate(:page => params[:page], :per_page => 10)
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby algorithm search


    【解决方案1】:

    一些提示:

    1. User.text_search 方法有什么作用?您使用的是全文搜索引擎吗?如果是这样,您应该构建一个搜索查询(term1 OR term2 OR term3 等),而不是为每个字词单独搜索。

    2. User.text_search 方法中,您是否正在创建数据库连接以预获取教育、职位、hold_skills 及其公司、学校和技能名称?这将大大减少数据库查询的数量。

    3. 考虑denormalizing 您的数据库架构。也许您可以将company_name 列添加到positions 表,将school_name 列添加到educations,将skill_name 列添加到held_skills 表。这将大大简化您的查询并提高性能。

    这些只是一些起点。

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 2019-02-06
      • 2017-12-23
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多