

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

# 为位置数据编制索引
<a name="location-indexing-geoquery"></a>

您可以使用 [AWS IoT 实例集索引](https://docs.aws.amazon.com//iot/latest/developerguide/iot-indexing.html)将设备上次发送的位置数据编入索引，并使用地理查询搜索设备。此特征解决了设备监控和管理使用案例，例如位置跟踪和邻近搜索。位置索引的工作原理与其他实例集索引特征类似，并且需要在[事物索引](managing-fleet-index.md)中指定其他配置。

常见使用案例包括：搜索和聚合位于所需地理边界内的设备；使用编入索引的数据来源中与设备元数据和状态相关的查询词获取特定位置的见解；提供精细视图，例如筛选特定地理区域的结果，以减少实例集监控地图中的渲染延迟并跟踪上次报告的设备位置；以及识别超出所需边界限制的设备并使用[实例集指标](iot-fleet-metrics.md)生成警报。要开始使用位置索引和地理查询，请参阅 [入门教程](location-indexing-tutorial.md)。

## 支持的数据格式
<a name="location-indexing-format"></a>

AWS IoT 舰队索引支持以下位置数据格式：

1. 

**坐标参考系的已知文本表示**

   遵循 [Geographic information - Well-known text representation of coordinate reference systems](https://docs.ogc.org/is/12-063r5/12-063r5.html) 格式的字符串。例如 `"POINT(long lat)"`。

1. 

**表示坐标的字符串**

   格式为 `"latitude, longitude"` 或 `"longitude, latitude"` 的字符串。如果使用 `"longitude, latitude"`，还必须指定在 `geoLocations` 中指定 `order`。例如 `"41.12,-71.34"`。

1. 

**由纬度、经度键组成的对象**

   这种格式适用于经典影子和命名影子。支持的键：`lat`、`latitude`、`lon`、`long`、`longitude`。例如 `{"lat": 41.12, "lon": -71.34}`。

1. 

**表示坐标的数组**

   格式为 `[lat,lon]` 或 `[lon,lat]` 的数组。如果您使用与 [GeoJSON](https://geojson.org/) 中的坐标相同的 `[lon,lat]` 格式（适用于经典影子和命名影子），则还必须在 `geoLocations` 中指定 `order`。

   例如：

   ```
   {
     "location": {
       "coordinates": [
         **Longitude**,
         **Latitude**
       ],
       "type": "Point",
       "properties": {
         "country": "United States",
         "city": "New York",
         "postalCode": "*****",
         "horizontalAccuracy": 20,
         "horizontalConfidenceLevel": 0.67,
         "state": "New York",
         "timestamp": "2023-01-04T20:59:13.024Z"
       }
     }
   }
   ```

## 如何为位置数据编制索引
<a name="location-indexing-steps"></a>

以下步骤说明如何更新位置数据的索引配置，以及如何使用地理查询来搜索设备。

1. 

**知道您的位置数据存储在什么位置**

   实例集索引目前支持为存储在经典影子或命名影子中的位置数据编制索引。

1. 

**使用支持的位置数据格式**

   确保您的位置数据格式遵循[支持的数据格式](#location-indexing-format)之一。

1. 

**更新索引配置**

   至少需要启用事物（注册表）索引配置。您还必须对包含您位置数据的经典影子或命名影子启用索引编制。更新事物索引时，应在索引配置中包含位置数据。

1. 

**创建并运行地理查询**

   根据您的使用案例，创建地理查询并运行这些查询来搜索设备。您编写的地理查询必须遵循[查询语法](https://docs.aws.amazon.com//iot/latest/developerguide/query-syntax.html)。您可以在 [地理查询示例](#location-indexing-geoqueries) 中找到一些示例。

## 更新事物索引配置
<a name="location-indexing-configuration"></a>

要为位置数据编制索引，您必须更新索引配置并包含您的位置数据。根据您位置数据的存储位置，请按照以下步骤更新您的索引配置：

### 位置数据存储在经典影子中
<a name="location-indexing-shadow-configuration"></a>

如果您的位置数据存储在经典影子中，则必须将 `thingIndexingMode` 设置为 `REGISTRY_AND_SHADOW`，并在 [https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html](https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html) 中的 `geoLocations` 字段（`name` 和 `order`）中指定您的位置数据。

在以下事物索引配置示例中，您可以将位置数据路径 `shadow.reported.coordinates` 指定为 `name`，将 `LonLat` 指定为 `order`。

```
{
	"thingIndexingMode": "REGISTRY_AND_SHADOW",
	"filter": {
		"geoLocations": [
			{
				"name": "shadow.reported.coordinates",
				"order": "LonLat"
			}
		]
	}
}
```
+ `thingIndexingMode`

  索引模式控制是否对注册表或影子编制索引。如果 `thingIndexingMode` 设置为 `OFF`，则禁用事物索引。

  要为存储在经典影子中的位置数据编制索引，必须将 `thingIndexingMode` 设置为 `REGISTRY_AND_SHADOW`。有关更多信息，请参阅 [事物索引模式](managing-index.md#index-mode)。
+ `filter`

  索引筛选器为命名影子和地理位置数据提供了其他选择。有关更多信息，请参阅 [索引筛选器](managing-index.md#thing-indexing-filter)。
+ `geoLocations`

  您选择要编制索引的地理位置目标列表。要编制索引的默认最大地理位置目标数量为 `1`。要提高限制，请参阅 [AWS IoT Device Management 限额](https://docs.aws.amazon.com//general/latest/gr/iot_device_management.html#fleet-indexing-limits)。
+ `name`

  地理位置目标字段的名称。`name` 的示例值可以是影子的位置数据路径：`shadow.reported.coordinates`。
+ `order`

  地理位置目标字段的顺序。有效值：`LatLon` 和 `LonLat`。`LatLon` 表示纬度和经度。`LonLat` 表示经度和纬度。该字段是可选的。默认值为 `LatLon`。

### 位置数据存储在命名影子中
<a name="location-indexing-named-shadow-configuration"></a>

如果您的位置数据存储在命名影子中，请将 `namedShadowIndexingMode` 设置为 `ON`，将您的命名影子名称添加到 [https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html](https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html) 的 `namedShadowNames` 字段中，并在 [https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html](https://docs.aws.amazon.com//iot/latest/apireference/API_IndexingFilter.html) 的 `geoLocations` 字段中指定您的位置数据路径。

在以下事物索引配置示例中，您可以将位置数据路径 `shadow.name.namedShadow1.reported.coordinates` 指定为 `name`，将 `LonLat` 指定为 `order`。

```
{
	"thingIndexingMode": "REGISTRY",
	"namedShadowIndexingMode": "ON",
	"filter": {
		"namedShadowNames": [
			"namedShadow1"
		],
		"geoLocations": [
			{
				"name": "shadow.name.namedShadow1.reported.coordinates",
				"order": "LonLat"
			}
		]
	}
}
```
+ `thingIndexingMode`

  索引模式控制是否对注册表或影子编制索引。如果 `thingIndexingMode` 设置为 `OFF`，则禁用事物索引。

  要为存储在命名影子中的位置数据编制索引，必须将 `thingIndexingMode` 设置为 `REGISTRY`（或 `REGISTRY_AND_SHADOW`）。有关更多信息，请参阅 [事物索引模式](managing-index.md#index-mode)。
+ `filter`

  索引筛选器为命名影子和地理位置数据提供了其他选择。有关更多信息，请参阅 [索引筛选器](managing-index.md#thing-indexing-filter)。
+ `geoLocations`

  您选择要编制索引的地理位置目标列表。要编制索引的默认最大地理位置目标数量为 `1`。要提高限制，请参阅 [AWS IoT Device Management 限额](https://docs.aws.amazon.com//general/latest/gr/iot_device_management.html#fleet-indexing-limits)。
+ `name`

  地理位置目标字段的名称。`name` 的示例值可以是影子的位置数据路径：`shadow.name.namedShadow1.reported.coordinates`。
+ `order`

  地理位置目标字段的顺序。有效值：`LatLon` 和 `LonLat`。`LatLon` 表示纬度和经度。`LonLat` 表示经度和纬度。该字段是可选的。默认值为 `LatLon`。

## 地理查询示例
<a name="location-indexing-geoqueries"></a>

完成位置数据的索引配置后，请运行地理查询来搜索设备。您也可以将地理查询与其他查询字符串合并。有关更多信息，请参阅[查询语法](query-syntax.md)和[事物查询示例](example-queries.md)。

**示例查询 1**

此示例假设位置数据存储在命名影子 `gps-tracker` 中。此命令的输出是距坐标为（47.6204,-122.3491）的中心点的径向距离在 15.5 千米内的设备列表。

```
aws iot search-index --query-string \
"shadow.name.gps-tracker.reported.coordinates:geo_distance,47.6204,-122.3491,15.5km"
```

**示例查询 2**

此示例假设位置数据存储在经典影子中。此命令的输出是距坐标为（47.6204,-122.3491）的中心点的径向距离在 15.5 千米内的设备列表。

```
aws iot search-index --query-string \
"shadow.reported.coordinates:geo_distance,47.6204,-122.3491,15.5km"
```

**示例查询 3**

此示例假设位置数据存储在经典影子中。此命令的输出是未连接且距坐标为（47.6204,-122.3491）的中心点的径向距离在 15.5 千米以外的设备列表。

```
aws iot search-index --query-string \
"connectivity.connected:false AND (NOT shadow.reported.coordinates:geo_distance,47.6204,-122.3491,15.5km)"
```

# 入门教程
<a name="location-indexing-tutorial"></a>

本教程演示了如何使用[实例集索引](iot-indexing.md)来[为您的位置数据编制索引](location-indexing-geoquery.md)。为简单起见，您可以创建一个代表您设备的事物，并将位置数据存储在命名影子中，更新位置索引的事物索引配置，并运行示例地理查询来搜索径向边界内的设备。

完成本教程需要大约 15 分钟。

**Topics**
+ [

## 先决条件
](#location-indexing-tutorial-prerequisites)
+ [

## 创建事物和影子
](#location-indexing-create-resources)
+ [

## 更新事物索引配置
](#location-indexing-update-configuration)
+ [

## 运行地理查询
](#location-indexing-run-geoquery)

## 先决条件
<a name="location-indexing-tutorial-prerequisites"></a>
+ 安装 [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) 的最新版本。
+ 自行熟悉[位置索引和地理查询](https://docs.aws.amazon.com/iot/latest/developerguide/location-indexing-geoquery.html)、[管理事物索引](https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html)和[查询语法](https://docs.aws.amazon.com/iot/latest/developerguide/query-syntax.html)。

## 创建事物和影子
<a name="location-indexing-create-resources"></a>

您可以创建一个代表您设备的事物，以及一个命名影子来存储其位置数据，坐标为（47.61564,-122.33584）。

1. 运行以下命令来创建代表您自行车（名为 Bike-1）的事物。*有关如何使用创建事物的更多信息 AWS CLI，请参阅通过参考[创建事物*AWS CLI*](https://docs.aws.amazon.com//cli/latest/reference/iot/create-thing.html)。*

   ```
   aws iot create-thing --thing-name "Bike-1" \
   --attribute-payload '{"attributes": {"model":"OEM-2302-12", "battery":"35", "acqDate":"06/09/23"}}'
   ```

   此命令的输出可能如下所示：

   ```
   {
       "thingName": "Bike-1",
       "thingArn": "arn:aws:iot:us-east-1:123456789012:thing/Bike-1",
       "thingId": "df9cf01d-b0c8-48fe-a2e2-e16cff6b23df"
   }
   ```

1. 运行以下命令创建一个命名影子来存储 Bike-1 的位置数据，坐标为（47.61564,-122.33584）。有关如何使用创建命名阴影的更多信息 AWS CLI，请参阅 “[update-thing-shadow](https://docs.aws.amazon.com//cli/latest/reference/iot-data/update-thing-shadow.html)参*AWS CLI**考*”。

   ```
   aws iot-data update-thing-shadow \
   --thing-name Bike-1 \
   --shadow-name Bike1-shadow \
   --cli-binary-format raw-in-base64-out \
   --payload '{"state":{"reported":{"coordinates":{"lat": 47.6153, "lon": -122.3333}}}}' \
   "output.txt" \
   ```

   此命令不会生成任何输出。要查看您创建的命名阴影，可以运行 [list-named-shadows-for-thing](https://docs.aws.amazon.com//cli/latest/reference/iot-data/list-named-shadows-for-thing.html) CLI 命令。

   ```
   aws iot-data list-named-shadows-for-thing --thing-name Bike-1
   ```

   此命令的输出可能如下所示：

   ```
   {
       "results": [
           "Bike1-shadow"
       ],
       "timestamp": 1699574309
   }
   ```

## 更新事物索引配置
<a name="location-indexing-update-configuration"></a>

要为位置数据编制索引，您必须更新您的事物索引配置，使其包含位置数据。由于您的位置数据存储在本教程中的命名影子中，请将 `thingIndexingMode` 设置为 `REGISTRY`（最低要求），将 `namedShadowIndexingMode` 设置为 `ON`，然后将您的位置数据添加到配置中。在此示例中，您必须将命名影子的名称和影子的位置数据路径添加到 `filter` 中。

1. 运行以下命令来更新位置索引的索引配置。

   ```
   aws iot update-indexing-configuration --cli-input-json '{
   "thingIndexingConfiguration": { "thingIndexingMode": "REGISTRY",
   "thingConnectivityIndexingMode": "OFF",
   "deviceDefenderIndexingMode": "OFF",
   "namedShadowIndexingMode": "ON",
   "filter": {
       "namedShadowNames": ["Bike1-shadow"],
       "geoLocations":[{
           "name":"shadow.name.Bike1-shadow.reported.coordinates"
       }]
   },
   "customFields": [
   { "name":"attributes.battery",
   "type":"Number"}] } }'
   ```

    命令不会生成任何输出。您可能需要稍等片刻，直到更新完成。要检查状态，请运行 [describe-index](https://docs.aws.amazon.com//cli/latest/reference/iot/describe-index.html) CLI 命令：如果您看到 `indexStatus` 显示 `ACTIVE`，则表示您的事物索引更新已完成。

1. 运行以下命令来验证您的索引配置。此为可选步骤。

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

   输出类似于以下内容：

   ```
   {
       "thingIndexingConfiguration": {
           "thingIndexingMode": "REGISTRY",
           "thingConnectivityIndexingMode": "OFF",
           "deviceDefenderIndexingMode": "OFF",
           "namedShadowIndexingMode": "ON",
           "managedFields": [
               {
                   "name": "shadow.name.*.hasDelta",
                   "type": "Boolean"
               },
               {
                   "name": "registry.version",
                   "type": "Number"
               },
               {
                   "name": "registry.thingTypeName",
                   "type": "String"
               },
               {
                   "name": "registry.thingGroupNames",
                   "type": "String"
               },
               {
                   "name": "shadow.name.*.version",
                   "type": "Number"
               },
               {
                   "name": "thingName",
                   "type": "String"
               },
               {
                   "name": "thingId",
                   "type": "String"
               }
           ],
           "customFields": [
               {
                   "name": "attributes.battery",
                   "type": "Number"
               }
           ],
           "filter": {
               "namedShadowNames": [
                   "Bike1-shadow"
               ],
               "geoLocations": [
                   {
                       "name": "shadow.name.Bike1-shadow.reported.coordinates",
                       "order": "LatLon"
                   }
               ]
           }
       },
       "thingGroupIndexingConfiguration": {
           "thingGroupIndexingMode": "OFF"
       }
   }
   ```

## 运行地理查询
<a name="location-indexing-run-geoquery"></a>

现在，您已经更新了事物索引配置，使其包含位置数据。请尝试创建一些地理查询，并运行这些查询以查看您是否可以获得所需的搜索结果。地理查询必须遵循[查询语法](query-syntax.md)。您可以在 [地理查询示例](location-indexing-geoquery.md#location-indexing-geoqueries) 中找到一些有用的地理查询示例。

在以下示例命令中，使用地理查询 `shadow.name.Bike1-shadow.reported.coordinates:geo_distance,47.6204,-122.3491,15.5km` 搜索距坐标为（47.6204,-122.3491）的中心点的径向距离在 15.5 千米以内的设备。

```
aws iot search-index --query-string "shadow.name.Bike1-shadow.reported.coordinates:geo_distance,47.6204,-122.3491,15.5km"
```

由于您设备的坐标纬度是 47.6153，经度是 -122.3333，距中心点的距离在 15.5 千米之内，因此您应该能够在输出中看到此设备（Bike-1）。输出类似于以下内容：

```
{
    "things": [
        {
            "thingName": "Bike-1",
            "thingId": "df9cf01d-b0c8-48fe-a2e2-e16cff6b23df",
            "attributes": {
                "acqDate": "06/09/23",
                "battery": "35",
                "model": "OEM-2302-12"
            },
            "shadow": "{\"reported\":{\"coordinates\":{\"lat\":47.6153,\"lon\":-122.3333}},\"metadata\":{\"reported\":{\"coordinates\":{\"lat\":{\"timestamp\":1699572906},\"lon\":{\"timestamp\":1699572906}}}},\"hasDelta\":false,\"version\":1}"
        }
    ]
}
```

有关更多信息，请参阅 [为位置数据编制索引](location-indexing-geoquery.md)。