Class: Soulmate::Matcher

Inherits:
Base
  • Object
show all
Defined in:
lib/soulmate/matcher.rb

Instance Attribute Summary

Attributes inherited from Base

#type

Instance Method Summary collapse

Methods inherited from Base

#base, #cachebase, #database, #initialize

Methods included from Helpers

#normalize, #prefixes_for_phrase

Constructor Details

This class inherits a constructor from Soulmate::Base

Instance Method Details

#matches_for_term(term, options = {}) ⇒ Object


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/soulmate/matcher.rb', line 5

def matches_for_term(term, options = {})
  options = { :limit => 5, :cache => true, :offset => 0 }.merge(options)
  
  words = normalize(term).split(' ').reject do |w|
    w.size < Soulmate.min_complete or Soulmate.stop_words.include?(w)
  end.sort

  return [] if words.empty?

  cachekey = "#{cachebase}:" + words.join('|')

  if !options[:cache] || !Soulmate.redis.exists(cachekey) || Soulmate.redis.exists(cachekey) == 0
    interkeys = words.map { |w| "#{base}:#{w}" }
    Soulmate.redis.zinterstore(cachekey, interkeys)
    Soulmate.redis.expire(cachekey, 10 * 60) # expire after 10 minutes
  end

  ids = Soulmate.redis.zrevrange(cachekey, options[:offset], options[:limit] - 1)
  if ids.size > 0
    results = Soulmate.redis.hmget(database, *ids)
    results = results.reject{ |r| r.nil? } # handle cached results for ids which have since been deleted
    results.map { |r| MultiJson.decode(r) }
  else
    []
  end
end