首页 > 解决方案 > 如何在 KQL 查询中指定参数?

问题描述

我正在尝试使用查询参数和 .NET Kusto SDK 对 Azure 数据资源管理器集群执行 KQL 查询。

我尝试将参数放在大括号 {} 内并且没有大括号。

我已阅读有关将参数传递给查询的文档,但我找不到任何示例说明通过 .NET SDK 将查询传递给 Azure 数据资源管理器时的外观。

当我在工具中设置参数时,我的查询在 Kusto.Explorer 工具中有效,但在使用 SDK 时我没有运气。

var queryParameters = new Dictionary<string, string>()
            {
                { "myscope", "scope001" },
                { "startdate", "2019-01-01" },
                { "enddate", "2019-01-30" },
                { "author", "Bob Jammo" }
            };

var query = @"declare query_parameters (myscope:string, startdate:string, enddate:string, author:string);
                            Events 
                            | where Scope == ""{myscope}"" 
                                and EventTime between (datetime({startdate}) .. datetime({enddate}))
                                and EventType == ""product""
                                and User.Email <> """"
                            | mv-expand Payload.products
                            | where Payload_products.authors contains ""{author}""
                            | distinct DeviceId
                            | count";

using (var client = KustoClientFactory.CreateCslQueryProvider(ConfigurationManager.AppSettings["AdxConnectionString"]))
{
    var clientRequestProperties = new Kusto.Data.Common.ClientRequestProperties(
        options: null,
        parameters: queryParameters);

    clientRequestProperties.ClientRequestId = StepsBase.ScenarioScope;

    using (var reader = client.ExecuteQuery(query, clientRequestProperties))
    {
        reader.Read();
        return Convert.ToInt32(reader[0]);
    }
}

我收到一个错误,提示我尚未设置参数值:“语法错误:无法解析查询:无法解析日期时间文字:'datetime(startdate)'”

标签: parameterskql

解决方案


从错误消息来看,这是因为您使用datetime({startdate})的是todatetime({startdate}).

无论如何,您还可以考虑更改 and 的类型而不是startdate开头enddate(并在 .NET 字典中调整它们的定义)datetimestring


推荐阅读