有效使用 KQL

已完成

Eventhouse 中的 KQL 数据库针对大量实时数据进行优化。 为了获得最佳结果,你应该记住一些好的做法。

基于实时数据流的表可能会变得很大。 最大程度地减少查询返回的数据有助于优化性能,并防止因超出数据限制而出错。

筛选列

使用 project 关键字仅检索所需的列。 例如,以下查询仅返回四列数据:

Automotive
| project trip_id, vendor_id, pickup_datetime, fare_amount

筛选行

使用 where 关键字筛选基于特定条件返回的行。 例如,以下查询仅返回当月发生的行程的数据:

Automotive
| where getmonth(pickup_datetime) == getmonth(now())
  and getyear(pickup_datetime) == getyear(now())
| project trip_id, vendor_id, pickup_datetime, fare_amount

请注意此示例中 getmonthgetyear 函数的使用。 鉴于实时数据通常涉及时态(基于时间的)元素,KQL 为基于时间的筛选提供强有力的支持。 例如,以下查询使用 ago 函数将结果限制为仅过去 30 分钟内发生的事件。

Automotive
| where pickup_datetime > ago(30min)
| project trip_id, vendor_id, pickup_datetime, fare_amount

当数据从流源(如通过 Eventstream)不断地进行加载时,可以使用 ingestion_time 函数根据数据加载到表中的时间进行筛选,即使数据不包含作为筛选条件的基于时间的值。 例如,以下查询检索过去一小时内已加载到表中的事件。

Automotive
| where ingestion_time() > ago(1h)
| project trip_id, vendor_id, pickup_datetime, fare_amount

汇总数据

有时,无需在单个事件级别检索数据。 你可以汇总数据来帮助对模式进行分析(通常基于时间间隔)。

例如,以下查询检索过去一天内引入的事件中每个出租车供应商每小时收取的平均费用。

Automotive
| where ingestion_time() > ago(1d)
| summarize average_fare = avg(fare_amount) by vendor_id, pickup_hour = hourofday(pickup_datetime)
| project pickup_hour, vendor_id, average_fare
| sort by pickup_hour