How to fetch only selected column in solr rails

448 views Asked by At

I am using rails with solr

I want to search on user and my user table have 12 field my mode is User

name,city,state,image,comment,status,note etc ...

in my user model

searchable do
    text :name, :city
end

when I do search using

@search = User.search do
    fulltext params[:search]
end
@users = @search.results

This will return me all field from database but I only wont three field name,city,state how can I get only three field using solr search. how can achieve this ?

3

There are 3 answers

0
coorasse On

I'm not really sure why you would do that but anyway you can use @search.hits instead of @search.results and load whatever you want using ids.

0
henadzit On

When you call @search.results, sunspot loads all matched records from your SQL database.

If you want to avoid hitting your SQL database, you can store the needed fields in Solr. You need to update your searchable definition

searchable do
  text :name, stored: true
  text :city, stored: true
end

and then reindex your model User.reindex. Then you can query your data like

@search = User.search do
  fulltext params[:search]
end
@users = @search.hits.each do |hit|
  puts "#{hit.stored(:name)} #{hit.stored(:city)}"
end
0
Osama Hashem On

You can do it in Schema

<field name="name" type="string" indexed="false" stored="true"/>
<field name="city" type="string" indexed="false" stored="true"/>
<field name="state" type="string" indexed="false" stored="true"/>

<field name="copiedfield" type="string" indexed="true" stored="false" multiValued="true"/>

Now all the field from you want to search, set source value of use copyField tag to copy from source field to dest Example Schema :

<copyField source="name" dest="copiedfield"/>
<copyField source="city" dest="copiedfield"/>
<copyField source="state" dest="copiedfield"/>

now you can search only by copiedfield

EDIT

you can do another way be searching in every column alone but this way is slow than copyField