Let 语句Let statement

Let 语句将名称绑定到表达式。Let statements bind names to expressions. 对于作用域中出现了 let 语句的其余部分,可以使用名称来引用其绑定值。For the rest of the scope, where the let statement appears, the name can be used to refer to its bound value. Let 语句的作用域可以是全局,也可以是某个函数主体。The let statement may be within a global scope or a function body scope. 如果该名称以前绑定到另一个值,则使用“innermost”let 语句绑定。If that name was previously bound to another value, the "innermost" let statement binding is used.

Let 语句改善了模块化和重用,因为它们允许你将可能复杂的表达式分解为多个部分。Let statements improve modularity and reuse, since they let you break a potentially complex expression into multiple parts. 每个部分都通过 let 语句绑定到一个名称,它们共同构成了整个表达式。Each part is bound to a name through the let statement, and together they compose the whole. 它们还可用于创建用户定义的函数和视图。They can also be used to create user-defined functions and views. 视图是基于表的表达式,其结果看起来像新表。The views are expressions over tables whose results look like a new table.

备注

Let 语句绑定的名称必须是有效的实体名称。Names bound by let statements must be valid entity names.

Let 语句绑定的表达式可以是:Expressions bound by let statements can be:

  • 标量类型Scalar types
  • 表格类型Tabular types
  • 用户定义的函数 (lambda)User-defined functions (lambdas)

语法Syntax

let Name = ScalarExpression | TabularExpression | FunctionDefinitionExpressionlet Name = ScalarExpression | TabularExpression | FunctionDefinitionExpression

字段Field 定义Definition 示例Example
名称Name 要绑定的名称。The name to bind. 名称必须是有效的实体名称。The name must be a valid entity name. 允许实体名称转义,例如 ["Name with spaces"]Entity name escaping, such as ["Name with spaces"], is permitted.
ScalarExpressionScalarExpression 具有标量结果的表达式,其值绑定到名称。An expression with a scalar result whose value is bound to the name. let one=1;
TabularExpressionTabularExpression 具有表格结果的表达式,其值绑定到名称。An expression with a tabular result whose value is bound to the name. Logs | where Timestamp > ago(1h)
FunctionDefinitionExpressionFunctionDefinitionExpression 一个表达式,该表达式生成将绑定到名称的 lambda(匿名函数声明)。An expression that yields a lambda, an anonymous function declaration that is to be bound to the name. let f=(a:int, b:string) { strcat(b, ":", a) }

Lambda 表达式语法Lambda expressions syntax

[view] ([TabularArguments][,][ScalarArguments]) { FunctionBody }[view] ([TabularArguments][,][ScalarArguments]) { FunctionBody }

TabularArguments - [TabularArgName : ([AtrName : AtrType] [, ... ])] [, ... ][,]TabularArguments - [TabularArgName : ([AtrName : AtrType] [, ... ])] [, ... ][,]

或者:or:

[TabularArgName : ( * )][TabularArgName : ( * )]

ScalarArguments - [ArgName : ArgType] [, ... ]ScalarArguments - [ArgName : ArgType] [, ... ]

字段Field 定义Definition 示例Example
viewview 仅可出现在无自变量的无参数 lambda 中。May appear only in a parameterless lambda, that has no arguments. 它表示当“所有表”都是查询时将包含绑定名称。It indicates that the bound name will be included when "all tables" are queries. 例如,当使用 union * 时。For example, when using union *.
TabularArgumentsTabularArguments 形式表格表达式自变量的列表。The list of the formal tabular expression arguments.
每个表格自变量都有:Each tabular argument has:
  • TabularArgNameTabularArgName
形式表格自变量的名称。The name of the formal tabular argument. 该名称可以出现在 FunctionBody 中,并在调用 lambda 时绑定到特定值。The name may appear in the FunctionBody and is bound to a particular value when the lambda is invoked.
  • 表架构定义Table schema definition
属性及其类型的列表A list of attributes with their types AtrName:AtrTypeAtrName : AtrType
ScalarArgumentsScalarArguments 形式标量自变量的列表。The list of the formal scalar arguments.
每个标量自变量都有:Each scalar argument has:
  • ArgNameArgName
形式标量自变量的名称。The name of the formal scalar argument. 该名称可以出现在 FunctionBody 中,并在调用 lambda 时绑定到特定值。The name may appear in the FunctionBody and is bound to a particular value when the lambda is invoked.
  • ArgTypeArgType
形式标量自变量的类型。The type of the formal scalar argument. 目前仅支持使用以下类型作为 lambda 参数类型:boolstringlongdatetimetimespanrealdynamic(以及这些类型的别名)。Currently only the following types are supported as a lambda argument type: bool, string, long, datetime, timespan, real, and dynamic (and aliases to these types).

备注

在 lambda 调用中使用的表格表达式必须包含(但不限于)类型匹配的所有属性。The tabular expression that is used in the lambda invocation must include (but is not limited to) all the attributes with the matching types.

(*) 可用作表格表达式。(*) can be used as the tabular expression.

任何表格表达式都可以用在 lambda 调用中,但其列都不能在 lambda 表达式中访问。Any tabular expression can be used in the lambda invocation and none of its columns can be accessed in the lambda expression.

所有表格参数都应位于标量参数之前。All tabular arguments should appear before the scalar arguments.

多个嵌套的 let 语句Multiple and nested let statements

多个 let 语句可以一起使用,以分号 ; 作为分隔符,如以下示例所示。Multiple let statements can be used with the semicolon, ;, delimiter between them, like in the following example.

备注

最后一个语句必须是有效的查询表达式。The last statement must be a valid query expression.

let start = ago(5h); 
let period = 2h; 
T | where Time > start and Time < start + period | ...

允许使用嵌套的 let 语句,可将其用在 lambda 表达式中。Nested let statements are permitted, and can be used inside a lambda expression. Let 语句和自变量在函数主体的当前作用域和内部作用域中可见。Let statements and arguments are visible in the current and inner scope of the function body.

let start_time = ago(5h); 
let end_time = start_time + 2h; 
T | where Time > start_time and Time < end_time | ...

示例Examples

使用 let 函数定义常量Use let function to define constants

下面的示例将名称 x 绑定到标量文本 1,然后在表格表达式语句中使用它。The following example binds the name x to the scalar literal 1, and then uses it in a tabular expression statement.

let x = 1;
range y from x to x step x

此示例与前一个示例类似,在使用 ['name'] 表示法时仅提供 let 语句的名称。This example is similar to the previous one, only the name of the let statement is given using the ['name'] notion.

let ['x'] = 1;
range y from x to x step x

将 let 用于标量值Use let for scalar values

let n = 10;  // number
let place = "Dallas";  // string
let cutoff = ago(62d); // datetime
Events 
| where timestamp > cutoff 
    and city == place 
| take n

使用带有自变量的 let 语句进行标量计算Use let statement with arguments for scalar calculation

此示例使用带有自变量的 let 语句进行标量计算。This example uses the let statement with arguments for scalar calculation. 该查询定义了用于将两个数字相乘的函数 MultiplyByNThe query defines function MultiplyByN for multiplying two numbers.

let MultiplyByN = (val:long, n:long) { val * n };
range x from 1 to 5 step 1 
| extend result = MultiplyByN(x, 5)
xx resultresult
11 55
22 1010
33 1515
44 2020
55 2525

以下示例删除输入中的前导/尾随 1The following example removes leading/trailing ones (1) from the input.

let TrimOnes = (s:string) { trim("1", s) };
range x from 10 to 15 step 1 
| extend result = TrimOnes(tostring(x))
xx resultresult
1010 00
1111
1212 22
1313 33
1414 44
1515 55

使用多个 let 语句Use multiple let statements

此示例定义了两个 let 语句,其中一个语句 (foo2) 使用另一个语句 (foo1)。This example defines two let statements where one statement (foo2) uses another (foo1).

let foo1 = (_start:long, _end:long, _step:long) { range x from _start to _end step _step};
let foo2 = (_step:long) { foo1(1, 100, _step)};
foo2(2) | count
// Result: 50

在 let 语句中使用 view 关键字Use the view keyword in a let statement

此示例演示了如何将 let 语句与 view 关键字一起使用。This example shows you how to use let statement with the view keyword.

let Range10 = view () { range MyColumn from 1 to 10 step 1 };
let Range20 = view () { range MyColumn from 1 to 20 step 1 };
search MyColumn == 5
$table$table MyColumnMyColumn
Range10Range10 55
Range20Range20 55

使用 materialize 函数Use materialize function

materialize 函数允许在执行查询时缓存子查询结果。The materialize function lets you cache subquery results during the time of query execution.

let totalPagesPerDay = PageViews
| summarize by Page, Day = startofday(Timestamp)
| summarize count() by Day;
let materializedScope = PageViews
| summarize by Page, Day = startofday(Timestamp);
let cachedResult = materialize(materializedScope);
cachedResult
| project Page, Day1 = Day
| join kind = inner
(
    cachedResult
    | project Page, Day2 = Day
)
on Page
| where Day2 > Day1
| summarize count() by Day1, Day2
| join kind = inner
    totalPagesPerDay
on $left.Day1 == $right.Day
| project Day1, Day2, Percentage = count_*100.0/count_1
第 1 天Day1 第 2 天Day2 百分比Percentage
2016-05-01 00:00:00.00000002016-05-01 00:00:00.0000000 2016-05-02 00:00:00.00000002016-05-02 00:00:00.0000000 34.064572597525534.0645725975255
2016-05-01 00:00:00.00000002016-05-01 00:00:00.0000000 2016-05-03 00:00:00.00000002016-05-03 00:00:00.0000000 16.61836896010116.618368960101
2016-05-02 00:00:00.00000002016-05-02 00:00:00.0000000 2016-05-03 00:00:00.00000002016-05-03 00:00:00.0000000 14.629137648963614.6291376489636