如何使用Redis批量插入?

19

我读过redis.io提供的mass-insert,但是它让我感到困惑。我尝试创建一个文件,然后使用"cat data.txt | redis-cli --pipe"来插入:

    SET Key0 Value0
    SET Key1 Value1
    SET Key2 Value3

然后我收到了这个:
    All data transferred. Waiting for the last reply...
    ERR wrong number of arguments for 'set' command
    ERR unknown command '$4'
    ERR wrong number of arguments for 'echo' command
    ERR unknown command '$20'

我也尝试过
    *3<cr><lf>
    $3<cr><lf>
    SET<cr><lf>
    $3<cr><lf>
    key<cr><lf>
    $5<cr><lf>
    value<cr><lf>

然后我收到了这个错误信息:ERR Protocol error: invalid multi bulk length

这真的让我感到困惑。有人能给我一个简单的例子吗?非常感谢。

3个回答

8

这里是:

echo -n '*3\r\n$3\r\nset\r\n$3\r\nkey\r\n$5\r\nvalue\r\n' | ./redis-cli --pipe
All data transferred. Waiting for the last reply...
Last reply received from server.
errors: 0, replies: 1

你遇到的问题可能来自于回车换行分隔符。你可以使用hexdump -C命令来检查这个点:

echo -n '*3\r\n$3\r\nset\r\n$3\r\nkey\r\n$5\r\nvalue\r\n' | hexdump -C
00000000  2a 33 0d 0a 24 33 0d 0a  73 65 74 0d 0a 24 33 0d  |*3..$3..set..$3.|
00000010  0a 6b 65 79 0a 0d 24 35  0d 0a 76 61 6c 75 65 0d  |.key..$5..value.|
00000020  0a                                                |.|
00000021

此外,您可能需要检查目标是否为最新的Redis实例,而不是1-2版本之前的实例(不支持“统一协议”)。
注意:上述行在zsh中正常工作。如果您使用bash,则需要在引号前添加$以触发ANSI-C引用。
echo -n $'*3\r\n$3\r\nset\r\n$3\r\nkey\r\n$5\r\nvalue\r\n' | hexdump -C

我使用的是2.4.14版本。它支持该协议。我得到了以下内容:$ echo -n '*3\r\n$3\r\nset\r\n$3\r\nkey\n\r$5\r\nvalue\r\n' | ./src/redis-cli --pipe 所有数据已传输。等待最后一个回复... ERR 协议错误:无效的多批量长度。 - wyp
对于hexdump -C,我得到的是"|*3\r\n$3\r\nset|",而不是|*3..$3..set..$3.|。谢谢你的回答。 - wyp
我正在使用Macbook电脑。它是Bash。 - wyp
不,你只需要找到如何在OSX shell中生成正确的字符序列(即cr + lf = 0d0a in hex)。 - Didier Spezia
我猜如果你启动echo -n '*...\n' > data.txt ; cat data.txt | redis-cli --pipe,它肯定能工作。 - Didier Spezia
显示剩余3条评论

7
你可以这样做:
echo -e "$(cat data.txt)" | redis-cli --pipe

我希望能为您提供帮助!

4
我能够使用“SET Key0 Value0”格式进行工作。
请查看https://dev59.com/N2Ei5IYBdhLWcg3w4Pnr#30511742 回复是关于“LPUSH”命令的。它也可以与“SET”一起正常使用。
总结一下,对参数加上双引号。
SET "mykey" "myval"

使用 unix2dos 命令将文件格式从 Unix 转换为 Windows 格式:

unix2dos myfile.txt

然后使用以下命令进行导入:

cat myfile.txt | src/redis-cli --pipe

这对我很有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接