Searching:
back to the FAQ Index
How can I search in an Index?
Is it possible to search in more than just one Index at a time?
Yes, it is. Checkout the IndexReader class.
index = IndexReader.new( ["/path/to/index1", "/path/to/index2"] )
How can I sort the results?
By default, the results are sorted by their score. However, if you want to sort your results by any other indexed field, you can pass an array of sortfields to your query. The results will be sorted by the 1st array element, and if two results are equal, by the 2nd element, and so on..
include Ferret::Search
sort_fields = []
sort_fields << SortField.new(:created_at, :sort_type => :integer)
sort_fields << SortField.new(:title, :sort_type => :string)
INDEX.search_each( query, :sort => Sort.new(sort_fields) ) do |doc, score|
# Assuming, you are storing the field :title in the index
puts "Found doc #{doc} (#{INDEX[doc][:title]}) with a score of #{score}"
end
Search results can only be sorted by untokenized fields. If you want to sort results by a string field like a 'title', be sure to add the title twice, e.g. :title tokenized for searching and :title_sort untokenized for sorting.
I get incorrect results when searching for words like "or", "and", "the", "his", "her" etc. What's the problem?
Ferret's standard analyzer strips stop-words by default. Stop words are common words like "the" and "to" which generally aren't very useful when searching the index. If you want to be able to search for these words you need to modify your analyzer. You can switch stop-word filtering off as described here.
Also, be aware that AND, OR, and NOT (note the all-capitalization) are keywords in Ferret's query language so turning off stop-word filtering won't help if you do a search for the term "OR". If you need to do something like this (eg. searching for the state abbreviation for Oregon), you will need write a custom query parser which is beyond the scope of this FAQ.
