4

I'm iterating through data and dumping some to a Redis DB. Here's an example:

hmset id:1 username "bsmith1" department "accounting"

How can I increment the unique ID on the fly and then use that during the next hmset command? This seems like an obvious ask but I can't quite find the answer.

0

2 Answers 2

6

Use another key, a String, for storing the last ID. Before calling HMSET, call INCR on that key to obtain the next ID. Wrap the two commands in a MULTI/EXEC block or a Lua script to ensure the atomicity of the transaction.

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

Comments

0

Like Itamar mentions you can store your index/counter in a separate key. In this example I've chosen the name index for that key.

Python 3

KEY_INDEX = 'index'
r = redis.from_url(host)

def store_user(user):
  r.incr(KEY_INDEX, 1)  # If key doesn't exist it will get created
  index = r.get(KEY_INDEX).decode('utf-8')  # Decode from byte to string
  int_index = int(index)  # Convert from string to int
  result = r.set('user::%d' % int_index, user)
  ...

Note that user::<index> is an arbitrary key chosen by me. You can use whatever you want.

If you have multiple machines writing to the same DB you probably want to use pipelines.

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.