提问者:小点点

使用ADOMDClient在Azure函数中解析对JSON的Azure分析响应


我正在使用Microsoft.AnalysisServices.adomdClient.dll文件连接到Azure Analysis Service,以便在Azure函数中执行DAX查询,我需要它在JSON中吐出。 下面是如何做的,但是当有大量的记录时,我看到在将响应转换为JSON时会出现延迟。 Analysis service在2秒内响应,但将响应屏蔽到json需要40秒以上的时间。 有人能提出一个更好的办法吗

AdomdCommand cmd = new AdomdCommand(query, _connect);
public List<Dictionary<string, object>> Results { get; } = new List<Dictionary<string, object>>();
var reader = cmd.ExecuteReader();
var schemeTable = reader.GetSchemaTable();
ISet<string> columnSet = new HashSet<string>();
foreach (DataRow row in schemeTable.Rows)
{
 String columnName = row[0].ToString();
 columnSet.Add(columnName);
}
while (reader.Read())
{
 Dictionary<string, object> columns = new Dictionary<string, object>();
 foreach (string columnName in columnSet)
 {
 var value = reader[reader.GetOrdinal(columnName)];
 if (value != null)
 {
  columns.Add(columnName, value);
 }
 else
 {
  columns.Add(columnName, null);
 }
}
 Results.Add(columns);
}
JsonConvert.SerializeObject(Results)

共1个答案

匿名用户

我在GitHub上有一个示例:microsoft/azure-analysis-services-http-sample。 它将结果从AdomdDataReader以JSON的形式流到输出流。 流可以是MemoryStream或(在我的例子中)HttpResponse流。

public static async Task WriteResultsToStream(object results, Stream stream, CancellationToken cancel)
{

    if (results == null)
    {
        return;
    }

    if (results is AdomdDataReader rdr)
    {
        var encoding = new System.Text.UTF8Encoding(false);
        using (var tw = new StreamWriter(stream,encoding,1024*4,true))
        using (var w = new Newtonsoft.Json.JsonTextWriter(tw))
        {

            await w.WriteStartObjectAsync(cancel);
            var rn = "rows";

            await w.WritePropertyNameAsync(rn);
            await w.WriteStartArrayAsync(cancel);

            while (rdr.Read())
            {
                await w.WriteStartObjectAsync(cancel);
                for (int i = 0; i < rdr.FieldCount; i++)
                {
                    string name = rdr.GetName(i);
                    object value = rdr.GetValue(i);

                    await w.WritePropertyNameAsync(name, cancel);
                    await w.WriteValueAsync(value, cancel);
                }
                await w.WriteEndObjectAsync(cancel);
            }

            await w.WriteEndArrayAsync(cancel);
            await w.WriteEndObjectAsync(cancel);

            await w.FlushAsync();
            await tw.FlushAsync();
            await stream.FlushAsync();
        }
    }
    else if (results is CellSet  cs)
    {
        throw new NotSupportedException("CellSet results");

    }
    else
    {
        throw new InvalidOperationException("Unexpected result type");
    }

}