redis.lpush a number of items
Asked Answered
S

2

9

In my node.js script I have an array of strings, and I want to LPUSH these strings into a Redis queue. I tried:

var redis = require('redis').createClient();
redis.lpush('queue', ['1', '2', '3'])

which results in a single string being pushed:

redis 127.0.0.1:6379> lrange queue 0 -1
1) "1,2,3"

Redis supports multiple values in LPUSH command, I am looking for help on utilizing this functionality. I am not asking how to loop over my array and push each item separately. :)

EDIT:

I know if I do this:

redis.lpush('queue', '1', '2', '3')

I get what I expect, but in my real application the array is generated at run time, and I do not know its contents.

Sobranje answered 7/8, 2013 at 4:24 Comment(0)
I
8

This appears to be a known issue/common request

One of the suggested workarounds is to use send_command directly

You might also try this (haven't tried this myself):

myvalues.unshift('queue');
redis.lpush.apply(redis, myvalues);
Interjoin answered 7/8, 2013 at 4:36 Comment(2)
thanks. both send_command and apply work, except for unshift returns the new length, so I had to do it as a separate statement.Sobranje
>= 2.4: Accepts multiple value arguments. In Redis versions older than 2.4 it was possible to push a single value per command. docHoahoactzin
E
25

This is now possible with es6 spread syntax. An array of any size will be spread out as the arguments to the function.

redis.lpush('queue', ...arrayOfValues)
Endorse answered 30/12, 2017 at 1:41 Comment(2)
You don't even need to use spread syntax anymore. Just passing an array will suffice. P.S. This answer is more up to date than the accepted answer.Mcgary
This should be the correct answer rather than the accepted one.Implement
I
8

This appears to be a known issue/common request

One of the suggested workarounds is to use send_command directly

You might also try this (haven't tried this myself):

myvalues.unshift('queue');
redis.lpush.apply(redis, myvalues);
Interjoin answered 7/8, 2013 at 4:36 Comment(2)
thanks. both send_command and apply work, except for unshift returns the new length, so I had to do it as a separate statement.Sobranje
>= 2.4: Accepts multiple value arguments. In Redis versions older than 2.4 it was possible to push a single value per command. docHoahoactzin

© 2022 - 2024 — McMap. All rights reserved.