【问题标题】:Pymongo, select random sequences?Pymongo,选择随机序列?
【发布时间】:2020-06-14 12:07:39
【问题描述】:

我有一个这样的 mongo db 集合

{ "_id" : ObjectId("5e2d4b6479799acab037af68"), 
  "timestamp" : 1577152302, #hourliy
  "login" : 'A4FC9',
  # 240 columns more
}

我想从 mongo db 中选择具有 24 个先前记录的随机序列。

数据库没有每小时的记录,有时它们会被遗漏,所以我无法制作随机时间戳并搜索时间戳范围之间的 24 条先前记录。

目前我正在这样做,但它真的很慢,我想提高性能


db = mongodb...

def sequence( size ):
     # first I search for a random row in my db and fetch the timestamb
     random = next( db.aggregate( [{ '$sample': { 'size'  : 1 }}] )['timestamp']

     #then a search the 24 previous
     next_rows = db.find( {'timestamp': {'$lte': random }} ).sort("timestamp",-1).limit( size )
     return next_rows

SEQUENCES = 100

batch = list()
for x in range( SEQUENCES ):
    rand_sequence = sequence( 24 )
    batch.append( rand_sequence ) 

这将返回 100 个序列,这些序列从具有 24 条先前记录的随机时间戳开始。 获取所有数据需要 30 分钟 有没有办法只用一个查询就可以做到这一点?

另外如果有其他方法请指教。

【问题讨论】:

  • 如果您的每个查询都需要 20 秒才能运行(100 次查询需要 30 分钟),我会看看为什么查询需要这么长时间,或者也许在一个查询中检索整个数据集,然后在您的应用程序中从中提取数据。
  • 问题是该集合有将近 500 万条记录(这是我花了这么长时间的方式)记录,我试图检索所有......并且漏洞操作系统停止工作
  • 使用投影来检索您只需要的数据,并确保您有足够的内存来完成这项工作。

标签: python-3.x mongodb lstm


【解决方案1】:

我做到了!

from random import randrange

db = mongodb...

random = next( db.aggregate( [{ '$sample': { 'size'  : 1 }}] )['timestamp']

#then a search the 50000 previous

maxrows = 50000
SEQUENCES = 100
SEQUENCE_LENGTH = 100

next_rows = db.find( {'timestamp': {'$lte': random }} ).sort("timestamp",-1).limit(maxrows)

# this makes an array of random indexes to select from
chosed = [ randrange( 0, maxrows - SEQUENCE_LENGTH  ) for x in range( SEQUENCE_LENGTH ) ]

#then i create a list to store all the sequences
sequences_list = [ [] for x in range( len(chosed) ) ]

# then i append all the values in squences_list if the index is previous to SEQUENCE_LENGTH 
for i, x in enumerate( next_rows ):
    for j, y in enumerate(chosed):
        if y >= i and y - SEQUENCE_LENGTH < i:
            #append the values correponding to j position on the list
            sequences_list[j].append( x )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2012-01-01
    • 2018-05-05
    • 1970-01-01
    • 2022-01-09
    • 2019-03-18
    • 1970-01-01
    相关资源
    最近更新 更多