

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Menggunakan Indek Sekunder Global: .NET
<a name="GSILowLevelDotNet"></a>

Anda dapat menggunakan API AWS SDK untuk .NET tingkat rendah untuk membuat tabel Amazon DynamoDB dengan satu atau beberapa indeks sekunder global, menjelaskan indeks pada tabel, dan melakukan kueri menggunakan indeks. Operasi ini dipetakan ke operasi DynamoDB yang sesuai. Untuk informasi selengkapnya, lihat [Referensi Amazon DynamoDB API](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/). 

Berikut ini adalah langkah-langkah umum untuk operasi tabel menggunakan API tingkat rendah .NET. 

1. Buat instans dari kelas `AmazonDynamoDBClient`.

1. Berikan parameter wajib dan opsional untuk operasi dengan membuat objek permintaan yang sesuai.

   Misalnya, buat objek `CreateTableRequest` untuk membuat tabel dan objek `QueryRequest` untuk mengkueri tabel atau indeks. 

1. Jalankan metode sesuai yang ditentukan oleh klien yang Anda buat pada langkah sebelumnya. 

**Topics**
+ [Membuat tabel dengan Indeks Sekunder Global](#GSILowLevelDotNet.CreateTableWithIndex)
+ [Mendeskripsikan tabel dengan Indeks Sekunder Global](#GSILowLevelDotNet.DescribeTableWithIndex)
+ [Mengkueri Indeks Sekunder Global](#GSILowLevelDotNet.QueryAnIndex)
+ [Contoh: Indeks Sekunder Global menggunakan API tingkat AWS SDK untuk .NET rendah](GSILowLevelDotNet.Example.md)

## Membuat tabel dengan Indeks Sekunder Global
<a name="GSILowLevelDotNet.CreateTableWithIndex"></a>

Anda dapat membuat indeks sekunder global pada saat membuat tabel. Untuk melakukannya, gunakan `CreateTable` dan berikan spesifikasi Anda untuk satu atau beberapa indeks sekunder global. Contoh kode C\$1 berikut membuat tabel untuk menyimpan informasi tentang data cuaca. Kunci partisinya adalah `Location` dan kunci urutannya adalah `Date`. Indeks sekunder global bernama `PrecipIndex` memungkinkan akses cepat ke data curah hujan untuk berbagai lokasi.

Berikut ini adalah langkah-langkah untuk membuat tabel dengan indeks sekunder global, menggunakan API tingkat rendah .NET. 

1. Buat instans dari kelas `AmazonDynamoDBClient`.

1. Buat instans dari kelas `CreateTableRequest` untuk memberikan informasi permintaan. 

   Anda harus memberikan nama tabel, kunci primernya, dan nilai throughput yang ditentukan. Untuk indeks sekunder global, Anda harus memberikan nama indeks, pengaturan throughput yang ditentukan, definisi atribut untuk kunci urutan indeks, skema kunci untuk indeks, dan proyeksi atribut.

1. Jalankan metode `CreateTable` dengan menentukan objek permintaan sebagai parameter.

Contoh kode \$1C berikut mendemonstrasikan langkah sebelumnya. Kode tersebut membuat tabel (`WeatherData`) dengan indeks sekunder global (`PrecipIndex`). Kunci partisi indeksnya adalah `Date` dan kunci urutannya adalah `Precipitation`. Semua atribut tabel diproyeksikan ke dalam indeks. Pengguna dapat mengkueri indeks ini untuk mendapatkan data cuaca untuk tanggal tertentu, yang secara opsional mengurutkan data berdasarkan jumlah curah hujan. 

Karena `Precipitation` bukan atribut kunci untuk tabel tersebut, maka tidak diperlukan. Namun, item `WeatherData` tanpa `Precipitation` tidak muncul di `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);
```

Anda harus menunggu hingga DynamoDB membuat tabel dan menetapkan status tabel menjadi `ACTIVE`. Setelah itu, Anda bisa mulai memasukkan item data ke dalam tabel.

## Mendeskripsikan tabel dengan Indeks Sekunder Global
<a name="GSILowLevelDotNet.DescribeTableWithIndex"></a>

Untuk mendapatkan informasi tentang indeks sekunder global pada sebuah tabel, gunakan `DescribeTable`. Untuk setiap indeks, Anda dapat mengakses namanya, skema kunci, dan atribut yang diproyeksikan.

Berikut ini adalah langkah-langkah untuk mengakses informasi indeks sekunder global untuk tabel menggunakan API tingkat rendah .NET. 

1. Buat instans dari kelas `AmazonDynamoDBClient`.

1. Jalankan metode `describeTable` dengan menyediakan objek permintaan sebagai parameter.

   Buat instans dari kelas `DescribeTableRequest` untuk memberikan informasi permintaan. Anda harus memberikan nama tabel.

Contoh kode \$1C berikut mendemonstrasikan langkah sebelumnya.

**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);
      }
}
```

## Mengkueri Indeks Sekunder Global
<a name="GSILowLevelDotNet.QueryAnIndex"></a>

Anda dapat menggunakan `Query` pada indeks sekunder global, sama seperti Anda `Query` tabel. Anda perlu menentukan nama indeks, kriteria kueri untuk kunci partisi indeks dan kunci urutan (jika ada), dan atribut yang ingin Anda kembalikan. Dalam contoh ini, indeks adalah `PrecipIndex`, yang memiliki kunci partisi `Date` dan kunci urutan `Precipitation`. Kueri indeks mengembalikan semua data cuaca untuk tanggal tertentu, dengan curah hujan lebih besar dari nol.

Berikut ini adalah langkah-langkah untuk mengkueri indeks sekunder global menggunakan API tingkat rendah .NET. 

1. Buat instans dari kelas `AmazonDynamoDBClient`.

1. Buat instans dari kelas `QueryRequest` untuk memberikan informasi permintaan.

1. Jalankan metode `query` dengan menentukan objek permintaan sebagai parameter.

Nama atribut `Date` adalah kata yang disimpan DynamoDB. Oleh karena itu, Anda harus menggunakan nama atribut ekspresi sebagai placeholder di `KeyConditionExpression`.

Contoh kode \$1C berikut mendemonstrasikan langkah sebelumnya.

**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();
}
```

# Contoh: Indeks Sekunder Global menggunakan API tingkat AWS SDK untuk .NET rendah
<a name="GSILowLevelDotNet.Example"></a>

Contoh kode C\$1 berikut menunjukkan cara menggunakan indeks sekunder global. Contoh tersebut membuat tabel bernama `Issues`, yang dapat digunakan dalam sistem pelacakan bug sederhana untuk pengembangan perangkat lunak. Kunci partisinya adalah `IssueId` dan kunci urutannya adalah `Title`. Ada tiga indeks sekunder global pada tabel ini:
+ `CreateDateIndex` — Kunci partisinya adalah `CreateDate` dan kunci urutannya adalah `IssueId`. Selain kunci tabel, atribut `Description` dan `Status` diproyeksikan ke dalam indeks.
+ `TitleIndex` — Kunci partisinya adalah `Title` dan kunci urutannya adalah `IssueId`. Tidak ada atribut selain kunci tabel yang diproyeksikan ke dalam indeks.
+ `DueDateIndex` — Kunci partisinya adalah `DueDate`, dan tidak ada kunci urutan. Semua atribut tabel diproyeksikan ke dalam indeks.

Setelah tabel `Issues` dibuat, program memuat tabel dengan data yang mewakili laporan bug perangkat lunak. Kemudian, data dikueri menggunakan indeks sekunder global. Terakhir, program menghapus tabel `Issues`.

Untuk step-by-step petunjuk pengujian sampel berikut, lihat[Contoh kode .NET](CodeSamples.DotNet.md).

**Example**  

```
using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.SecurityToken;

namespace com.amazonaws.codesamples
{
    class LowLevelGlobalSecondaryIndexExample
    {
        private static AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        public static String tableName = "Issues";

        public static void Main(string[] args)
        {
            CreateTable();
            LoadData();

            QueryIndex("CreateDateIndex");
            QueryIndex("TitleIndex");
            QueryIndex("DueDateIndex");

            DeleteTable(tableName);

            Console.WriteLine("To continue, press enter");
            Console.Read();
        }

        private static void CreateTable()
        {
            // Attribute definitions
            var attributeDefinitions = new List<AttributeDefinition>()
        {
            {new AttributeDefinition {
                 AttributeName = "IssueId", AttributeType = "S"
             }},
            {new AttributeDefinition {
                 AttributeName = "Title", AttributeType = "S"
             }},
            {new AttributeDefinition {
                 AttributeName = "CreateDate", AttributeType = "S"
             }},
            {new AttributeDefinition {
                 AttributeName = "DueDate", AttributeType = "S"
             }}
        };

            // Key schema for table
            var tableKeySchema = new List<KeySchemaElement>() {
            {
                new KeySchemaElement {
                    AttributeName= "IssueId",
                    KeyType = "HASH" //Partition key
                }
            },
            {
                new KeySchemaElement {
                    AttributeName = "Title",
                    KeyType = "RANGE" //Sort key
                }
            }
        };

            // Initial provisioned throughput settings for the indexes
            var ptIndex = new ProvisionedThroughput
            {
                ReadCapacityUnits = 1L,
                WriteCapacityUnits = 1L
            };

            // CreateDateIndex
            var createDateIndex = new GlobalSecondaryIndex()
            {
                IndexName = "CreateDateIndex",
                ProvisionedThroughput = ptIndex,
                KeySchema = {
                new KeySchemaElement {
                    AttributeName = "CreateDate", KeyType = "HASH" //Partition key
                },
                new KeySchemaElement {
                    AttributeName = "IssueId", KeyType = "RANGE" //Sort key
                }
            },
                Projection = new Projection
                {
                    ProjectionType = "INCLUDE",
                    NonKeyAttributes = {
                    "Description", "Status"
                }
                }
            };

            // TitleIndex
            var titleIndex = new GlobalSecondaryIndex()
            {
                IndexName = "TitleIndex",
                ProvisionedThroughput = ptIndex,
                KeySchema = {
                new KeySchemaElement {
                    AttributeName = "Title", KeyType = "HASH" //Partition key
                },
                new KeySchemaElement {
                    AttributeName = "IssueId", KeyType = "RANGE" //Sort key
                }
            },
                Projection = new Projection
                {
                    ProjectionType = "KEYS_ONLY"
                }
            };

            // DueDateIndex
            var dueDateIndex = new GlobalSecondaryIndex()
            {
                IndexName = "DueDateIndex",
                ProvisionedThroughput = ptIndex,
                KeySchema = {
                new KeySchemaElement {
                    AttributeName = "DueDate",
                    KeyType = "HASH" //Partition key
                }
            },
                Projection = new Projection
                {
                    ProjectionType = "ALL"
                }
            };



            var createTableRequest = new CreateTableRequest
            {
                TableName = tableName,
                ProvisionedThroughput = new ProvisionedThroughput
                {
                    ReadCapacityUnits = (long)1,
                    WriteCapacityUnits = (long)1
                },
                AttributeDefinitions = attributeDefinitions,
                KeySchema = tableKeySchema,
                GlobalSecondaryIndexes = {
                createDateIndex, titleIndex, dueDateIndex
            }
            };

            Console.WriteLine("Creating table " + tableName + "...");
            client.CreateTable(createTableRequest);

            WaitUntilTableReady(tableName);
        }

        private static void LoadData()
        {
            Console.WriteLine("Loading data into table " + tableName + "...");

            // IssueId, Title,
            // Description,
            // CreateDate, LastUpdateDate, DueDate,
            // Priority, Status

            putItem("A-101", "Compilation error",
                "Can't compile Project X - bad version number. What does this mean?",
                "2013-11-01", "2013-11-02", "2013-11-10",
                1, "Assigned");

            putItem("A-102", "Can't read data file",
                "The main data file is missing, or the permissions are incorrect",
                "2013-11-01", "2013-11-04", "2013-11-30",
                2, "In progress");

            putItem("A-103", "Test failure",
                "Functional test of Project X produces errors",
                "2013-11-01", "2013-11-02", "2013-11-10",
                1, "In progress");

            putItem("A-104", "Compilation error",
                "Variable 'messageCount' was not initialized.",
                "2013-11-15", "2013-11-16", "2013-11-30",
                3, "Assigned");

            putItem("A-105", "Network issue",
                "Can't ping IP address 127.0.0.1. Please fix this.",
                "2013-11-15", "2013-11-16", "2013-11-19",
                5, "Assigned");
        }

        private static void putItem(
            String issueId, String title,
            String description,
            String createDate, String lastUpdateDate, String dueDate,
            Int32 priority, String status)
        {
            Dictionary<String, AttributeValue> item = new Dictionary<string, AttributeValue>();

            item.Add("IssueId", new AttributeValue
            {
                S = issueId
            });
            item.Add("Title", new AttributeValue
            {
                S = title
            });
            item.Add("Description", new AttributeValue
            {
                S = description
            });
            item.Add("CreateDate", new AttributeValue
            {
                S = createDate
            });
            item.Add("LastUpdateDate", new AttributeValue
            {
                S = lastUpdateDate
            });
            item.Add("DueDate", new AttributeValue
            {
                S = dueDate
            });
            item.Add("Priority", new AttributeValue
            {
                N = priority.ToString()
            });
            item.Add("Status", new AttributeValue
            {
                S = status
            });

            try
            {
                client.PutItem(new PutItemRequest
                {
                    TableName = tableName,
                    Item = item
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void QueryIndex(string indexName)
        {
            Console.WriteLine
                ("\n***********************************************************\n");
            Console.WriteLine("Querying index " + indexName + "...");

            QueryRequest queryRequest = new QueryRequest
            {
                TableName = tableName,
                IndexName = indexName,
                ScanIndexForward = true
            };


            String keyConditionExpression;
            Dictionary<string, AttributeValue> expressionAttributeValues = new Dictionary<string, AttributeValue>();

            if (indexName == "CreateDateIndex")
            {
                Console.WriteLine("Issues filed on 2013-11-01\n");

                keyConditionExpression = "CreateDate = :v_date and begins_with(IssueId, :v_issue)";
                expressionAttributeValues.Add(":v_date", new AttributeValue
                {
                    S = "2013-11-01"
                });
                expressionAttributeValues.Add(":v_issue", new AttributeValue
                {
                    S = "A-"
                });
            }
            else if (indexName == "TitleIndex")
            {
                Console.WriteLine("Compilation errors\n");

                keyConditionExpression = "Title = :v_title and begins_with(IssueId, :v_issue)";
                expressionAttributeValues.Add(":v_title", new AttributeValue
                {
                    S = "Compilation error"
                });
                expressionAttributeValues.Add(":v_issue", new AttributeValue
                {
                    S = "A-"
                });

                // Select
                queryRequest.Select = "ALL_PROJECTED_ATTRIBUTES";
            }
            else if (indexName == "DueDateIndex")
            {
                Console.WriteLine("Items that are due on 2013-11-30\n");

                keyConditionExpression = "DueDate = :v_date";
                expressionAttributeValues.Add(":v_date", new AttributeValue
                {
                    S = "2013-11-30"
                });

                // Select
                queryRequest.Select = "ALL_PROJECTED_ATTRIBUTES";
            }
            else
            {
                Console.WriteLine("\nNo valid index name provided");
                return;
            }

            queryRequest.KeyConditionExpression = keyConditionExpression;
            queryRequest.ExpressionAttributeValues = expressionAttributeValues;

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

        private static void DeleteTable(string tableName)
        {
            Console.WriteLine("Deleting table " + tableName + "...");
            client.DeleteTable(new DeleteTableRequest
            {
                TableName = tableName
            });
            WaitForTableToBeDeleted(tableName);
        }

        private static void WaitUntilTableReady(string tableName)
        {
            string status = null;
            // Let us wait until table is created. Call DescribeTable.
            do
            {
                System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
                try
                {
                    var res = client.DescribeTable(new DescribeTableRequest
                    {
                        TableName = tableName
                    });

                    Console.WriteLine("Table name: {0}, status: {1}",
                              res.Table.TableName,
                              res.Table.TableStatus);
                    status = res.Table.TableStatus;
                }
                catch (ResourceNotFoundException)
                {
                    // DescribeTable is eventually consistent. So you might
                    // get resource not found. So we handle the potential exception.
                }
            } while (status != "ACTIVE");
        }

        private static void WaitForTableToBeDeleted(string tableName)
        {
            bool tablePresent = true;

            while (tablePresent)
            {
                System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
                try
                {
                    var res = client.DescribeTable(new DescribeTableRequest
                    {
                        TableName = tableName
                    });

                    Console.WriteLine("Table name: {0}, status: {1}",
                              res.Table.TableName,
                              res.Table.TableStatus);
                }
                catch (ResourceNotFoundException)
                {
                    tablePresent = false;
                }
            }
        }
    }
}
```