Module: Noodall::Search::ClassMethods

Defined in:
lib/noodall/search.rb

Instance Method Summary collapse

Instance Method Details

#language(lang = 'en') ⇒ Object



25
26
27
# File 'lib/noodall/search.rb', line 25

def language(lang = 'en')
  @language ||= lang
end

#search(query, options = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/noodall/search.rb', line 33

def search(query, options = {})
  if options[:per_page] || options[:per_page]
    per_page      = options.delete(:per_page)
    page          = options.delete(:page)
  end
  plucky_query = query(options.reverse_merge(
    :order => 'relevance DESC'
  ))
  criteria = plucky_query.criteria.to_hash
  options = plucky_query.options.to_hash

  # Extract words from the query and clean up
  words = query.to_s.downcase.split(/\W/) - STOPWORDS
  words.reject!{|w| w.length < 3}

  # add stemmed words to the array of words
  words = stem(words) | words

  criteria.merge!( :_keywords => { :$in => words } )

  # The Search result
  search_result = collection.map_reduce(search_map(words), search_reduce, :query => criteria, :out => "#{self.collection_name}_search")

  # Add value to sort options because model is stored in the value key
  options[:sort].map! do |s,v|
    ["value.#{s}",v]
  end

  search_query = Plucky::Query.new(search_result, options)

  if per_page
    results = search_query.paginate(:per_page => per_page, :page => page)
  else
    results = search_query.all
  end
  #return results mappped to objects
  results.tap do |docs|
    docs.map! { |hash| load(hash['value']) }
  end
end

#search_finalizeObject



96
97
98
# File 'lib/noodall/search.rb', line 96

def search_finalize
  "function( key , values ){return values.model;}"
end

#search_map(words) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/noodall/search.rb', line 78

def search_map(words)
  #convert words into Regex OR
  q = words.map do |k|
    Regexp.escape(k)
  end.join("|")
  "function(){" +
    "this.relevance = this._keywords.filter(" +
    "function(z){" +
    "return String(z).match(/(#{q})/i);" +
    "}).length;" +
    "emit(this._id, this);" +
    "}"
end

#search_reduceObject



92
93
94
# File 'lib/noodall/search.rb', line 92

def search_reduce
  "function( key , values ){return values[0];}"
end

#searchable_keys(*keys) ⇒ Object



18
19
20
21
22
23
# File 'lib/noodall/search.rb', line 18

def searchable_keys(*keys)
  @searchable_keys ||= Set.new
  @searchable_keys += keys

  @searchable_keys
end

#stem(words) ⇒ Object



74
75
76
# File 'lib/noodall/search.rb', line 74

def stem(words)
  words.map { |word| stemmer.stem(word) }
end

#stemmerObject



29
30
31
# File 'lib/noodall/search.rb', line 29

def stemmer
  @stemmer ||= Lingua::Stemmer.new(:language => language)
end