1

I am trying to add multiple values to a hash in Redis using hmset.

Example :

hmset test1 name abc lastname B age 20

Next time when I try to add different values to the same hash key fields, it is replacing them with the existing value.

Is it possible to add multiple values to the same field in Redis using scala or nodejs?

Actual result

hmset test1 name abc lastname B age 20 
hmset test1 name aa lastname D age 21
hgetall test1
  1. "name"
  2. "aa"
  3. "lastname"
  4. "BJ"
  5. "age"
  6. "20"

Expected result

hmset test1 name abc lastname B age 20 
hmset test1 name aa lastname D age 21
hgetall test1
  1. "name"
  2. "abc"
  3. "aa"
  4. "lastname"
  5. "B"
  6. "D"
  7. "age"
  8. "20"
  9. "21"

3 Answers 3

1

Each field in the Hash has a single String value associated with it, and you can only replace the value with a new one.

It is possible that the OP's use case can be accommodated with the Stream data structure, as it appears that the need is to keep an historical log of the changes.

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

Comments

0

Since Redis 4.0, HMSET method was deprecated. You should use HSET method/command instead of HMSET.

Below Code Node.JS Syntax

const setHashBook = await client.hSet("books",
    {
        book1: 'Clean Code', writer1: 'Robert C. Martin',
        book2: 'Refactoring', writer2: 'Martin Fowler',
    }
);

And below code is Redis Syntax.

HSET books book3 'GRPC Go Microservice' writer3 'Huseyin Babal' book4 'Redis Essentials' writer4 'Hugo Lopes'

If i answer your question, This command overwrites the values of specified fields that exist in the hash. If key doesn't exist, a new key holding a hash is created.

Because a Hash is a mapping of a String to a String.

Comments

0

We can you multi(),hSet() and exce() to set multiple key:values to hash Simple Nodejs code

function addValues(key,fields,values){
  const multi=redisClient.multi();
  for(let i=0;i<fields.length;i++){
    multi.hSet(key,fields[i],values[i]);
  }
  multi.exec((err,result)=>{
      if(err)
        console.log(err);
      else
        console.log(result)
  });
}

Comments

Your Answer

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