Jim
Jim

Reputation: 11379

How would you sort an array in Ruby based off of a formula (e.g. search ranking)?

So, I'm building quick and dirty search functionality in my first rails app. I'm doing a query and returning a list of objects. e.g.

@articles = Article.find_by_sql("select * from article where title like "%test%" or title like "%foobar%")

So, the articles collection will return a lot of data, some of it matching my search terms better than others. I want to sort the array so that the items that match are presented first.

Here's the conceptual pseudo code I'm trying to implement.

for each article in @articles
    calculate the article score based on how many times the search terms appear
sort the array of articles based on the score

("score" is not part of the article object.)

Any ideas on how this can be sorted?

Upvotes: 1

Views: 396

Answers (2)

Jeff Swensen
Jeff Swensen

Reputation: 3573

Depending on what database you're using it might be more efficient to complete the ranking there. For instance, in MySQL you could you Natural Language Full Text Search:

http://dev.mysql.com/doc/refman/5.1/en/fulltext-natural-language.html

By default or with the IN NATURAL LANGUAGE MODE modifier, the MATCH() function performs a natural language search for a string against a text collection. A collection is a set of one or more columns included in a FULLTEXT index. The search string is given as the argument to AGAINST(). For each row in the table, MATCH() returns a relevance value; that is, a similarity measure between the search string and the text in that row in the columns named in the MATCH() list.

Upvotes: 1

James
James

Reputation: 5403

If all else fails you can do:

@articles.sort! {|x,y| search_fitness_function(y) <=> search_fitness_function(x)}

Upvotes: 2

Related Questions