S3选择CSV标头

时间:2018-06-14 01:56:20

标签: amazon-web-services amazon-s3 amazon-s3-select

我正在使用S3 Select从S3 Bucket读取csv文件并输出为CSV。在输出中我只看到行,但不是标题。如何获得包含标题的输出。

import boto3

s3 = boto3.client('s3')

r = s3.select_object_content(
        Bucket='demo_bucket',
        Key='demo.csv',
        ExpressionType='SQL',
        Expression="select * from s3object s",
        InputSerialization={'CSV': {"FileHeaderInfo": "Use"}},
        OutputSerialization={'CSV': {}},
)

for event in r['Payload']:
    if 'Records' in event:
        records = event['Records']['Payload'].decode('utf-8')
        print(records)

CSV

Name, Age, Status
Rob, 25, Single
Sam, 26, Married

s3select的输出

Rob, 25, Single
Sam, 26, Married

3 个答案:

答案 0 :(得分:1)

Amazon S3 Select不会输出标题。

在您的代码中,您可以在循环结果之前包含print命令来输出标题。

答案 1 :(得分:0)

更改InputSerialization={'CSV': {"FileHeaderInfo": "Use"}},

InputSerialization={'CSV': {"FileHeaderInfo": "NONE"}},

然后,它将打印完整的内容,包括标题。

说明

FileHeaderInfo接受“ NONE | USE | IGNORE”之一。

使用NONE选项而不是USE,它也会打印标题,因为NONE告诉您还需要标题来进行处理。

这里是参考。 https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.select_object_content

希望对您有帮助。

答案 2 :(得分:0)

Red Boy的解决方案不允许您在查询中使用列名,而必须使用列索引。 这对我不利,因此我的解决方案是执行另一个查询,以仅获取标头并将其与实际查询结果连接起来。这是基于JavaScript的,但同样适用于Python:

      const params = {
        Bucket: bucket,
        Key: "file.csv",
        ExpressionType: 'SQL',
        Expression: `select * from s3object s where s."date" >= '${fromDate}'`,
        InputSerialization: {'CSV': {"FileHeaderInfo": "USE"}},
        OutputSerialization: {'CSV': {}},
      };

      //s3 select doesn't return the headers, so need to run another query to only get the headers (see '{"FileHeaderInfo": "NONE"}')
      const headerParams = {
        Bucket: bucket,
        Key: "file.csv",
        ExpressionType: 'SQL',
        Expression: "select * from s3object s limit 1", //this will only get the first record of the csv, and since we are not parsing headers, they will be included
        InputSerialization: {'CSV': {"FileHeaderInfo": "NONE"}},
        OutputSerialization: {'CSV': {}},
      };

      //concatenate header + data -- getObject is a method that handles the request
      return await this.getObject(s3, headerParams) + await this.getObject(s3, params);