2020年4月26日 星期日

[Redis] Cache search keywords and result


 Redis   Search caching 





Introduction


This is an example of using Redis to cache the search keywords and result.

For example, we have 2 fields: “Name”(partial-match) and “From”, and we want to cache the user’s search keywords and  result in order to response the cached result for the same search keywords at the next time.





We will use the following Redis’s Data Types:

Data Type
Description
Sample
Key
Value
Strings
Key: GUID
Value: Search result
1cdda6577b644a2f918ce0daceb97bd9
[{“Name“:”Stan”, “From“: “TW“}, {“Name“:”Stanley”, “From“: “HK“}]
Sets
Key: A search’s field and keyword
Value: The search result’s Redis key
Name:Stan
1cdda6577b644a2f918ce0daceb97bd9


The following search scenarios will show what will be stores in Redis.

When user search with Name: “Stan”, and the result will be cached in key X:

Data Type
Key
Value
Strings
X (X is a GUID)
[{“Name“:”Stan”, “From“: “TW“}, {“Name“:”Stanley”, “From“: “HK“}]
Sets
Name:Stan
X
Sets
From:null
X



When user search with Name: “Mary”, and the result will be cached in key Y:

Data Type
Key
Value
Strings
X
[{“Name“:”Stan”, “From“: “TW“}, {“Name“:”Stanley”, “From“: “HK“}]
Strings
Y
[{“Name“:”Mary”, “From“: “TW“}]
Sets
Name:Stan
X
Sets
Name:Mary
Y
Sets
From:null
X, Y


When user search with From: “JP”, and the result will be cached in key Z:

Data Type
Key
Value
Strings
X
[{“Name“:”Stan”, “From“: “TW“}, {“Name“:”Stanley”, “From“: “HK“}]
Strings
Y
[{“Name“:”Mary”, “From“: “TW“}]
Strings
Z
[{“Name“:”Jack”, “From“: “JP“}]
Sets
Name:Stan
X
Sets
Name:Mary
Y
Sets
Name:null
Z
Sets
From:JP
Z
Sets
From:null
X, Y


When user search with Name: “Stan” + From: “TW”, and the result will be cached in key W:

Data Type
Key
Value
Strings
X
[{“Name“:”Stan”, “From“: “TW“}, {“Name“:”Stanley”, “From“: “HK“}]
Strings
Y
[{“Name“:”Mary”, “From“: “TW“}]
Strings
Z
[{“Name“:”Jack”, “From“: “JP“}]
Strings
W
[{“Name“:”Stan”, “From“: “TW“}]
Sets
Name:Stan
X, W
Sets
Name:Mary
Y
Sets
Name:null
Z
Sets
From:JP
Z
Sets
From:TW
W
Sets
From:null
X, Y


Now next time a user searches with Name: “Stan” + From: “TW”, we will intersects the sets by the 2 keys:

l   Name:Stan
l   From:TW

That will get W, and we can return the result from key: W. The redis-cli command is as following,

$ SINTER Name:Stan From:TW
(string) W
$ MGET W
(string) [{“Name“:”Stan”, “From“: “TW“}]



Another search example with only name keyword: Name: “Mary”:

$ SINTER Name:Mary From:null
(string) Y
$ MGET Y
(string) [{“Name“:”Mary”, “From“: “TW“}]





Reference







沒有留言:

張貼留言