

# グローバルセカンダリインデックスの操作: .NET
<a name="GSILowLevelDotNet"></a>

AWS SDK for .NET 低レベル API を使用して、1 つ以上のグローバルセカンダリインデックスを含む Amazon DynamoDB テーブルを作成し、テーブルのインデックスを記述し、インデックスを使用してクエリを実行できます。これらのオペレーションは、対応する DynamoDB オペレーションにマッピングされます。詳細については、「[Amazon DynamoDB API リファレンス](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/)」を参照してください。

以下に、.NET 低レベル API を使用したテーブルオペレーションの一般的な手順を示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. 対応するリクエストオブジェクトを作成して、オペレーションについて必要なパラメータとオプションパラメータを入力します。

   たとえば、テーブルを作成するには `CreateTableRequest` オブジェクトを作成し、テーブルやインデックスにクエリを実行するには `QueryRequest` オブジェクトを作成します。

1. 前述のステップで作成したクライアントから提供された適切なメソッドを実行します。

**Topics**
+ [グローバルセカンダリインデックスを持つテーブルを作成します](#GSILowLevelDotNet.CreateTableWithIndex)
+ [グローバルセカンダリインデックスを持つテーブルの説明](#GSILowLevelDotNet.DescribeTableWithIndex)
+ [グローバルセカンダリインデックスのクエリ](#GSILowLevelDotNet.QueryAnIndex)
+ [例: AWS SDK for .NET 低レベル API を使用したグローバルセカンダリインデックス](GSILowLevelDotNet.Example.md)

## グローバルセカンダリインデックスを持つテーブルを作成します
<a name="GSILowLevelDotNet.CreateTableWithIndex"></a>

グローバルセカンダリインデックスは、テーブルの作成と同時に作成できます。これを行うには、`CreateTable` を使用し、1 つ以上のグローバルセカンダリインデックスの仕様を指定します。次の C\# コード例では、気象データに関する情報を保持するテーブルを作成しています。パーティションキーは `Location` で、ソートキーは `Date` です。グローバルセカンダリインデックス `PrecipIndex` は、さまざまな場所の降水データへの高速アクセスを可能にします。

.NET 低レベル API を使用して、グローバルセカンダリインデックスを含むテーブルを作成する手順を次に示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. リクエスト情報を指定する `CreateTableRequest` クラスのインスタンスを作成します。

   テーブル名、プライマリキー、およびプロビジョニングされたスループット値を指定する必要があります。グローバルセカンダリインデックスの場合は、インデックス名、プロビジョニングされたスループット設定、インデックスソートキーの属性定義、インデックスのキースキーマ、および属性射影を指定する必要があります。

1. リクエストオブジェクトをパラメータとして指定して、`CreateTable` メソッドを実行します。

以下の C\# サンプルコードは、前述のステップの例です。このコードは、グローバルセカンダリインデックス (`PrecipIndex`) を持つテーブル (`WeatherData`) を作成します。インデックスパーティションキーは `Date` で、ソートキーは `Precipitation` です。すべてのテーブル属性がインデックスに射影されます。ユーザーは、このインデックスに対するクエリを実行して、特定の日付の気象データを取得できます。必要に応じて、降水量によってデータを並べ替えることもできます。

`Precipitation` はテーブルのキー属性ではないため、必須ではありません。ただし、`Precipitation` のない `WeatherData` 項目は `PrecipIndex` に表示されません。

```
client = new AmazonDynamoDBClient();
string tableName = "WeatherData";

// Attribute definitions
var attributeDefinitions = new List<AttributeDefinition>()
{
    {new AttributeDefinition{
        AttributeName = "Location",
        AttributeType = "S"}},
    {new AttributeDefinition{
        AttributeName = "Date",
        AttributeType = "S"}},
    {new AttributeDefinition(){
        AttributeName = "Precipitation",
        AttributeType = "N"}
    }
};

// Table key schema
var tableKeySchema = new List<KeySchemaElement>()
{
    {new KeySchemaElement {
        AttributeName = "Location",
        KeyType = "HASH"}},  //Partition key
    {new KeySchemaElement {
        AttributeName = "Date",
        KeyType = "RANGE"}  //Sort key
    }
};

// PrecipIndex
var precipIndex = new GlobalSecondaryIndex
{
    IndexName = "PrecipIndex",
    ProvisionedThroughput = new ProvisionedThroughput
    {
        ReadCapacityUnits = (long)10,
        WriteCapacityUnits = (long)1
    },
    Projection = new Projection { ProjectionType = "ALL" }
};

var indexKeySchema = new List<KeySchemaElement> {
    {new KeySchemaElement { AttributeName = "Date", KeyType = "HASH"}},  //Partition key
    {new KeySchemaElement{AttributeName = "Precipitation",KeyType = "RANGE"}}  //Sort key
};

precipIndex.KeySchema = indexKeySchema;

CreateTableRequest createTableRequest = new CreateTableRequest
{
    TableName = tableName,
    ProvisionedThroughput = new ProvisionedThroughput
    {
        ReadCapacityUnits = (long)5,
        WriteCapacityUnits = (long)1
    },
    AttributeDefinitions = attributeDefinitions,
    KeySchema = tableKeySchema,
    GlobalSecondaryIndexes = { precipIndex }
};

CreateTableResponse response = client.CreateTable(createTableRequest);
Console.WriteLine(response.CreateTableResult.TableDescription.TableName);
Console.WriteLine(response.CreateTableResult.TableDescription.TableStatus);
```

DynamoDB がテーブルを作成し、テーブルのステータスを `ACTIVE` に設定するまで待機する必要があります。その後、テーブルへのデータ項目の入力を開始できます。

## グローバルセカンダリインデックスを持つテーブルの説明
<a name="GSILowLevelDotNet.DescribeTableWithIndex"></a>

テーブルでグローバルセカンダリインデックスに関する情報を取得するには、`DescribeTable` を使用します。インデックスごとに、名前、キースキーマ、および射影された属性にアクセスできます。

.NET 低レベル API を使用してテーブルのグローバルセカンダリインデックス情報にアクセスするには次の手順に従います。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. リクエストオブジェクトをパラメータとして指定して、`describeTable` メソッドを実行します。

   リクエスト情報を指定する `DescribeTableRequest` クラスのインスタンスを作成します。テーブル名を入力する必要があります。

以下の C\# サンプルコードは、前述のステップの例です。

**Example**  

```
client = new AmazonDynamoDBClient();
string tableName = "WeatherData";

DescribeTableResponse response = client.DescribeTable(new DescribeTableRequest { TableName = tableName});

List<GlobalSecondaryIndexDescription> globalSecondaryIndexes =
response.DescribeTableResult.Table.GlobalSecondaryIndexes;

// This code snippet will work for multiple indexes, even though
// there is only one index in this example.

foreach (GlobalSecondaryIndexDescription gsiDescription in globalSecondaryIndexes) {
     Console.WriteLine("Info for index " + gsiDescription.IndexName + ":");

     foreach (KeySchemaElement kse in gsiDescription.KeySchema) {
          Console.WriteLine("\t" + kse.AttributeName + ": key type is " + kse.KeyType);
     }

      Projection projection = gsiDescription.Projection;
      Console.WriteLine("\tThe projection type is: " + projection.ProjectionType);

      if (projection.ProjectionType.ToString().Equals("INCLUDE")) {
           Console.WriteLine("\t\tThe non-key projected attributes are: "
                + projection.NonKeyAttributes);
      }
}
```

## グローバルセカンダリインデックスのクエリ
<a name="GSILowLevelDotNet.QueryAnIndex"></a>

テーブルに `Query` を実行するのとほぼ同じ方法で、グローバルセカンダリインデックスに対する `Query` を使用することができます。インデックス名、インデックスパーティションキーとソートキー (存在する場合) のクエリ条件、および返す属性を指定する必要があります。この例では、インデックスは `PrecipIndex` で、パーティションキーが `Date` で、ソートキーが `Precipitation` です。このインデックスクエリは、降水量がゼロより大きい特定の日付のすべての気象データを返します。

.NET 低レベル API を使用して、グローバルセカンダリインデックスを含むテーブルにクエリを実行する手順を次に示します。

1. `AmazonDynamoDBClient` クラスのインスタンスを作成します。

1. リクエスト情報を指定する `QueryRequest` クラスのインスタンスを作成します。

1. リクエストオブジェクトをパラメータとして指定して、`query` メソッドを実行します。

属性名 `Date` は DynamoDB の予約語です。したがって、式の属性名を `KeyConditionExpression` のプレースホルダーとして使用する必要があります。

以下の C\# サンプルコードは、前述のステップの例です。

**Example**  

```
client = new AmazonDynamoDBClient();

QueryRequest queryRequest = new QueryRequest
{
    TableName = "WeatherData",
    IndexName = "PrecipIndex",
    KeyConditionExpression = "#dt = :v_date and Precipitation > :v_precip",
    ExpressionAttributeNames = new Dictionary<String, String> {
        {"#dt", "Date"}
    },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
        {":v_date", new AttributeValue { S =  "2013-08-01" }},
        {":v_precip", new AttributeValue { N =  "0" }}
    },
    ScanIndexForward = true
};

var result = client.Query(queryRequest);

var items = result.Items;
foreach (var currentItem in items)
{
    foreach (string attr in currentItem.Keys)
    {
        Console.Write(attr + "---> ");
        if (attr == "Precipitation")
        {
            Console.WriteLine(currentItem[attr].N);
    }
    else
    {
        Console.WriteLine(currentItem[attr].S);
    }

         }
     Console.WriteLine();
}
```