PHP Treasure Data REST API


そんなこんなで6日目です。今日は弊社のとあるゲームからTDへのクエリに使っているライブラリについて簡単にご紹介したいと思います。

PHP TreasureData Api Client

sotarokがが作ったphp-treasure-dataというTD APIがあるのは知っていたのですがやんごとなき事情+Proxy周りのサポートとかを入れたりするのでつくったのが下記ライブラリです

実装が去年なので今の最新の機能はそんなに無かったりすると思うんですが、必要な機能はだいたい揃っているはず。

KEEP IN MINDの所をを見返すとメモリ利用率でチョット効率的なはず、とかなるべく小さな配列使うようにしてるので比較的安定してるよーってのをオシてたみたいなのですが、実測してないしまぁ、とりあえず書いてみたくらいのものだったと思うんでとりあえず横に置いておきましょう。

Treasure Data API

TDのAPIについては上記URLに詳細な記載があります、がソースみたほうが色々と面白いと個人的に思っています。

基本的にほとんどすべての操作がREST API経由で行えるのもTDのメリットですね。

実行例

オールドスタイルなPHPライブラリなので同梱のautoloaderを使うかComposer経由で利用出来ます。

composerの場合は下記をrequireに追加してください。

{
   "require": {
       "chobie/treasuredata-api-client": "dev-master"
    }
}

[https://github.com/chobie/treasuredata-api-client/blob/master/examples/issue\_query.php]

それではQuery実行から取得するまで待つ実装の例を見てみましょう。

<?php
require_once join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)), "src", "TreasureData", "Autoloader.php"));
date_default_timezone_set("UTC");
TreasureData_Autoloader::register();

$api = TreasureData_APIFactory::createClient(array(
    "api_key" => "<PUT YOUR API KEY HERE(see ~/.td/td.conf)>",
));

$message = $api->issueHiveQuery("testdb", "select v['code'] as code, count(1) as cnt from www_access group by v['code']", 0)
                ->getResult();

/* @var TreasureData_API_Message_IssueJob $message */

printf("# Issuing job_id %s successful\n", $message->getJobId());
printf("# polling job status. this will 30 over seconds...\n");

while (true) {
    printf("# Issuing job status api. we wait 10 seconds after issuing api.\n");

    $st = $api->getJobStatus($message->getJobId())->getResult();
    /* @var TreasureData_API_Message_JobStatus $status */
    if ($st->isSuccess()) {
        $result = $api->getJobResult($message->getJobId())->getResult();
        break;
    } else if ($st->isError()) {
        throw new RuntimeException(sprintf("job_id %s returns error", $message->getJobId()));
    } else {
        printf(".");
        var_dump($st);
        sleep(10);
    }
}

var_dump($result);

ruby等の場合は公式のライブラリを使えばいいんですが、PHPだとデファクトスタンダードがないので状況に併せて好きなのを使うといいと思います。

たぶん後の方でこれを使ったアプリケーション側視点での記事をなんか書くと思うのでご期待!