Reputation: 189
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
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.
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