

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

# 在 DynamoDB AWS CLI 中使用本機次要索引
<a name="LCICli"></a>

您可以使用 AWS CLI 建立含有一或多個本機次要索引的 Amazon DynamoDB 資料表、描述資料表上的索引，以及使用索引執行查詢。

**Topics**
+ [使用本機次要索引建立資料表](#LCICli.CreateTableWithIndex)
+ [使用本機次要索引描述資料表](#LCICli.DescribeTableWithIndex)
+ [查詢本機次要索引](#LCICli.QueryAnIndex)

## 使用本機次要索引建立資料表
<a name="LCICli.CreateTableWithIndex"></a>

您必須同時建立資料表和本機次要索引。若要執行這項操作，請使用 `create-table` 參數，並提供一或多個本機次要索引的規格。以下範例會建立資料表 (`Music`) 來保存音樂收藏中歌曲的相關資訊。分割區索引鍵為 `Artist`，而排序索引鍵為 `SongTitle`。`AlbumTitle` 屬性上的次要索引 `AlbumTitleIndex` 有助於依照專輯標題查詢。

```
aws dynamodb create-table \
    --table-name Music \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
        AttributeName=AlbumTitle,AttributeType=S  \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput \
        ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --local-secondary-indexes \
        "[{\"IndexName\": \"AlbumTitleIndex\",
        \"KeySchema\":[{\"AttributeName\":\"Artist\",\"KeyType\":\"HASH\"},
                      {\"AttributeName\":\"AlbumTitle\",\"KeyType\":\"RANGE\"}],
        \"Projection\":{\"ProjectionType\":\"INCLUDE\",  \"NonKeyAttributes\":[\"Genre\", \"Year\"]}}]"
```

您必須等到 DynamoDB 建立資料表，並將資料表狀態設定為 `ACTIVE`。之後，您可以開始將資料項目放入資料表中。您可以使用 [describe-table](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/describe-table.html) 來判斷資料表建立的狀態。

## 使用本機次要索引描述資料表
<a name="LCICli.DescribeTableWithIndex"></a>

若要取得資料表上本機次要索引的資訊，請使用 `describe-table` 參數。對於每個索引，您可以存取其名稱、索引鍵結構描述和投影屬性。

```
aws dynamodb describe-table --table-name Music
```

## 查詢本機次要索引
<a name="LCICli.QueryAnIndex"></a>

您可以依照與 `query` 資料表大致相同的方式在本機次要索引上使用 `query` 操作。您必須指定索引名稱、索引排序索引鍵的查詢準則，以及您要傳回的屬性。在本例中，索引是 `AlbumTitleIndex`，而索引排序索引鍵為 `AlbumTitle`。

傳回的唯一屬性是已投影到索引的屬性。您也可以修改此查詢來選擇非索引鍵屬性，但這需要相對昂貴的資料表擷取活動。如需資料表擷取的詳細資訊，請參閱 [屬性投影](LSI.md#LSI.Projections)。

```
aws dynamodb query \
    --table-name Music \
    --index-name AlbumTitleIndex \
    --key-condition-expression "Artist = :v_artist and AlbumTitle = :v_title" \
    --expression-attribute-values  '{":v_artist":{"S":"Acme Band"},":v_title":{"S":"Songs About Life"} }'
```