0

I'm very much new to Redis Cache. The following is my Json string which contains the data.

Code

[
{
    "ResourceKey": "Members",
    "Language": 1,
    "ClientId": 1,
    "ResourceValue": "Members"
},
{
    "ResourceKey": "Members",
    "Language": 2,
    "ClientId": 1,
    "ResourceValue": "会员"
}
]

What I am trying to achieve is that using ResourceKey, LanguageId, ClientId should form a kind of composite key in Redis to retrieve the ResourceValue field.

I have tried to store Json string as it is but it's very difficult to retrieve 1 particular data as I need to deserialize the whole string then get the single value.

Code

resKeyValue = JsonConvert.DeserializeObject<List<ResourceViewModel>>(readTask.Result);
resKeyValue = resKeyValue.Where(x => x.language == iLanguageId && x.clientid == iClientId).ToList();

Code

var db = _redis.GetDatabase();
var addedItems = new List<KeyValuePair<RedisKey, RedisValue>>();
if (!await db.KeyExistsAsync("resourceList"))
{
   addedItems.Add(new KeyValuePair<RedisKey, RedisValue>("resourceList", JsonConvert.SerializeObject(resItem)));
   await db.StringSetAsync(addedItems.ToArray());
   return Ok("Resources Added Successfully.");
}

I was looking into Hash but NOT able to visualize how to store composite key into Redis. Please help to suggest.

2
  • can you share the code which saves the value to redis? Commented Sep 10, 2021 at 5:53
  • @Chetan I updated my code Commented Sep 10, 2021 at 6:00

1 Answer 1

0

Since you are only interested in ResourceValue you can try to concatenate all fields to create a composite key.

For instance

set myCompositeKey:Members:1:1 Members
set myCompositeKey:Members:1:2 会员
get myCompositeKey:Members:1:1
"Members"

get myCompositeKey:Members:1:2
"会员"

Prefix myCompositeKey can be used to group all keys for that use case or schema. But it is really up to you.

Using this approach we do not use hash data type

Just in case, you can read more about redis keys here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.