【问题标题】:Searchkick get all results when using paginationSearchkick 使用分页时获取所有结果
【发布时间】:2020-08-25 22:08:00
【问题描述】:

我使用 searchkick 对产品进行以下搜索查询:

def index
  @filter = params[:filter].blank? ? nil : Search.find(params[:filter])

  if @filter.present?
      @products = @filter.products(set_order_column(@sort), @direction, params[:page], @per_page)
  else
      query = @query.presence || "*"

      @products = Product.search(
        query, 
        where: {
          active: true
        }, 
        page: params[:page], 
        per_page: @per_page, 
        order: [{
          "#{set_order_column(@sort)}" => "#{@direction}"
        }],
        misspellings: { distance: 2 },
        fields: fields)
  end

  @filter_product_ids = @products.map(&:id)
end

有一个变量 filter_product_ids 我需要存储所有结果而不是@per_page 过滤的结果。有可能这样做吗?现在,只有结果@per_page 的结果。

在不分页的情况下获得所有结果的目标是获取所有用于网站上各种产品分类的产品的 uniq 值。

感谢您的任何提示,米罗斯拉夫

【问题讨论】:

    标签: ruby-on-rails searchkick


    【解决方案1】:

    我的解决方案是把它放在它自己的类(服务类)中,然后

    class ProductFilter
      attr_reader :search_params, :search_query, :pagination_params
    
      def initialize(search_params, search_query, pagination_params)
        @search_params = search_params
        @search_query = search_query
        @pagination_params = pagination_params
      end
    
      # Will return all records from searchkick, unpaginated
      def filtered_products
        Product.search(search_query, search_param_stuff)
      end
    
      # Will return all filtered_products & then paginate on that object
      def paginated_products
        filtered_products.records.paginate(pagination_params)
      end
    
      private
      def search_param_stuff
        search_params
      end
    end
    

    无论如何,searchkick 的分页方法实际上适用于 searchkick 记录对象,因此您可以在一种方法中拉取 ES 查询(不传递分页参数),然后在 filtered_products.records 上分页。

    【讨论】:

      【解决方案2】:

      删除

      params[:page], @per_page
      

      和

      page: params[:page], 
      per_page: @per_page,
      

      来自您的代码。

      【讨论】:

      • 我仍然需要对结果/页面进行分页,但同时我需要访问所有记录的数组(无需分页)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2018-02-07
      • 2015-11-15
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多