简体   繁体   English

通过API从Athena Query返回JSON

[英]Return JSON from Athena Query via API

I am able to use the Athena API with startQueryExecution() to create a CSV file of the responses in S3. 我可以使用带有startQueryExecution()的Athena API在S3中创建响应的CSV文件。 However, I would like to be able to return to my application a JSON response so I can further process the data. 但是,我希望能够返回我的应用程序JSON响应,以便我可以进一步处理数据。 I am trying to return JSON results after I run startQueryExecution() via the API, how do I can get the results as a JSON response back? 我通过API运行startQueryExecution()后尝试返回JSON结果,如何将结果作为JSON响应返回?

I am using the AWS PHP SDK [ https://aws.amazon.com/sdk-for-php/] , however this is relevant to any language since I can not find any answers to actually getting a response back, it just saves a CSV file to S3. 我正在使用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";
        }
      }         

}

The Amazon Athena SDK will return the results of a query and then you can write (send) this as JSON. Amazon Athena SDK将返回查询结果,然后您可以将其写为(发送)为JSON。 The SDK will not do this for you itself. SDK本身不会为您执行此操作。

The API startQueryExecution() retuns QueryExecutionId. API startQueryExecution()返回QueryExecutionId。 Use this to call getQueryExecution() to determine if the query is complete. 使用此命令调用getQueryExecution()以确定查询是否完整。 Once the query completes call getQueryResults(). 查询完成后,调用getQueryResults()。

You can then process each row in the result set. 然后,您可以处理结果集中的每一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM