开发者

Rails text search using array of keywords

I have a Post model that consists of title and content.

I want to implement a text search on that model that would split the user's submitted form into an array and then search for th开发者_Go百科ese keywords on both the title and the content.

Example

If the title is : Today its a nice day
and the content: Today I woke up at 7am and..

I would like this to be returned if the user uses the term: "day woke 7am"

I will not prefer to use any Full Text Search as this is bit pricy on heroku where my app is hosted.

What are the best practiced to implement a sql-search like this? Is it possible to apply some weighting on my results? Can anyone show me any code snippets?


I would the code you write into your Post model. I'd make a method that would

  1. accept the search string as a parameter
  2. downcase the search string and turn it into an array 2a. I would consider taking out all the 1- or 2-character words
  3. then i'd iterate through the posts table. As I go through each line, I'd -- combine the title and body, downcase the combination, and turn it into an array -- perform the array - array operation, and save each post where the result is an empty array
  4. return the resulting posts

This is not tested -- I don't have a model handy like your Post model - but hopefully you can get what I'm doing here:

def charlie_search(search_string) output_array = [] Post.all.each do |p| output_array.push(p.id) if search_string.downcase.split - (p.title.downcase.split + p.description.downcase.split) == [] end Post.find(output_array) end

I don't understand what is expensive in your situation.

You could just put a Google site search box on your site (I think Google still has that service), and let Google index all your pages, then when someone does a search, they would get Google-type search listings for just your site.

Anyway, finding matches is something that a search index like Google is really good at, and I think that's what the other answers were driving at -- using a search index to deliver results.


Try Sunspot for Solr

http://github.com/outoftime/sunspot

Edited:

Following might help you.

Articles.find(:all, :conditions => ["match(title,body) against (?)", "Databases"] )

Here title and body are the database columns and keyword is 'Databases'. For more options check match-against in mysql.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html


One super simple way would be to use Ruby's Array "-" method:

p 'got one' if 'day woke 7am'.downcase.split(' ') - 'Today its a nice day Today I woke up at 7am and'.downcase.split(' ') == []

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜