✅ Azure 流分析 ✅ 构造事件流
返回指定索引处的数组元素。 此函数可用于分析 JSON 和 AVRO 格式的输入事件数据中的数组和嵌套对象。 有关更多示例,请参阅 分析 JSON 和 AVRO 数据。 如果需要返回数组中的所有嵌套元素,请改用 GetArrayElements 。
语法
GetArrayElement ( array_expression, bigint_expression )
论据
array_expression
要计算为源数组的数组表达式。 array_expression可以是数组类型的列,也可以是另一个函数调用的结果。
bigint_expression
要计算为数组索引的 bigint 表达式。 元素数组中的序号位置,从 0 开始。
返回类型
返回类型由数组元素类型确定,可以是 任何受支持的类型。
例子
示例数据
[
{
"DeviceId" : "123",
"SensorReadings" :
{
"Temperature" : 80,
"Humidity" : 70,
"CustomSensor": [1,1,0]
}
},
{
"DeviceId" : "631",
"SensorReadings" :
{
"Temperature" : 81,
"Humidity" : 69,
"CustomSensor": [0,1,0]
}
}
]
上面的示例数据集是两条记录的数组。 在 JSON 文件中用作 本地输入 时,Azure 流分析会解释顶级数组以生成行/事件。 无需在查询语法中考虑它。
在单个记录级别,有两个 不同类型的属性。
DeviceId 为 nvarchar(max)类型, SensorReadings 类型 为 record (object)。
GetType 可用于在必要时确定类型。
SensorReadings有三个属性:两个是 bigint 类型:Temperature并且HumidityCustomSensor属于数组类型(bigint)。 如果此数组更为复杂(本身包含记录或数组),则可使用 GetArrayElements (plural) 和 GetRecordPropertyValue 的组合。
查询
此查询使用点表示法返回记录根目录(DeviceId)、嵌套字段(TemperatureHumidity包括数组(CustomSensor),最后,通过 GetArrayElement 返回该数组的第一个和第二个元素(索引 0 和 1):
SELECT
i.DeviceId,
i.SensorReadings.Temperature,
i.SensorReadings.Humidity,
i.SensorReadings.CustomSensor as CustomSensorArray,
GetArrayElement(i.SensorReadings.CustomSensor,0) AS FirstCustomSensorValue,
GetArrayElement(i.SensorReadings.CustomSensor,1) AS SecondCustomSensorValue
FROM input i
返回以下输出:
| DeviceId | 温度 | 湿度 | CustomSensorArray | FirstCustomSensorValue | SecondCustomSensorValue |
|---|---|---|---|---|---|
| 631 | 81 | 69 | 0,1,0 | 0 | 1 |
| 123 | 80 | 70 | 1,1,0 | 1 | 1 |
使用 CROSS APPLY 展开数组:
SELECT
i.DeviceId,
CustomerSensorValue.ArrayValue AS CustomerSensorValue
FROM input AS i
CROSS APPLY GetArrayElements(i.SensorReadings.CustomSensor) AS CustomerSensorValue
返回以下输出:
| DeviceId | CustomerSensorValue |
|---|---|
| 631 | 0 |
| 631 | 1 |
| 631 | 0 |
| 123 | 0 |
| 123 | 1 |
| 123 | 1 |
从那里,可以根据需要轻松聚合内容:
SELECT
i.DeviceId,
SUM(CustomerSensorValue.ArrayValue) AS CustomerSensorTotal
FROM input AS i
CROSS APPLY GetArrayElements(i.SensorReadings.CustomSensor) AS CustomerSensorValue
GROUP BY i.DeviceId, TumblingWindow(minute, 1)
| DeviceId | CustomerSensorTotal |
|---|---|
| 123 | 2 |
| 631 | 1 |