【问题标题】:thinking-sphinx collect attributes of search resultthinking-sphinx 收集搜索结果的属性
【发布时间】:2014-04-29 12:51:54
【问题描述】:

如何获取搜索结果的属性集合?

I.E.

我搜索了Product有很多Category的模型:

class Product < ActiveRecord::Base
  has_many :categories

这是我的索引:

ThinkingSphinx::Index.define :product, with: :active_record do
  ###
  has category(:id), as: :direct_category_id

所以,我通过查询进行搜索

products = Product.search params[:query]
categories = Category.find(products.map(&:category_id)) # slow & bad & ugly

但是这种方法又慢又糟糕。有没有办法从搜索结果中获取所有属性而不是收集?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 thinking-sphinx


    【解决方案1】:
    search       = Product.search params[:query]
    search.context[:panes] << ThinkingSphinx::Panes::AttributesPane
    category_ids = search.collect { |product|
      product.sphinx_attributes['direct_category_id']
    }
    categories   = Category.find category_ids
    

    但是,请记住,如果您在控制台中运行此命令,则第一行会评估搜索请求,因为 IRB 会呈现结果。这意味着无法添加窗格...因此您需要在第一行的末尾添加 ; '' 或类似内容(同样:仅在 Rails 控制台中需要):

    search       = Product.search params[:query]; ''
    

    【讨论】:

    • 您的方法似乎只获得了前 20 条记录。我试过(在启用分页之前)search.size #=&gt; 20 & search.count #=&gt; 6396,对于#collect & #each 方法,只有 20 个产品。
    • Sphinx 对结果进行分页 - 没有办法解决这个问题,但您可以请求非常大的页面大小。如果您需要超过 1000 个,请阅读文档:pat.github.io/thinking-sphinx/…
    • 为什么我得到 20,而不是默认的 1000 值?
    • 我尝试粘贴 per_page 选项专门用于收集至少 1000 条记录的结果,但遇到了一些困难,例如急切加载巨大的数组和分页(之后 will_paginate 不起作用)。
    • 鉴于数据量很大,也许这不是获得所需数据结果的最佳方式?加载所有类别的目的是什么?
    【解决方案2】:

    好的。我自己解决了。解决方案使用facets

    首先,我们需要添加direct_category_id:

    has category(:id), as: :direct_category_id, facet: true
    

    之后,我们只需要使用

    category_ids = products.facets[:direct_category_id].keys
    categories = Category.where(id: category_ids)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多