Indexing and ordering by dynamic field with sunspot

徘徊边缘 提交于 2019-12-25 06:54:56

问题


So I have many items that can be part of many different pages. So here is the simplified models:

class Page
  #we just need the id for this question
end

class Item
  embeds_many :page_usages
end 

class PageUsage
  field :position, :default => 0
  embedded_in :item
  belongs_to :page  
end

So the page_usage is holding the position of the items on every page. I want to put that into solr so it can pull up the right items and in the right order for me.

I've looked into dynamic fields and ended up with something like this but not really sure. I want the field to basically be the page id pointing to the position of the item:

searchable do
 dynamic_integer :page_usages do
   page_usages.inject({}) do |hash, page_usage|
     hash.merge(page_usage.page_id => page_usage.position)
   end
 end
end

And in my controller I have something like this:

Item.search do
  dynamic :page_usages do
    #i have @page.id but not sure how to get all items with the @page.id
  end
end

I need something that will check if the item exist on the page and find out how to use order_by with the position. Is this possible this way or do I have to find another solution?


回答1:


Solved it after lots of trial and error.

searchable do
 dynamic_integer :page_usages do
   page_usages.inject({}) do |hash, page_usage|
     hash.merge( ("page" + page_usage.page_id.to_s).to_sym => page_usage.position)
   end
 end
end

So I first had to store the key as a symbol which is important. But the problem I ran into was that the symbol couldn't have quotes in it. So if you call to_sym on the id, it would look something like :"123456789" which will give you a "wrong constant name" error later on. So I threw on a string before the id to create the new symbol which looks like :page123456789.

Next step was to create the search block:

Item.search do
  dynamic :page_usages do
    with ("page" + page.id.to_s).to_sym ).greater_than(-1)
    order_by(("page" + page.id.to_s).to_sym, :asc)
  end
end

By using that page id, I was able to pull up all the right items in the right order. I used greater than -1 because by default my positions start at 0 and goes up from there.



来源:https://stackoverflow.com/questions/21738522/indexing-and-ordering-by-dynamic-field-with-sunspot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!