通过API

时间:2017-11-30 07:43:41

标签: amazon-web-services amazon-athena

我可以使用带有startQueryExecution()的Athena API在S3中创建响应的CSV文件。但是,我希望能够返回我的应用程序JSON响应,以便我可以进一步处理数据。我通过API运行startQueryExecution()后尝试返回JSON结果,如何将结果作为JSON响应返回?

我正在使用AWS PHP SDK [https://aws.amazon.com/sdk-for-php/],但这与任何语言都相关,因为我找不到实际获得回复的任何答案,它只是将CSV文件保存到S3。

$athena = AWS::createClient('athena');
$queryx = 'SELECT * FROM elb_logs LIMIT 20';

$result = $athena->startQueryExecution([
    'QueryExecutionContext' => [
        'Database' => 'sampledb',
    ],
    'QueryString' => 'SELECT request_ip FROM elb_logs LIMIT 20', // REQUIRED
    'ResultConfiguration' => [ // REQUIRED
        'EncryptionConfiguration' => [
            'EncryptionOption' => 'SSE_S3' // REQUIRED
        ],
        'OutputLocation' => 's3://xxxxxx/', // REQUIRED
    ],
]);

// check completion : getQueryExecution()
$exId = $result['QueryExecutionId'];

sleep(6);

$checkExecution = $athena->getQueryExecution([
    'QueryExecutionId' => $exId, // REQUIRED
]);


if($checkExecution["QueryExecution"]["Status"]["State"] == 'SUCCEEDED')
{
    $dataOutput = $athena->getQueryResults([
        'QueryExecutionId' => $result['QueryExecutionId'], // REQUIRED
    ]);

      while (($data = fgetcsv($dataOutput, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
      }         

}

1 个答案:

答案 0 :(得分:1)

Amazon Athena SDK将返回查询结果,然后您可以将其写为(发送)为JSON。 SDK本身不会为您执行此操作。

API startQueryExecution()返回QueryExecutionId。使用此命令调用getQueryExecution()以确定查询是否完整。查询完成后,调用getQueryResults()。

然后,您可以处理结果集中的每一行。