初めに
.NETのBigQuery APIライブラリ(NuGetパッケージだとGoogle.Cloud.BigQuery.V2)を用いて、BigQueryからレコードを取得する場合、サンプルソースなどではジョブの完了を待って結果を読みだす方法が書かれている。
一方、IDataReaderのReadメソッドの様に、一件ずつレコードにアクセスしたい場合もアプリケーションの仕様として求められる場合がある。
後者の場合、どのようなコードになるのかをこの投稿では例示する。
ジョブ完了まで待つ場合のコードサンプル
コードサンプルというか、Googleのページにあるサンプルそのまま。
GetAtOnce
using Google.Cloud.BigQuery.V2;
using System;
public class BigQueryQuery
{
public void Query(
string projectId = "your-project-id"
)
{
BigQueryClient client = BigQueryClient.Create(projectId);
string query = @"
SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013`
WHERE state = 'TX'
LIMIT 100";
BigQueryJob job = client.CreateQueryJob(
sql: query,
parameters: null,
options: new QueryOptions { UseQueryCache = false });
// Wait for the job to complete.
job.PollUntilCompleted();
// Display the results
foreach (BigQueryRow row in client.GetQueryResults(job.Reference))
{
Console.WriteLine($"{row["name"]}");
}
}
}
これだと、全件の件数が多すぎた場合にも途中で打ち切ることなくレコードを取得しなくてはいけない。
一件ずつ読み込むコードの例
GetOneByOne
public class BigQueryQueryOneByOne
{
public void Query(
string projectId = "your-project-id"
)
{
BigQueryClient client = BigQueryClient.Create(projectId);
string query = @"
SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013`
WHERE state = 'TX'
LIMIT 100";
BigQueryJob job = client.CreateQueryJob(
sql: query,
parameters: null,
options: new QueryOptions { UseQueryCache = false });
// Wait for the job to complete.
BigQueryResults results = client.GetQueryResults(job.Resource.JobReference, queryResultOptions).ThrowOnAnyError();
IEnumerator<BigQueryRow> recordEnumerator = results.GetEnumerator();
// Display the results
int rowCount = 0;
while(recordEnumerator.MoveNext())
{
if(rowCount > 1000)
{
// 読み込みを1000件で打ち切る。
break;
}
BigQueryRow row = recordEnumerator.Current;
Console.WriteLine($"{row["name"]}");
rowCount++;
}
}
}
こんな感じになる。