

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

# 第 6 步：创建数据查询
<a name="step6-hierarchical-model"></a>

定义访问模式并设计数据模型后，可以在 DynamoDB 数据库中查询层次数据。作为节省成本和确保性能的最佳实践，以下示例仅使用无 `Scan` 的查询操作。
+ **查找组件的祖先。**

  要查找 CM8组件的祖先（父母、祖父母、曾祖父母等），请使用查询基表。`ComponentId = "CM8"`查询将返回以下记录。

  要减小结果数据的大小，您可以使用投影表达式仅返回 `Path` 属性。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)
+ **查找组件的直系子组件。**

  要获取该组件的所有直接子组件或下游单级组 CM2件，请 GSI1 使用`ParentId = "CM2"`查询。查询将返回以下记录。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)
+ **使用顶部组件查找所有下游子组件。**

  要获取顶级组件的所有子组件或下游组件 CM1，请 GSI2使用`GraphId = "CM1#1"`和进行查询`begins_with("Path", "CM1|")`，然后使用带的投影表达式`ComponentId`。它将返回与该树相关的所有组件。

  这个例子只有一棵树， CM1 作为顶部组件。实际上，同一个表中可能有数百万个顶部组件。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)
+ **使用中间组件查找所有下游子组件。**

  要递归获取组件的所有子组件或下游组件 CM2，您有两个选择。您可以逐级递归查询，也可以查询 GSI2索引。
  + 逐级递归查询 GSI1，直到达到子组件的最后一级。

    1.  GSI1 使用查询`ParentId = "CM2"`。这将返回以下记录。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 再说一遍， GSI1 使用查询`ParentId = "CM4"`。这将返回以下记录。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 再说一遍， GSI1 使用查询`ParentId = "CM5"`。这将返回以下记录。

       继续循环：查询每个 `ComponentId`，直至到达最后一级。当使用 `ParentId = "<ComponentId>"` 查询未返回任何结果时，上一个结果来自树的最后一级。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 合并所有结果。

        

       结果= [CM4, CM5] \$1 [,] \$1 [CM8 CM9] \$1 [] CM10

                =[CM4, CM5, CM8, CM9, CM10]
  + 查询 GSI2，它存储顶级组件（汽车或 CM1）的分层树。

    1. 首先，找到顶级组件或顶级祖先和`Path`。 CM2为此，使用 `ComponentId = "CM2"` 查询基表，在层次树中找到该组件的路径。选择 `GraphId` 和 `Pat`h 属性。查询将返回以下记录。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1.  GSI2 使用查询`GraphId = "CM1#1" AND BEGINS_WITH("Path", "CM1|CM2|")`。查询将返回以下结果。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 选择要返回其所有子组件的`ComponentId`属性 CM2。