Ruby Forum Ferret > sorting with booleans

Posted by Caspar Bl (ghost)
on 20.08.2006 16:07
Hi i have a column in  my ferret model called sponsored. It is a boolean 
and i want to order the results by sponsored and date registered. At the 
moment it is not managing to sort the booleans.
I tried declaring this in my model but it seems to have had no effect.

		def false.<=>(o) o ? -1 : 0 end
		def true.<=>(o)  !o ? 1 : 0 end
I'm using the acts_as_ferret plugin.
below is the relevent code that i'm currently using.


sort_fields = []
sort_fields << Ferret::Search::SortField.new("sponsorerd")
sort_fields << Ferret::Search::SortField.new("ferret_date_registered", 
:reverse => :true)

results = VoObject.find_by_contents(query,:first_doc=>page, :num_docs=> 
20,:sort =>sort_fields)

Thanks in advance for any replies.

regards
c
Posted by David Balmain (Guest)
on 22.08.2006 20:21
(Received via mailing list)
On 8/20/06, Caspar Bl <waspfactory@gmail.com> wrote:
>
> regards
> c

Hi Casper,

Firstly, if you are not declaring the field's type, you may as well
specify the sort like this;

    results = VoObject.find_by_contents(query,
                                        :first_doc=>page,
                                        :num_docs=> 20,
                                        :sort => [:sponsored,
:ferret_date_registered])

Also, please use symbols for your field names. Future versions of
Ferret will expect this and it is much more efficient for the ruby
interpreter.

Secondly, the way the sort works is by comparing values in the index.
The boolean field will probably get added to the index as "true" or
"false" so "false" should come first in a sort (it's alphabetical).
You might want to define a ferret_sponsored field like this;

    def ferret_sponsored
        sponsored ? 1 : 0
    end

Sorting by numbers is more efficient than strings. Also, 1 and 0 take
up a quarter of the space in the index.

Same goes with dates. The best way to store dates is in the format
YYYYMMDD. Today for example is 20060823. I'm guessing you are probably
already doing this though since you have the :ferret_date_registered
field.

Just remember that the sorting is done within the Ferret c code, not in 
Ruby.

Hop that helps,
Dave
Posted by Caspar (Guest)
on 23.08.2006 21:18
Hi dave,

this works nicely except

results2 = VoObject.find_by_contents(query,:num_docs=> 20000,:sort => 
[:sponsored,:ferret_date_registered])

I can't work out where to put the reverse part in?
I would like both fields to be reverersed and sponsored to be the 
primary sort field.

Thanks in advance
regards,
Caspar