IoT 中心消息路由查询语法IoT Hub message routing query syntax

消息路由使用户能够将不同的数据类型(即设备遥测消息、设备生命周期事件和设备孪生更改事件)路由到各个终结点。Message routing enables users to route different data types namely, device telemetry messages, device lifecycle events, and device twin change events to various endpoints. 此外,还可以在路由此数据之前对其应用丰富查询,以接收对你而言重要的数据。You can also apply rich queries to this data before routing it to receive the data that matters to you. 本文介绍 IoT 中心消息路由查询语言,并提供一些常见的查询模式。This article describes the IoT Hub message routing query language, and provides some common query patterns.


本文中提到的某些功能(例如云到设备消息传递、设备孪生、设备管理)仅在 IoT 中心的标准层中提供。Some of the features mentioned in this article, like cloud-to-device messaging, device twins, and device management, are only available in the standard tier of IoT hub. 有关基本和标准 IoT 中心层的详细信息,请参阅如何选择合适的 IoT 中心层For more information about the basic and standard IoT Hub tiers, see How to choose the right IoT Hub tier.

消息路由允许你查询消息属性和消息正文以及设备孪生标记和设备孪生属性。Message routing allows you to query on the message properties and message body as well as device twin tags and device twin properties. 如果消息正文不是 JSON,则消息路由仍可路由消息,但查询不能应用于消息正文。If the message body is not JSON, message routing can still route the message, but queries cannot be applied to the message body. 查询被描述为布尔表达式,其中布尔值 true 使查询成功,会路由所有传入数据,而布尔值 false 使查询失败,并且不会路由数据。Queries are described as Boolean expressions where a Boolean true makes the query succeed which routes all the incoming data, and Boolean false fails the query and no data is routed. 如果表达式计算结果为 null 或未定义,则将其视为 false,并且发生故障时将在 IoT 中心路由资源日志日志中生成错误。If the expression evaluates to null or undefined, it is treated as false and an error will be generated in IoT Hub routes resource logs logs in case of a failure. 查询语法必须正确,才能保存和计算路由。The query syntax must be correct for the route to be saved and evaluated.

基于消息属性的消息路由查询Message routing query based on message properties

IoT 中心为所有设备到云的消息传送定义了格式,以便实现跨协议互操作性。The IoT Hub defines a common format for all device-to-cloud messaging for interoperability across protocols. IoT 中心消息假设以下 JSON 表示形式的消息。IoT Hub message assumes the following JSON representation of the message. 为所有用户添加系统属性并标识消息的内容。System properties are added for all users and identify content of the message. 用户可以有选择地向消息添加应用程序属性。Users can selectively add application properties to the message. 我们建议使用唯一的属性名称,因为 IoT 中心设备到云消息传递不区分大小写。We recommend using unique property names as IoT Hub device-to-cloud messaging is not case-sensitive. 例如,如果有多个具有相同名称的属性,IoT 中心将仅发送其中一个属性。For example, if you have multiple properties with the same name, IoT Hub will only send one of the properties.

  "message": { 
    "systemProperties": { 
      "contentType": "application/json", 
      "contentEncoding": "UTF-8", 
      "iothub-message-source": "deviceMessages", 
      "iothub-enqueuedtime": "2017-05-08T18:55:31.8514657Z" 
    "appProperties": { 
      "processingPath": "{cold | warm | hot}", 
      "verbose": "{true, false}", 
      "severity": 1-5, 
      "testDevice": "{true | false}" 
    "body": "{\"Weather\":{\"Temperature\":50}}" 

系统属性System properties

系统属性有助于标识消息的内容和源。System properties help identify contents and source of the messages.

propertiesProperty 类型Type 说明Description
contentTypecontentType 字符串string 用户指定消息的内容类型。The user specifies the content type of the message. 若要允许查询消息正文,此值应设置应用程序/JSON。To allow query on the message body, this value should be set application/JSON.
contentEncodingcontentEncoding 字符串string 用户指定消息的编码类型。The user specifies the encoding type of the message. 如果 contentType 设置为应用程序/JSON,则允许的值为 UTF-8、UTF-16 和 UTF-32。Allowed values are UTF-8, UTF-16, UTF-32 if the contentType is set to application/JSON.
iothub-connection-device-idiothub-connection-device-id 字符串string 此值由 IoT 中心设置,标识设备的 ID。This value is set by IoT Hub and identifies the ID of the device. 若要查询,请使用 $connectionDeviceIdTo query, use $connectionDeviceId.
iothub-enqueuedtimeiothub-enqueuedtime 字符串string 此值由 IoT 中心设置,表示 UTC 中消息排入队列的实际时间。This value is set by IoT Hub and represents the actual time of enqueuing the message in UTC. 若要查询,请使用 enqueuedTimeTo query, use enqueuedTime.
dt-dataschemadt-dataschema stringstring 此值是由 IoT 中心对设备到云的消息设置的。This value is set by IoT hub on device-to-cloud messages. 它包含在设备连接中设置的设备型号 ID。It contains the device model ID set in the device connection. 若要查询,请使用 $dt-dataschemaTo query, use $dt-dataschema.
dt-subjectdt-subject stringstring 正在发送设备到云的消息的组件名称。The name of the component that is sending the device-to-cloud messages. 若要查询,请使用 $dt-subjectTo query, use $dt-subject.

IoT 中心消息中所述,一条消息中还有其他系统属性。As described in the IoT Hub Messages, there are additional system properties in a message. 除了上一表中的上述属性外,还可以查询 connectionDeviceId、connectionModuleId。In addition to above properties in the previous table, you can also query connectionDeviceId, connectionModuleId.

应用程序属性Application properties

应用程序属性是用户定义的字符串,可以添加到消息。Application properties are user-defined strings that can be added to the message. 这些字段是可选的。These fields are optional.

查询表达式Query expressions

对消息系统属性的查询需要以 $ 符号为前缀。A query on message system properties needs to be prefixed with the $ symbol. 对应用程序属性的查询使用其名称进行访问,而且不应以 $ 符号为前缀。Queries on application properties are accessed with their name and should not be prefixed with the $symbol. 如果应用程序属性名称以 $ 开头,则 IoT 中心将在系统属性中搜索它,如果找不到,再在应用程序属性中查找。If an application property name begins with $, then IoT Hub will search for it in the system properties, and it is not found, then it will look in the application properties. 例如:For example:

查询系统属性 contentEncodingTo query on system property contentEncoding

$contentEncoding = 'UTF-8'

查询应用程序属性 processingPath:To query on application property processingPath:

processingPath = 'hot'

若要组合这些查询,可以使用布尔表达式和函数:To combine these queries, you can use Boolean expressions and functions:

$contentEncoding = 'UTF-8' AND processingPath = 'hot'

表达式和条件中显示了支持的运算符和函数的完整列表。A full list of supported operators and functions is shown in Expression and conditions.

基于消息正文的消息路由查询Message routing query based on message body

若要启用对消息正文的查询,消息应采用以 UTF-8、UTF-16 或 UTF-32 编码的 JSON 格式。To enable querying on message body, the message should be in a JSON encoded in either UTF-8, UTF-16 or UTF-32. 在系统属性中,contentType 必须设置为 application/JSON,而 contentEncoding 则设置为一个受支持的 UTF 编码。The contentType must be set to application/JSON and contentEncoding to one of the supported UTF encodings in the system property. 如果未指定这些属性,IoT 中心将不会计算消息正文的查询表达式。If these properties are not specified, IoT Hub will not evaluate the query expression on the message body.

下面的示例演示如何创建具有正确格式和编码 JSON 正文的消息:The following example shows how to create a message with a properly formed and encoded JSON body:

var messageBody = JSON.stringify(Object.assign({}, {
    "Weather": {
        "Temperature": 50,
        "Time": "2017-03-09T00:00:00.000Z",
        "PrevTemperatures": [
        "IsEnabled": true,
        "Location": {
            "Street": "One Microsoft Way",
            "City": "Redmond",
            "State": "WA"
        "HistoricalData": [
                "Month": "Feb",
                "Temperature": 40
                "Month": "Jan",
                "Temperature": 30

// Encode message body using UTF-8  
var messageBytes = Buffer.from(messageBody, "utf8");

var message = new Message(messageBytes);

// Set message body type and content encoding 
message.contentEncoding = "utf-8";
message.contentType = "application/json";

// Add other custom application properties"Status", "Active");

deviceClient.sendEvent(message, (err, res) => {
    if (err) console.log('error: ' + err.toString());
    if (res) console.log('status: ' +;


这说明了如何处理 javascript 中正文的编码。This shows how to handle the encoding of the body in javascript. 若要查看中 C# 的示例,请下载 Azure IoT C# 示例If you want to see a sample in C#, download the Azure IoT C# Samples. 解压缩 文件。Unzip the file. Visual Studio 解决方案 SimulatedDevice 的 Program.cs 文件演示如何编码以及如何将消息提交到 IoT 中心。The Visual Studio solution SimulatedDevice's Program.cs file shows how to encode and submit messages to an IoT Hub. 这是用于测试消息路由的同一示例,如消息路由教程中所述。This is the same sample used for testing the message routing, as explained in the Message Routing tutorial. 在 Program.cs 的底部,它还提供了一个方法,用于在其中一个编码文件中读取内容,对其进行解码,然后将其作为 ASCII 写回,方便你读取。At the bottom of Program.cs, it also has a method to read in one of the encoded files, decode it, and write it back out as ASCII so you can read it.

查询表达式Query expressions

对消息正文的查询需要以 $body 为前缀。A query on message body needs to be prefixed with the $body. 你可以在查询表达式中使用正文引用、正文数组引用或多个正文引用。You can use a body reference, body array reference, or multiple body references in the query expression. 查询表达式还可以将正文引用与消息系统属性和消息应用程序属性引用组合在一起。Your query expression can also combine a body reference with message system properties, and message application properties reference. 例如,以下所有查询表达式都有效:For example, the following are all valid query expressions:

$body.Weather.HistoricalData[0].Month = 'Feb' 
$body.Weather.Temperature = 50 AND $body.Weather.IsEnabled 
length($body.Weather.Location.State) = 2 
$body.Weather.Temperature = 50 AND processingPath = 'hot'

基于设备孪生的消息路由查询Message routing query based on device twin

通过消息路由,可以查询设备孪生标记和属性,这些是 JSON 对象。Message routing enables you to query on Device Twin tags and properties, which are JSON objects. 还支持对模块孪生进行查询。Querying on module twin is also supported. 设备孪生标记和属性的示例如下所示。A sample of Device Twin tags and properties is shown below.

    "tags": { 
        "deploymentLocation": { 
            "building": "43", 
            "floor": "1" 
    "properties": { 
        "desired": { 
            "telemetryConfig": { 
                "sendFrequency": "5m" 
            "$metadata" : {...}, 
            "$version": 1 
        "reported": { 
            "telemetryConfig": { 
                "sendFrequency": "5m", 
                "status": "success" 
            "batteryLevel": 55, 
            "$metadata" : {...}, 
            "$version": 4 

查询表达式Query expressions

对消息孪生的查询需要以 $twin 为前缀。A query on message twin needs to be prefixed with the $twin. 此外,查询表达式还可以将孪生标记或属性引用与正文引用、消息系统属性和消息应用程序属性引用组合在一起。Your query expression can also combine a twin tag or property reference with a body reference, message system properties, and message application properties reference. 我们建议在标记和属性中使用唯一名称,因为查询不区分大小写。We recommend using unique names in tags and properties as the query is not case-sensitive. 这同时适用于设备孪生和模块孪生。This applies to both device twins and module twins. 同时,请避免使用 twin$twinbody$body 作为属性名称。Also refrain from using twin, $twin, body, or $body, as a property names. 例如,以下所有查询表达式都有效:For example, the following are all valid query expressions:

$ = '5m'
$body.Weather.Temperature = 50 AND $ = '5m'
$twin.tags.deploymentLocation.floor = 1 

不支持在有效负载或属性名称中有句点的正文或设备孪生上路由查询。Routing query on body or device twin with a period in the payload or property name is not supported.

后续步骤Next steps