首页 > 解决方案 > 编码大型 numpy 数组并将其保存到 dynamodb

问题描述

我正在尝试使用 Python 构建一个 lambda 函数,并将 dict 输出保存到 dynamodb 数据库。dict 输出之一是浮点数 numpy 数组。可能已经提出了类似的问题,例如,这里使用 pickle.dumps 或 numpy.save (如何在保留矩阵维度的同时序列化 numpy 数组?)。

import boto3
import numpy as np
import pickle

# Dynamodb table example with primary keys first_name and last_name
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')

# Dict output example
output = {
    'first_name': 'David',
    'last_name': 'Adams',
    'rate', np.random.rand(100000)
}

# Put dict output directly as item to dynamodb
# it will fail due to the data type dynamodb supports
table.put_item(
    Item = output
)

# OR convert array to string, but the numeric array will be truncated
table.put_item(
    Item = {
        'first_name': output['first_name'],
        'last_name': output['last_name'],
        'rate': str(output['rate'])
    }
)

# OR using pickle.dumps to convert numeric array to bytes.
# However, it will fail when the array length is too big, since dynamodb item has a limit of 400kb
table.put_item(
    Item = {
        'first_name': output['first_name'],
        'last_name': output['last_name'],
        'rate': pickle.dumps(output['rate'])
    }
)

标签: jsonpython-3.xamazon-web-servicesnumpyamazon-dynamodb

解决方案


推荐阅读