小编典典

redis-大量插入和计数器

redis

这是我在stackoverflow上遇到的第一个问题。亲爱的社区,非常感谢您的综合知识和专业知识!

我是Redis的新手,所以请耐心等待,因为我敢肯定有一个简单的解决方案。

redis-server --version

=> Redis服务器v = 2.6.14 sha = 00000000:0 malloc = libc位= 64

redis-cli --version

=> redis-cli 2.6.14

我已阅读“如何使用Redis大容量插入?”如何使用Redis大容量插入?
我在Google上搜索并阅读了很多关于Redis INCR功能的赞美。但是我并不真正理解所有内容,并且它也无济于事-仅在内部进行。

我的目标:我想将’n’文本行导入redis,然后以完全相同的顺序检索它们。

我为每一行设置一个唯一的键,例如key:1,key:2,key:3等。通过使用递增计数器作为键的一部分,我以后可以按存储它们的相同顺序检索这些行。在Redis中。


现在(不使用redis大量插入),我可以通过使用awk脚本生成redis-cli调用来轻松解决此问题,例如:

cat data.txt | awk -f myscript.awk | bash

“ data.txt”看起来像这样:
这是第一行。
这是更长的第二行。


“ myscript.awk”看起来像这样:

#!/usr/bin/awk -f

### This section is being applied before any line is read:
BEGIN {
# Set counter initially to Zero
print "redis-cli SET counter 0"
}

### This section is being applied per line read into awk:
{
# Increase counter by One
print "redis-cli INCR counter"
# Read current counter from redis into an variable
print "MYCOUNTER=`redis-cli GET counter`"
# Use this variable as counter for the key
print "redis-cli SET key:$MYCOUNTER \"" $0 "\""
# Retrive stored value from redis for illustration
print "redis-cli GET key:$MYCOUNTER"
}

“ cat data.txt | awk -f myscript.awk | bash”的输出为:

OK
(integer) 1
OK
"This is the first line."
(integer) 2
OK
"This here is the much longer second line."

所以一切都很好。


但是,我不想使用每个导入行两次调用“ redis-cli”,而是要使用redis的“大量插入”功能。在这里我需要您的帮助:

我将如何仅在redis中做这样的事情?

SET counter 0
=> OK
INCR counter
=> (integer) 1
GET counter
=> "1"
SET KEY:{counter} "Content of line 1"
=> OK
INCR counter
=> (integer) 2
GET counter
=> "2"
SET KEY:{counter} "Different content of line 2"
=> OK

等等等

“获取计数器”行仅用于说明。

任何帮助表示赞赏。再次感谢 !

伯尼


阅读 460

收藏
2020-06-20

共1个答案

小编典典

为此使用列表。没有理由为每一行使用新的密钥。所有列表命令都在这里,但是您想要的是RPUSH。您可以在同一行中一次推送多个值,因此您只需执行以下操作:

RPUSH some_key line1 line2 ... lineN

然后检索:

LRANGE some_key 0 -1

快捷方便!

2020-06-20