

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 管理事物索引
<a name="managing-index"></a>

`AWS_Things` 是为您的所有事物创建的索引。您可以从以下数据源控制要索引的内容：[AWS IoT 注册表](thing-registry.md)数据，[AWS IoT 设备影子](iot-device-shadows.md)数据，[AWS IoT 连接](life-cycle-events.md)数据以及 [AWS IoT Device Defender](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/what-is-device-defender.html) 违规数据。

**Topics**
+ [启用事物索引](#enable-index)
+ [描述事物索引](#describe-index)
+ [查询事物索引](#search-index)
+ [限制和局限性](#index-limitations)
+ [Authorization](#query-auth)

## 启用事物索引
<a name="enable-index"></a>

您可以使用 [update-indexing-configuration](https://docs.aws.amazon.com/cli/latest/reference/iot/update-indexing-configuration.html)CLI 命令或 [UpdateIndexingConfiguration](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateIndexingConfiguration.html)API 操作来创建`AWS_Things`索引并控制其配置。`--thing-indexing-configuration` (`thingIndexingConfiguration`) 参数允许您控制建立索引的数据类型（例如，注册表、影子和设备连接数据和Device Defender 违规数据）。

`--thing-indexing-configuration` 参数采用具有以下结构的字符串：

```
{
  "thingIndexingMode": "OFF"|"REGISTRY"|"REGISTRY_AND_SHADOW",
  "thingConnectivityIndexingMode": "OFF"|"STATUS",
  "deviceDefenderIndexingMode": "OFF"|"VIOLATIONS",
  "namedShadowIndexingMode": "OFF"|"ON",
  "managedFields": [
    {
      "name": "string",
      "type": "Number"|"String"|"Boolean"
    }, 
    ...
  ], 
  "customFields": [
    { 
      "name": "string",
      "type": "Number"|"String"|"Boolean" 
    },
    ...
  ],
  "filter": {
     "namedShadowNames": [ "string" ],
     "geoLocations": [
        {
            "name": "String",
            "order": "LonLat|LatLon"
        }
    ]
  }
}
```

### 事物索引模式
<a name="index-mode"></a>

您可以在索引配置中指定不同的事物索引模式，具体取决于要从哪些数据来源编制索引和搜索设备：
+ `thingIndexingMode`：控制是否为注册表或影子编制索引。如果 `thingIndexingMode` 设置为 `OFF`，则禁用事物索引。
+ `thingConnectivityIndexingMode`：指定是否为事物连接数据编制索引。
+ `deviceDefenderIndexingMode`：指定是否为 Device Defender 违规数据编制索引。
+ `namedShadowIndexingMode`：指定是否为命名影子数据编制索引。要选择要添加到实例集索引配置的命名影子，请将 `namedShadowIndexingMode` 设置为 `ON`并在 [https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html](https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html) 中指定命名的影子名称。

下表显示了每种索引模式的有效值以及为每个值编入索引的数据来源。


****  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/managing-index.html)

### 托管字段和自定义字段
<a name="managed-custom-field"></a>

**托管字段**

托管字段包含与事物、事物组、设备影子、设备连接和 Device Defender 违规相关的数据。 AWS IoT 定义托管字段中的数据类型。您可以在创建 AWS IoT 事物时指定每个托管式字段的值。例如，事物名称、事物组和事物描述都是托管字段。实例集索引根据您指定的索引模式为托管式字段编制索引。托管字段无法更改或显示在 `customFields` 中。

**自定义字段**

您可以通过创建自定义字段来对属性、Device Shadow 数据和 Device Defender 违规数据进行汇总来进行索引。`customFields` 属性是字段名称和数据类型对的列表。您可以根据数据类型执行聚合查询。您选择的索引模式会影响可以在 `customFields` 中指定的字段。例如，如果您指定 `REGISTRY` 索引模式，则无法从事物影子中指定字段。您可以使用 [update-indexing-configuration](https://docs.aws.amazon.com/cli/latest/reference/iot/update-indexing-configuration.html)CLI 命令创建或更新自定义字段（参见[更新索引配置示例中的示例](#update-index-examples)命令）。有关更多信息，请参阅[自定义字段](managing-fleet-index.md#custom-field)。

### 索引筛选器
<a name="thing-indexing-filter"></a>

索引筛选器为命名影子和地理位置数据提供了其他选择。

**`namedShadowNames`**

要将命名影子添加到实例集索引配置，请将 `namedShadowIndexingMode` 设置为 `ON`，并在 `namedShadowNames` 中指定命名影子名称。

**示例**

```
"filter": {
     "namedShadowNames": [ "namedShadow1", "namedShadow2" ]
}
```

`geoLocations`

要将地理位置数据添加到实例集索引配置，请执行以下操作：
+ 如果您的地理位置数据存储在经典（未命名）影子中，请将 `thingIndexingMode` 设置为 REGISTRY\$1AND\$1SHADOW，并在 `geoLocations` 筛选器中指定您的地理位置数据。

  下面的示例筛选器在经典（未命名）影子中指定了 geoLocation 对象：

  ```
  "filter": {
       "geoLocations": [
          {
              "name": "shadow.reported.location",
              "order": "LonLat"
          }
       ]
    }
  ```
+ 如果您的地理位置数据存储在命名影子中，请 `namedShadowIndexingMode` 设置为“开启”，在 `namedShadowNames` 筛选器中添加影子名称，然后在 `geoLocations` 筛选器中指定您的地理位置数据。

  下面的示例筛选器在命名影子（`nameShadow1`）中指定了 geoLocation 对象：

  ```
  "filter": {
       "namedShadowNames": [ "namedShadow1" ],
       "geoLocations": [
          {
              "name": "shadow.name.namedShadow1.reported.location",
              "order": "LonLat"
          }
       ]
    }
  ```

有关更多信息，请参阅《*AWS IoT**API [ IndexingFilter](https://docs.aws.amazon.com/iot/latest/apireference/API_IndexingFilter.html)参考*》。

### 更新索引配置示例
<a name="update-index-examples"></a>

要更新您的索引配置，请使用 AWS IoT **update-indexing-configuration** CLI 命令。以下示例显示了如何使用 **update-indexing-configuration** 标签。

简短语法：

```
aws iot update-indexing-configuration --thing-indexing-configuration \
'thingIndexingMode=REGISTRY_AND_SHADOW, deviceDefenderIndexingMode=VIOLATIONS, 
namedShadowIndexingMode=ON,filter={namedShadowNames=[thing1shadow]}, thingConnectivityIndexingMode=STATUS,
customFields=[{name=attributes.version,type=Number},
{name=shadow.name.thing1shadow.desired.DefaultDesired, type=String}, {name=shadow.desired.power, type=Boolean}, 
{name=deviceDefender.securityProfile1.NUMBER_VALUE_BEHAVIOR.lastViolationValue.number, type=Number}]'
```

JSON 语法：

```
aws iot update-indexing-configuration --cli-input-json \ '{
          "thingIndexingConfiguration": { "thingIndexingMode": "REGISTRY_AND_SHADOW",
          "thingConnectivityIndexingMode": "STATUS", 
          "deviceDefenderIndexingMode": "VIOLATIONS",
          "namedShadowIndexingMode": "ON",
          "filter": { "namedShadowNames": ["thing1shadow"]},
          "customFields": [ { "name": "shadow.desired.power", "type": "Boolean" }, 
          {"name": "attributes.version", "type": "Number"}, 
          {"name": "shadow.name.thing1shadow.desired.DefaultDesired", "type": "String"}, 
          {"name": "deviceDefender.securityProfile1.NUMBER_VALUE_BEHAVIOR.lastViolationValue.number", "type": Number} ] } }'
```

此命令不会生成任何输出。

要检查事物索引状态，请运行 `describe-index` CLI 命令：

```
aws iot describe-index --index-name "AWS_Things"
```

`describe-index` 命令的输出如下所示：

```
{
    "indexName": "AWS_Things",
    "indexStatus": "ACTIVE",
    "schema": "MULTI_INDEXING_MODE"
}
```

**注意**  
实例集索引可能需要一点时间才能更新实例集指数。我们建议 `indexStatus` 在使用之前显示 ACTIVE。根据配置的数据来源，您可以在模式字段中具有不同的值。有关更多信息，请参阅[描述事物索引](#describe-index)。

要获取事物索引配置详细信息，请运行 `get-indexing-configuration` CLI 命令：

```
aws iot get-indexing-configuration
```

`get-indexing-configuration` 命令的输出如下所示：

```
{
    "thingIndexingConfiguration": {
        "thingIndexingMode": "REGISTRY_AND_SHADOW",
        "thingConnectivityIndexingMode": "STATUS",
        "deviceDefenderIndexingMode": "VIOLATIONS",
        "namedShadowIndexingMode": "ON",
        "managedFields": [
            {
                "name": "connectivity.disconnectReason",
                "type": "String"
            },
            {
                "name": "registry.version",
                "type": "Number"
            },
            {
                "name": "thingName",
                "type": "String"
            },
            {
                "name": "deviceDefender.violationCount",
                "type": "Number"
            },
            {
                "name": "shadow.hasDelta",
                "type": "Boolean"
            },
            {
                "name": "shadow.name.*.version",
                "type": "Number"
            },
            {
                "name": "shadow.version",
                "type": "Number"
            },
            {
                "name": "connectivity.version",
                "type": "Number"
            },
            {
                "name": "connectivity.timestamp",
                "type": "Number"
            },
            {
                "name": "shadow.name.*.hasDelta",
                "type": "Boolean"
            },
            {
                "name": "registry.thingTypeName",
                "type": "String"
            },
            {
                "name": "thingId",
                "type": "String"
            },
            {
                "name": "connectivity.connected",
                "type": "Boolean"
            },
            {
                "name": "registry.thingGroupNames",
                "type": "String"
            }
        ],
        "customFields": [
            {
                "name": "shadow.name.thing1shadow.desired.DefaultDesired",
                "type": "String"
            },

            {
                "name": "deviceDefender.securityProfile1.NUMBER_VALUE_BEHAVIOR.lastViolationValue.number",
                "type": "Number"
            },
            {
                "name": "shadow.desired.power",
                "type": "Boolean"
            },
            {
                "name": "attributes.version",
                "type": "Number"
            }
        ], 
        "filter": {
              "namedShadowNames": [
                  "thing1shadow"
              ]
          }
      },
    "thingGroupIndexingConfiguration": {
        "thingGroupIndexingMode": "OFF"
    }
}
```

要更新自定义字段，可以运行 `update-indexing-configuration` 命令。示例如下：

```
aws iot update-indexing-configuration --thing-indexing-configuration
          'thingIndexingMode=REGISTRY_AND_SHADOW,customFields=[{name=attributes.version,type=Number},{name=attributes.color,type=String},{name=shadow.desired.power,type=Boolean},{name=shadow.desired.intensity,type=Number}]'
```

此命令已将 `shadow.desired.intensity` 添加到索引配置中。

**注意**  
更新自定义字段索引配置将覆盖所有现有的自定义字段。请确保在调用 **update-indexing-configuration** 时指定所有自定义字段。

重建索引后，您可以对新添加的字段、搜索注册表数据、影子数据和事物连接状态数据使用聚合查询。

更改索引模式时，请使用新的索引模式以确保所有自定义字段均有效。例如，如果从 `REGISTRY_AND_SHADOW` 模式开始使用名为 `shadow.desired.temperature` 的自定义字段，则必须先删除 `shadow.desired.temperature` 自定义字段，然后再将索引模式更改为 `REGISTRY`。如果您的索引配置包含未通过索引模式建立索引的自定义字段，则更新失败。

## 描述事物索引
<a name="describe-index"></a>

以下命令说明了如何使用 **describe-index** CLI 命令来检索事物索引的当前状态。

```
aws iot describe-index --index-name "AWS_Things"
```

命令的响应如下所示：

```
{
    "indexName": "AWS_Things", 
    "indexStatus": "BUILDING", 
    "schema": "REGISTRY_AND_SHADOW_AND_CONNECTIVITY_STATUS"
}
```

首次为舰队编制索引时， AWS IoT 会生成索引。如果 `indexStatus` 处于 `BUILDING` 状态，您无法查询索引。事物索引的 `schema` 指示将对什么类型的数据 (`REGISTRY_AND_SHADOW_AND_CONNECTIVITY_STATUS`) 建立索引。

更改索引的配置会导致重新生成索引。此过程中的 `indexStatus` 为 `REBUILDING`。在重建期间，您可以对事物索引中的数据运行查询。例如，如果您将索引配置从 `REGISTRY` 更改为 `REGISTRY_AND_SHADOW`，同时正在重新生成索引，则您可以查询注册表数据，包括最新的更新。但是，在重新生成操作完成之前，无法查询影子数据。生成或重新生成索引所需的时间量取决于数据量。

根据配置的数据来源，您可能在模式字段中看到不同的值。下表显示了不同的模式值和相应的说明：


| 架构 | 说明 | 
| --- | --- | 
| OFF | 没有配置或索引数据源。 | 
| REGISTRY | 对注册表数据建立索引。 | 
| REGISTRY\$1AND\$1SHADOW | 对注册表数据和未命名（经典）影子数据建立索引。 | 
| REGISTRY\$1AND\$1CONNECTIVITY | 为注册数据和连接数据建立索引。 | 
| REGISTRY\$1AND\$1SHADOW\$1AND\$1CONNECTIVITY\$1STATUS | 对注册表数据、未命名（典型）影子数据和连接数据都建立了索引。 | 
| MULTI\$1INDEXING\$1MODE | 除了注册表、未命名（经典）影子或连接数据之外，也对命名影子或 Device Defender 违规数据建立了索引。 | 

## 查询事物索引
<a name="search-index"></a>

使用 **search-index** CLI 命令可查询索引中的数据。

```
aws iot search-index --index-name "AWS_Things" --query-string
          "thingName:mything*"
```

```
{  
    "things":[{  
         "thingName":"mything1",
         "thingGroupNames":[  
            "mygroup1"
         ],
         "thingId":"a4b9f759-b0f2-4857-8a4b-967745ed9f4e",
         "attributes":{  
            "attribute1":"abc"
         },
         "connectivity": { 
            "connected":false,
            "timestamp":1556649874716,
            "disconnectReason": "CONNECTION_LOST"
         }         
    },
    {  
        "thingName":"mything2",
        "thingTypeName":"MyThingType",
        "thingGroupNames":[  
            "mygroup1",
            "mygroup2"
        ],
        "thingId":"01014ef9-e97e-44c6-985a-d0b06924f2af",
        "attributes":{  
            "model":"1.2",
            "country":"usa"
        },
        "shadow":{  
            "desired":{  
                "location":"new york",
                "myvalues":[3, 4, 5]
            },
            "reported":{  
                "location":"new york",
                "myvalues":[1, 2, 3],
                "stats":{  
                    "battery":78
                }
            },
            "metadata":{  
                 "desired":{  
                       "location":{  
                            "timestamp":123456789
                        },
                       "myvalues":{  
                             "timestamp":123456789
                       }
                  },
                  "reported":{  
                        "location":{  
                             "timestamp":34535454
                         },
                        "myvalues":{  
                             "timestamp":34535454
                        },
                        "stats":{  
                             "battery":{  
                                   "timestamp":34535454
                             }
                        }
                 }
            },
            "version":10,
            "timestamp":34535454
        },
        "connectivity": { 
            "connected":true,
            "timestamp":1556649855046
        }        
    }],
    "nextToken":"AQFCuvk7zZ3D9pOYMbFCeHbdZ+h=G"
}
```

在 JSON 响应中，`"connectivity"`（由 `thingConnectivityIndexingMode=STATUS` 设置启用）提供了一个布尔值、时间戳和 disconnectReason（用于指示设备是否连接到 AWS IoT Core）。出于 `CONNECTION_LOST` 原因，设备 `"mything1"` 在 POSIX 时间 `1556649874716` 断开连接 (`false`)。有关断开原因的更多信息，请参阅[生命周期事件](life-cycle-events.md)。

```
"connectivity": { 
    "connected":false,
    "timestamp":1556649874716, 
    "disconnectReason": "CONNECTION_LOST"
}
```

设备 `"mything2"` 在 POSIX 时间 `1556649855046` 连接 (`true`)：

```
"connectivity": { 
    "connected":true,
    "timestamp":1556649855046
}
```

时间戳以自纪元以来的毫秒数表示，因此 `1556649855046` 表示 2019 年 4 月 30 日星期二上午 6:44:15.046（UTC）。

**重要**  
如果设备已断开连接大约一小时，则连接状态的 `"timestamp"` 值和 `"disconnectReason"` 值可能会缺失。

## 限制和局限性
<a name="index-limitations"></a>

`AWS_Things` 具有这些限制。

**具有复杂类型的影子字段**  
只有字段的值是简单类型、不包含数组的 JSON 对象或完全由简单类型组成的数组时，才会对影子字段编制索引。“简单类型”是指字符串、数字或文本 `true` 或 `false` 之一。例如，如果是以下影子状态，则系统将不会编制索引字段 `"palette"` 的值，因为它是一个包含复杂类型项目的数组。字段 `"colors"` 的值将会编制索引，因为该数组中的每个值都是一个字符串。  

```
{
    "state": {
        "reported": {
            "switched": "ON",
            "colors": [ "RED", "GREEN", "BLUE" ],
            "palette": [
                {
                    "name": "RED", 
                    "intensity": 124
                },
                {
                    "name": "GREEN", 
                    "intensity": 68
                },
                {
                    "name": "BLUE", 
                    "intensity": 201
                }
            ]
        }
    }
}
```

**嵌套影子字段名称**  
嵌套影子字段的名称存储为以句点 (.) 分隔的字符串。例如，假设存在以下影子文档：  

```
{
  "state": {
    "desired": {
      "one": {
        "two": {
          "three": "v2"
        }
      }
    }    
  }
}
```
字段 `three` 的名称存储为 `desired.one.two.three`。如果您还有影子文档，存储方式如下：  

```
{
  "state": {
    "desired": {
      "one.two.three": "v2"
    }    
  }
}
```
都匹配 `shadow.desired.one.two.three:v2` 的查询。最佳实践是不要在影子字段名称中使用句点。

**影子元数据**  
影子的元数据部分中的字段编制了索引，但仅当影子的 `"state"` 部分中的相应字段编制了索引时才会出现这种情况。（在之前的示例中，影子的元数据部分中的 `"palette"` 字段也不会编制索引。）

**未注册的设备**  
实例集索引对设备的连接状态编制索引，该设备的连接 `clientId` 与[注册表](https://docs.aws.amazon.com//iot/latest/developerguide/thing-registry.html)中已注册事物的 `thingName` 相同。

**未注册的影子**  
如果您使用[UpdateThingShadow](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdata_UpdateThingShadow.html)尚未在 AWS IoT 账户中注册的事物名称创建影子，则不会为该影子中的字段编制索引。这适用于经典的未命名影子和命名影子。

**数字值**  
如果任何注册表或影子数据被服务识别为数值，则会对其照此编制索引。您可以针对数字值创建涉及范围和比较运算符的查询（例如 `"attribute.foo<5"` 或 `"shadow.reported.foo:[75 TO 80]"`）。要识别为数字，数据的值必须是有效的文字类型 JSON 数字。该值可以是2^53...2^53-1范围内的整数，具有可选指数表示法的双精度浮点，或仅包含这些值的数组的一部分。

**Null 值**  
未对 Null 值建立索引。

**最大值**  
聚合查询的最大自定义字段数是 5。  
聚合查询请求的最大百分位数是 100。

## Authorization
<a name="query-auth"></a>

您可以在 AWS IoT 策略操作中将事物索引指定为 Amazon 资源名称 (ARN)，如下所示。


****  

| Action | 资源 | 
| --- | --- | 
|  `iot:SearchIndex`  |  索引 ARN（例如，`arn:aws:iot:your-aws-regionyour-aws-account:index/AWS_Things`）。  | 
|  `iot:DescribeIndex`  |  索引 ARN（例如，`arn:aws:iot:your-aws-region:index/AWS_Things`）。  | 

**注意**  
如果您有权查询机群索引，可以访问整个机群的事物数据。