parm530
9/25/2019 - 3:59 PM

Redis & Soulmate (Autocomplete)

Using Soulmate in Rails App

  • Used to implement an autocomplete feature
  • Add gem 'soulmate' to your GEMFILE and bundle install
  • Will install redis as a dependency
  • Need to add an after_save callback to your model object:
class Person
  after_save :load_into_soulmate
  
  def load_into_soulmate
    loader = Soulmate::Loader.new("person")
    loader.add("id" => id, "term" => name)
    # term will be the attribute you want to search for in autocomplete
  end
  
end
  • If the following error occurs: Redis::CommandError: ERR value is not a valid float

    • FIX: Add score: 1 in the loader.add() parameter hash
  • After that, run a task to update your model objects


Understanding how to structure the Redis DB

  • When using soulmate to populate the db:
Soulmate::Loader.new(db_name).add({
  "term" => "value of field that will be sesrched on",
  "id" => "record.id" if using ActiceRecord,
  "value" => "string representation what to return to frontend" 
})

Redis-Server

  • where you can write queries and obtain info about the redis db
  • run keys * to obtain all keys in this current redis db
  • Soulmate::Loader.new("person") will create the following keys:
    • soulmate-data:person: stores in a hash the attributes you added when you used loader.add
    • soulmate-index:person: stores a list of partial substrings of the term attribute
      • If a term was "dogsled", it would contain: "d", "do", "dog", ... "dogsled"

Useful Commands

  • keys *
  • keys soulmate-data:person *: retrieves all values in this key
  • keys soulmate-index:person:sub_string*: retrieves all values in the DB that contain this sub_string
  • hgetall soulmate-data:person
  • hget soulmate-data:person 1: get value with id = 1
  • select #: selects a db
  • dbsize: returns the number of keys in that db
  • Things to note:
    • Soulmate produces soulmate-index and soulmate-data keys
    • soulmate-index: is the collection of partial strings of the search term
    • soulmate-data: is the hash object formed when you produce the hash in the matches collection
  • Verify the rank of a key:
    • zscore soulmate-index:cat:f7f 1643: contains the key of the db as well as the id (should be the same id of the product) of the key
    • Test the score by hitting the search again for that item and see if the score increased

Deleting Data in Redis DB

  • Delete all keys from all Redis databases:
    • redis-cli FLUSHALL
  • Delete all keys of the currently selected Redis database:
    • redis-cli FLUSHDB
  • Delete all keys of the specified Redis database:
    • redis-cli -n <database_number> FLUSHDB