Importing Large Size of Zipped JSON File from Amaz

2019-08-02 09:07发布

问题:

I'm trying to import a large size of ZIPPED JSON FILE from Amazon S3 into AWS RDS-PostgreSQL using Python. But, these errors occured,

Traceback (most recent call last):

File "my_code.py", line 64, in file_content = f.read().decode('utf-8').splitlines(True)

File "/usr/lib64/python3.6/zipfile.py", line 835, in read buf += self._read1(self.MAX_N)

File "/usr/lib64/python3.6/zipfile.py", line 925, in _read1 data = self._decompressor.decompress(data, n)

MemoryError

//my_code.py

import sys
import boto3
import psycopg2
import zipfile
import io
import json
import config

s3 = boto3.client('s3', aws_access_key_id=<aws_access_key_id>, aws_secret_access_key=<aws_secret_access_key>)
connection = psycopg2.connect(host=<host>, dbname=<dbname>, user=<user>, password=<password>)
cursor = connection.cursor()

bucket = sys.argv[1]
key = sys.argv[2]
obj = s3.get_object(Bucket=bucket, Key=key)


def insert_query():
    query = """
        INSERT INTO data_table
        SELECT
            (src.test->>'url')::varchar, (src.test->>'id')::bigint,
            (src.test->>'external_id')::bigint, (src.test->>'via')::jsonb
        FROM (SELECT CAST(%s AS JSONB) AS test) src
    """
    cursor.execute(query, (json.dumps(data),))


if key.endswith('.zip'):
    zip_files = obj['Body'].read()
    with io.BytesIO(zip_files) as zf:
        zf.seek(0)
        with zipfile.ZipFile(zf, mode='r') as z:
            for filename in z.namelist():
                with z.open(filename) as f:
                    file_content = f.read().decode('utf-8').splitlines(True)
                    for row in file_content:
                        data = json.loads(row)
                        insert_query()
if key.endswith('.json'):
    file_content = obj['Body'].read().decode('utf-8').splitlines(True)
    for row in file_content:
        data = json.loads(row)
        insert_query()

connection.commit()
connection.close()

Are there any solutions to these problems? Any help would do, thank you so much!

回答1:

The problem is that you try to read an entire file into memory at a time, which can cause you to run out of memory if the file is indeed too large.

You should read the file one line at a time, and since each line in a file is apparently a JSON string, you can process each line directly in the loop:

with z.open(filename) as f:
    for line in f:
        insert_query(json.loads(line.decode('utf-8')))

Your insert_query function should accept data as a parameter, by the way:

def insert_query(data):