

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 步驟 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_tw/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)
+ **使用頂層元件尋找所有下游子元件。**

  若要取得頂層元件 CM1 的所有子元件或下游元件，請使用 `GraphId = "CM1#1"`和 查詢 GSI2`begins_with("Path", "CM1|")`，並使用投影表達式搭配 `ComponentId`。它將傳回與該樹狀目錄相關的所有元件。

  此範例具有單一樹狀目錄，其中 CM1 為頂端元件。實際上，您在相同表格中可能具有數百萬個頂層元件。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)
+ **使用中階元件尋找所有下游子元件。**

  若要以遞迴方式取得元件 CM2 的所有子元件或下游元件，您有兩個選項。您可以用遞迴方式逐層查詢，也可以查詢 GSI2 索引。
  + 以遞迴方式逐層查詢 GSI1，直到到達最後一層子元件。

    1. 使用 `ParentId = "CM2"` 查詢 GSI1。它將傳回下列記錄。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 再次使用 `ParentId = "CM4"` 查詢 GSI1。它將傳回下列記錄。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 再次使用 `ParentId = "CM5"` 查詢 GSI1。它將傳回下列記錄。

       繼續循環：查詢每個 `ComponentId`，直到到達最後一層。使用 `ParentId = "<ComponentId>"` 的查詢未傳回任何結果時，先前的結果來自樹狀目錄的最後一層。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 合併所有結果。

        

       result=【CM4， CM5】 \$1 【CM8， CM9】 \$1 【CM10】

                =【CM4、CM5, CM8, CM9, CM10】
  + 查詢 GSI2，它儲存頂層元件 (汽車或 CM1) 的階層樹狀目錄。

    1. 首先，尋找頂層元件或頂級上階和 CM2 的 `Path`。為此，使用 `ComponentId = "CM2"` 查詢基本資料表，以尋找階層樹狀目錄中該元件的路徑。選取 `GraphId`和 `Pat`h 屬性。此查詢會傳回下列記錄。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/dynamodb-data-modeling/step6-hierarchical-model.html)

    1. 選取 `ComponentId` 屬性，以傳回 CM2 的所有子元件。