【发布时间】:2015-07-22 22:40:30
【问题描述】:
我正在使用 C# .Net 客户端库将插入数据从本地文件流式传输到 Bigquery 数据库。我用我的代码成功插入了所有数据,但是性能(插入速度)非常慢。我的加载速度为 20KB/秒。例如,我有一个大小为 323MB 的文件,加载程序大约需要 20 分钟。我测试了我的带宽,上传速度是 3MB/秒,我想知道是否有办法提高性能?(我想它应该比那快得多)
这是我的代码:
namespace BigQuery_Test
{
class StreamDatacs
{
private static ServiceAccountCredential credential;
public StreamDatacs()
{
Credential2().Wait();
}
public async Task Credential2()
{
string certificateFile = "C:\\xxxxxx.p12";
string serviceAccountEmail = "xxxxxxxxxxxx@developer.gserviceaccount.com";
var certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { StorageService.Scope.DevstorageReadWrite,
BigqueryService.Scope.Bigquery }
}.FromCertificate(certificate));
Console.WriteLine(credential.Token);
Console.WriteLine(credential.TokenServerUrl);
}
public void ReadData(string path)
{
var logs = new List<TableDataInsertAllRequest.RowsData>();
using (StreamReader sr = new StreamReader(path))
{
string line = "";
string [] aLog = new string[1000];
Log Loga = new Log();
int count = 0;
int i = 0;
while((line = sr.ReadLine()) != null)
{
var theLog = new TableDataInsertAllRequest.RowsData();
string[] token = line.Split('\t');
theLog.Json = new Dictionary<string, object>();
theLog.Json.Add("Timestamp", token[0]);
theLog.Json.Add("ClientIpAddress", token[1]);
theLog.Json.Add("Username", token[2]);
theLog.Json.Add("GroupID", token[3]);
theLog.Json.Add("CompanyID", token[4]);
theLog.Json.Add("FullOrSiteLogging", token[5]);
theLog.Json.Add("PolicyFlags", token[6]);
theLog.Json.Add("ActionsTaken", token[7]);
theLog.Json.Add("ResponseStatus", token[8]);
logs.Add(theLog);
count++;
if (count > 20000)
{
BQStreamInsert(logs);
logs.Clear();
count = 0;
}
}
}
Task.WaitAll(tasks.ToArray());
}
public void BQStreamInsert(List<TableDataInsertAllRequest.RowsData> rows)
{
string projectId= "ws-2015-logs";
string datasetId = "CompanyGroup1";
string tableId ="RawLogsTest7";
var service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "BQ test"
});
try
{
var content = new TableDataInsertAllRequest();
content.Rows = rows;
content.Kind = "bigquery#tableDataInsertAllRequest";
content.IgnoreUnknownValues = true;
content.SkipInvalidRows = true;
var insertTask = service.Tabledata.InsertAll(content, projectId, datasetId, tableId);
TableDataInsertAllResponse response = insertTask.Execute();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
在program.cs中:
class Program
{
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
StreamDatacs sd = new StreamDatacs();
sd.ReadData(@"C:\2015071600.csv");
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Stop();
Console.Read();
}
在代码中,我逐行读取文件,每20,000行停止并插入BQ,直到所有行都插入为止。我在这里尝试了不同的缓冲区大小(500行,1000行,50,000行),但没有看到很大的不同。 我很感激你的任何建议。提前非常感谢。
【问题讨论】:
标签: google-bigquery