Neil
Neil

Reputation: 189

Using Redis Hashes to store question/answer pairs

An application has a MySQL database containing a table of Users. Each User has it's own Redis Hash. Each User-owned Redis Hash contains key/value pairs of question/answer strings. For example (in Ruby):

user = User.find(1)
question = "What colour is the sky?"
answer = "Blue"
user_hash = Redis::HashKey.new(user.id)
user_hash[question] = answer
user_hash[question] # returns answer

Now the User needs the ability to store multiple answers per question, for example:

question = "What colour is the sky?"
answers = ["Blue", "Grey", "Red"]

Also the application will perform methods on groups of questions/answers scoped through each User Hash, such as searching for User question strings containing certain words.

1) Is the Redis Hash the appropriate data type for the application at this point and, if so, 2) what is the best way to handle question/answer pairs with multiple answers?

Upvotes: 2

Views: 1010

Answers (1)

Sripathi Krishnan
Sripathi Krishnan

Reputation: 31528

You should think of these as 3 Objects - User, Question and Answer. Then, the relation between them becomes simple. User has Questions, Question has Answers.

Now, it is easy to model this in Redis.

  • The objects User, Question and Answer are stored in a hash
  • Question will have fields like id, text, userid, date_asked, date_modified and so on
  • Answer will have fields like id, text, userid, questionid

Then you need to store answers for a question. Create a Redis list with key question:$id:answers. This will be a list of answer ids.

To search on the basis of keywords, you should create a Redis set for each keyword. In this Set, store ids for questions that contain this word.

For example, sadd tag:java 123 232 4231 indicates that questions 123, 232 and 4231 have java in them. Similarly, add such a set for each keyword.

Then, to filter questions that contain java and redis, just do a set intersection on tag:java and tag:redis.

Upvotes: 2

Related Questions