jjzjj

python - 写入 3,795,790,711 唯一键 :value pairs to redis

coder 2023-07-18 原文

我想处理一个相当大的语料库。它的名称是 web 1T-gram。它拥有大约 3 万亿个代币。这是我第一次使用 redis,我正在尝试编写所有键:值对,但它花费的时间太长了。我的最终目标是使用多个 redis 实例来存储语料库,但目前,我坚持将其全部写在一个实例上。

我不确定,但有什么方法可以加快写作过程吗?到目前为止,我只在一台有 64G RAM 的机器上写一个 redis 实例。我在想是否有一些缓存大小设置可以最大化以用于 redis。或者那些线路上的东西?

谢谢。

为了引用,我写了下面的代码:

import gzip
import redis
import sys
import os
import time
import gzip
r = redis.StrictRedis(host='localhost',port=6379,db=0)
startTime = time.time()
for l in os.listdir(sys.argv[1]):
        infile = gzip.open(os.path.join(sys.argv[1],l),'rb')
        print l
        for line in infile:
                parts = line.split('\t')
                #print parts[0],' ',parts[1]
                r.set(parts[0],int(parts[1].rstrip('\n')))
r.bgsave()
print time.time() - startTime, ' seconds '

更新:

我读到了有关批量插入的内容,并一直在尝试这样做,但也一直失败。这是脚本中的更改:

def gen_redis_proto(*args):
    proto = ''
    proto += '*' + str(len(args)) + '\r\n'
    for arg in args:
        proto += '$' + str(len(arg)) + '\r\n'
        proto += str(arg) + '\r\n'
    return proto
import sys
import os
import gzip
outputFile = open(sys.argv[2],'w')



for l in os.listdir(sys.argv[1]):
        infile = gzip.open(os.path.join(sys.argv[1],l),'rb')
        for line in infile:
                parts = line.split('\t')
                key = parts[0]
                value = parts[1].rstrip('\n')
                #outputFile.write(gen_redis_proto('SET',key,value))
                print gen_redis_proto('SET',key,value)

        infile.close()
        print 'done with file ',l

生成方法归功于 github 用户。我没有写。

如果我运行这个,

ERR wrong number of arguments for 'set' command
ERR unknown command '$18'
ERR unknown command 'ESSPrivacyMark'
ERR unknown command '$3'
ERR unknown command '225'
ERR unknown command ' *3'
ERR unknown command '$3'
ERR wrong number of arguments for 'set' command
ERR unknown command '$25'
ERR unknown command 'ESSPrivacyMark'
ERR unknown command '$3'
ERR unknown command '157'
ERR unknown command ' *3'
ERR unknown command '$3'

这种情况一直持续下去。输入的形式是

“字符串”\t 计数。

谢谢。

第二次更新:

我使用了流水线,这确实给了我很大的帮助。但很快它就耗尽了内存。作为引用,我有一个带有 64 g RAM 的系统。而且我认为它不会耗尽内存。代码如下:

import redis
import gzip
import os
import sys
r = redis.Redis(host='localhost',port=6379,db=0)
pipe = r.pipeline(transaction=False)
i = 0
MAX = 10000
ignore = ['3gm-0030.gz','3gm-0063.gz','2gm-0008.gz','3gm-0004.gz','3gm-0022.gz','2gm-0019.gz']
for l in os.listdir(sys.argv[1]):
        if(l in ignore):
                continue
        infile = gzip.open(os.path.join(sys.argv[1],l),'rb')
        print 'doing it for file ',l
        for line in infile:
                parts = line.split('\t')
                key = parts[0]
                value = parts[1].rstrip('\n')
                if(i<MAX):
                        pipe.set(key,value)
                        i=i+1
                else:   
                        pipe.execute()
                        i=0
                        pipe.set(key,value)
                        i=i+1
        infile.close()

哈希是可行的方法吗?我认为 64 gig 就足够了。我只给了它 20 亿键值对的一小部分,而不是全部。

最佳答案

你想要的在你的情况下可能是不可能的。

根据 this page ,您的数据集使用 gzip压缩 为 24 GB。 这些文件可能包含很多类似的文本,例如字典。

使用 dict 程序中的 words 文件进行快速测试,得到 3.12 倍的压缩率:

> gzip -k -c /usr/share/dict/web2 > words.gz
> du /usr/share/dict/web2  words.gz
2496    /usr/share/dict/web2
800 words.gz
> calc '2496/800'
3.12 /* 3.12 */
> calc '3.12*24'
74.88 /* 7.488e1 */

因此您的未压缩数据大小很容易超过 64 GB。因此,即使 Redis 没有任何开销,即使您使用 16 位无符号整数来存储计数,它也不会适合您的 RAM。

查看示例,大多数键相对较短;

serve as the incoming   92
serve as the incubator  99
serve as the independent    794
serve as the index  223
serve as the indication 72
serve as the indicator  120
serve as the indicators 45
serve as the indispensable  111
serve as the indispensible  40
serve as the individual 234
serve as the industrial 52

您可以对 key 进行哈希处理,但平均而言它可能不会为您节省很多:

In [1]: from hashlib import md5

In [2]: data = '''serve as the incoming 92
serve as the incubator 99
serve as the independent 794
serve as the index 223
serve as the indication 72
serve as the indicator 120
serve as the indicators 45
serve as the indispensable 111
serve as the indispensible 40
serve as the individual 234
serve as the industrial 52'''

In [3]: lines = data.splitlines()

In [4]: kv = [s.rsplit(None, 1) for s in lines]

In [5]: kv[0:2]
Out[5]: [['serve as the incoming', '92'], ['serve as the incubator', '99']]

In [6]: [len(s[0]) for s in kv]
Out[6]: [21, 22, 24, 18, 23, 22, 23, 26, 26, 23, 23]

In [7]: [len(md5(s[0]).digest()) for s in kv]
Out[7]: [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16]

对于任何短于 16 字节的 key ,它实际上会花费您更多的空间来散列它。

压缩字符串通常不会节省空间,即使您忽略标题也是如此;

In [1]: import zlib

In [2]: zlib.compress('foo')[:3]
Out[2]: 'x\x9cK'

In [3]: zlib.compress('bar')[:3]
Out[3]: 'x\x9cK'

In [4]: s = 'serve as the indispensable'

In [5]: len(s)
Out[5]: 26

In [6]: len(zlib.compress(s))-3
Out[6]: 31

关于python - 写入 3,795,790,711 唯一键 :value pairs to redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15713408/

有关python - 写入 3,795,790,711 唯一键 :value pairs to redis的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  3. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  4. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  5. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  6. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

  7. 「Python|Selenium|场景案例」如何定位iframe中的元素? - 2

    本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决

  8. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

  9. Python 刷Leetcode题库,顺带学英语单词(31) - 2

    ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem

  10. python - 是否可以使用 Ruby 或 Python 禁用 anchor /引用来发出有效的 YAML? - 2

    是否可以在PyYAML或Ruby的Psych引擎中禁用创建anchor和引用(并有效地显式列出冗余数据)?也许我在网上搜索时遗漏了一些东西,但在Psych中似乎没有太多可用的选项,而且我也无法确定PyYAML是否允许这样做.基本原理是我必须序列化一些数据并将其以可读的形式传递给一个不是真正的技术同事进行手动验证。有些数据是多余的,但我需要以最明确的方式列出它们以提高可读性(anchor和引用是提高效率的好概念,但不是人类可读性)。Ruby和Python是我选择的工具,但如果有其他一些相当简单的方法来“展开”YAML文档,它可能就可以了。 最佳答案

随机推荐