I'm trying to provide a text search to find cities, based on their name and the name of the country they belong to.
For instance, I want to return Milan, Italy
for a search with the terms mil ita
, or also Los Angeles, United States
for a search on los ang uni
.
These are the current models I have (validations omitted):
class City < ActiveRecord::Base
belongs_to :country
searchable do
text :name
text :country do
country.name
end
end
end
and
class Country < ActiveRecord::Base
end
This is the relevant part of my solr schema.xml
file:
<fieldtype class="solr.TextField" positionIncrementGap="100" name="text">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StandardFilterFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
<!--<filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>-->
<filter class="solr.ISOLatin1AccentFilterFactory"/>
<filter class="solr.TrimFilterFactory" />
<filter class="solr.EdgeNGramFilterFactory"
minGramSize="3"
maxGramSize="30"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StandardFilterFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
<!--<filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>-->
<filter class="solr.ISOLatin1AccentFilterFactory"/>
<filter class="solr.TrimFilterFactory" />
</analyzer>
</fieldtype>
I'm performing a search in a controller with:
search = City.search do
fulltext params[:q]
paginate page: 1, per_page: 10
end
What happens here, is if I search for mil
I will get Milan, Italy
as a result, but searching for mil ita
will return nothing.
Any ideas?
Thank you in advance,
r.
Found a solution, I thought I'd share.
All you need is to build a 'custom field' with all the text that you want to enable search on, like this (in the City model):
searchable do
text :composite_name do
"#{name} #{country.name}"
end
end
This works.
r.