

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Utilisation d'index secondaires globaux : Java
<a name="GSIJavaDocumentAPI"></a>

Vous pouvez utiliser l'API AWS SDK pour Java Document pour créer une table Amazon DynamoDB avec un ou plusieurs index secondaires globaux, décrire les index de la table et effectuer des requêtes à l'aide des index. 

Voici les étapes courantes pour les opérations de table. 

1. Créez une instance de la classe `DynamoDB`.

1. Fournissez les paramètres obligatoires et facultatifs pour l'opération en créant les objets de requête correspondants. 

1. Appelez la méthode appropriée fournie par le client, que vous avez créée à l'étape précédente. 

**Topics**
+ [Créer une table avec un index secondaire global](#GSIJavaDocumentAPI.CreateTableWithIndex)
+ [Décrire une table avec un index secondaire global](#GSIJavaDocumentAPI.DescribeTableWithIndex)
+ [Interroger un index secondaire global](#GSIJavaDocumentAPI.QueryAnIndex)
+ [Exemple : index secondaires globaux utilisant l'API du AWS SDK pour Java document](GSIJavaDocumentAPI.Example.md)

## Créer une table avec un index secondaire global
<a name="GSIJavaDocumentAPI.CreateTableWithIndex"></a>

Vous pouvez créer des index secondaires globaux au moment où vous créez une table. Pour ce faire, utilisez `CreateTable` et fournissez vos spécifications pour un ou plusieurs index secondaires globaux. L'exemple de code Java suivant crée une table destinée à accueillir des données météorologiques. La clé de partition est `Location`, et la clé de tri `Date`. Un index secondaire global nommé `PrecipIndex` permet un accès rapide aux données de précipitations pour différents endroits.

Voici les étapes à suivre pour créer une table avec un index secondaire global à l'aide de l'API Document DynamoDB. 

1. Créez une instance de la classe `DynamoDB`.

1. Créez une instance de la classe `CreateTableRequest` pour fournir l'information de requête.

   Vous devez fournir le nom de la table, sa clé primaire et les valeurs de débit approvisionné. Pour l'index secondaire global, vous devez fournir le nom de l'index, ses paramètres de débit approvisionné, les définitions d'attribut pour la clé de tri d'index, le schéma de clé pour l'index et la projection d'attribut.

1. Appelez la méthode `createTable` en fournissant l'objet de demande comme paramètre.

L’exemple de code Java suivant illustre les tâches précédentes. Le code crée une table (`WeatherData`) avec un index secondaire global (`PrecipIndex`). La clé de partition d'index est `Date`, et la clé de tri `Precipitation`. Tous les attributs de table sont projetés sur l'index. Les utilisateurs peuvent interroger cet index afin d'obtenir des données météorologiques pour une date particulière, en triant éventuellement les données par quantité de précipitations. 

`Precipitation` n'étant pas un attribut de clé pour la table, il n'est pas obligatoire. Toutefois, les éléments `WeatherData` sans `Precipitation` n'apparaissent pas dans `PrecipIndex`.

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

// Attribute definitions
ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();

attributeDefinitions.add(new AttributeDefinition()
    .withAttributeName("Location")
    .withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
    .withAttributeName("Date")
    .withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
    .withAttributeName("Precipitation")
    .withAttributeType("N"));

// Table key schema
ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>();
tableKeySchema.add(new KeySchemaElement()
    .withAttributeName("Location")
    .withKeyType(KeyType.HASH));  //Partition key
tableKeySchema.add(new KeySchemaElement()
    .withAttributeName("Date")
    .withKeyType(KeyType.RANGE));  //Sort key

// PrecipIndex
GlobalSecondaryIndex precipIndex = new GlobalSecondaryIndex()
    .withIndexName("PrecipIndex")
    .withProvisionedThroughput(new ProvisionedThroughput()
        .withReadCapacityUnits((long) 10)
        .withWriteCapacityUnits((long) 1))
        .withProjection(new Projection().withProjectionType(ProjectionType.ALL));

ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>();

indexKeySchema.add(new KeySchemaElement()
    .withAttributeName("Date")
    .withKeyType(KeyType.HASH));  //Partition key
indexKeySchema.add(new KeySchemaElement()
    .withAttributeName("Precipitation")
    .withKeyType(KeyType.RANGE));  //Sort key

precipIndex.setKeySchema(indexKeySchema);

CreateTableRequest createTableRequest = new CreateTableRequest()
    .withTableName("WeatherData")
    .withProvisionedThroughput(new ProvisionedThroughput()
        .withReadCapacityUnits((long) 5)
        .withWriteCapacityUnits((long) 1))
    .withAttributeDefinitions(attributeDefinitions)
    .withKeySchema(tableKeySchema)
    .withGlobalSecondaryIndexes(precipIndex);

Table table = dynamoDB.createTable(createTableRequest);
System.out.println(table.getDescription());
```

Vous devez attendre que DynamoDB crée la table et définisse l'état de celle-ci sur `ACTIVE`. Après cela, vous pouvez commencer à insérer des éléments de données dans la table.

## Décrire une table avec un index secondaire global
<a name="GSIJavaDocumentAPI.DescribeTableWithIndex"></a>

Pour obtenir des informations concernant les index secondaires globaux sur une table, utilisez l'opération `DescribeTable`. Pour chaque index, vous pouvez accéder à son nom, à son schéma de clé et aux attributs projetés.

Voici les étapes à suivre pour accéder aux informations d'index secondaire global sur une table. 

1. Créez une instance de la classe `DynamoDB`.

1. Créez une instance de la classe `Table` pour représenter l'index que vous souhaitez utiliser.

1. Appelez la méthode `describe` sur l'objet `Table`.

L’exemple de code Java suivant illustre les tâches précédentes.

**Example**  

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

Table table = dynamoDB.getTable("WeatherData");
TableDescription tableDesc = table.describe();
    

Iterator<GlobalSecondaryIndexDescription> gsiIter = tableDesc.getGlobalSecondaryIndexes().iterator();
while (gsiIter.hasNext()) {
    GlobalSecondaryIndexDescription gsiDesc = gsiIter.next();
    System.out.println("Info for index "
         + gsiDesc.getIndexName() + ":");

    Iterator<KeySchemaElement> kseIter = gsiDesc.getKeySchema().iterator();
    while (kseIter.hasNext()) {
        KeySchemaElement kse = kseIter.next();
        System.out.printf("\t%s: %s\n", kse.getAttributeName(), kse.getKeyType());
    }
    Projection projection = gsiDesc.getProjection();
    System.out.println("\tThe projection type is: "
        + projection.getProjectionType());
    if (projection.getProjectionType().toString().equals("INCLUDE")) {
        System.out.println("\t\tThe non-key projected attributes are: "
            + projection.getNonKeyAttributes());
    }
}
```

## Interroger un index secondaire global
<a name="GSIJavaDocumentAPI.QueryAnIndex"></a>

Vous pouvez utiliser l'opération `Query` sur un index secondaire global de la même manière que vous utilisez l'opération `Query` sur une table. Vous devez spécifier le nom de l'index, les critères de requête pour la clé de partition d'index et la clé de tri (le cas échéant), ainsi que les attributs que vous souhaitez renvoyer. Dans cet exemple, l'index est `PrecipIndex`. Il a une clé de partition `Date` et une clé de tri `Precipitation`. L'interrogation de l'index renvoie toutes les données météorologiques pour une date particulière, où les précipitations sont supérieures à zéro.

Voici les étapes à suivre pour interroger un index secondaire global à l'aide de l'API AWS SDK pour Java Document. 

1. Créez une instance de la classe `DynamoDB`.

1. Créez une instance de la classe `Table` pour représenter l'index que vous souhaitez utiliser.

1. Créez une instance de la classe `Index` pour l'index que vous souhaitez interroger.

1. Appelez la méthode `query` sur l'objet `Index`.

Nom d'attribut `Date` est un mot réservé DynamoDB. Par conséquent, vous devez utiliser un nom d'attribut d'expression comme espace réservé dans la `KeyConditionExpression`.

L’exemple de code Java suivant illustre les tâches précédentes.

**Example**  

```
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);

Table table = dynamoDB.getTable("WeatherData");
Index index = table.getIndex("PrecipIndex");

QuerySpec spec = new QuerySpec()
    .withKeyConditionExpression("#d = :v_date and Precipitation = :v_precip")
    .withNameMap(new NameMap()
        .with("#d", "Date"))
    .withValueMap(new ValueMap()
        .withString(":v_date","2013-08-10")
        .withNumber(":v_precip",0));

ItemCollection<QueryOutcome> items = index.query(spec);
Iterator<Item> iter = items.iterator(); 
while (iter.hasNext()) {
    System.out.println(iter.next().toJSONPretty());
}
```

# Exemple : index secondaires globaux utilisant l'API du AWS SDK pour Java document
<a name="GSIJavaDocumentAPI.Example"></a>

L'exemple de code Java suivant montre comment utiliser les index secondaires globaux. L'exemple crée une table nommée `Issues`, utilisable dans un système simple de suivi de bogues pour le développement de logiciels. La clé de partition est `IssueId`, et la clé de tri `Title`. Il y a trois index secondaires globaux sur cette table :
+ `CreateDateIndex` – La clé de partition est `CreateDate`, et la clé de tri `IssueId`. En plus des clés de table, les attributs `Description` et `Status` sont projetés dans l'index.
+ `TitleIndex` – La clé de partition est `Title`, et la clé de tri `IssueId`. Aucun attribut autre que les clés de table n'est projeté dans l'index.
+ `DueDateIndex` – La clé de partition est `DueDate` et il n'y a pas de clé de tri. Tous les attributs de table sont projetés sur l'index.

Une fois la table `Issues` créée, le programme charge la table avec des données représentant des rapports de bogues logiciels. Il interroge ensuite les données à l'aide d'index secondaires globaux. Enfin, le programme supprime la table `Issues`.

Pour step-by-step obtenir des instructions sur le test de l'exemple suivant, reportez-vous à[Exemples de code Java](CodeSamples.Java.md).

**Example**  

```
package com.amazonaws.codesamples.document;

import java.util.ArrayList;
import java.util.Iterator;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.Projection;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;

public class DocumentAPIGlobalSecondaryIndexExample {

    static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    static DynamoDB dynamoDB = new DynamoDB(client);

    public static String tableName = "Issues";

    public static void main(String[] args) throws Exception {

        createTable();
        loadData();

        queryIndex("CreateDateIndex");
        queryIndex("TitleIndex");
        queryIndex("DueDateIndex");

        deleteTable(tableName);

    }

    public static void createTable() {

        // Attribute definitions
        ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();

        attributeDefinitions.add(new AttributeDefinition().withAttributeName("IssueId").withAttributeType("S"));
        attributeDefinitions.add(new AttributeDefinition().withAttributeName("Title").withAttributeType("S"));
        attributeDefinitions.add(new AttributeDefinition().withAttributeName("CreateDate").withAttributeType("S"));
        attributeDefinitions.add(new AttributeDefinition().withAttributeName("DueDate").withAttributeType("S"));

        // Key schema for table
        ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>();
        tableKeySchema.add(new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.HASH)); // Partition
                                                                                                           // key
        tableKeySchema.add(new KeySchemaElement().withAttributeName("Title").withKeyType(KeyType.RANGE)); // Sort
                                                                                                          // key

        // Initial provisioned throughput settings for the indexes
        ProvisionedThroughput ptIndex = new ProvisionedThroughput().withReadCapacityUnits(1L)
                .withWriteCapacityUnits(1L);

        // CreateDateIndex
        GlobalSecondaryIndex createDateIndex = new GlobalSecondaryIndex().withIndexName("CreateDateIndex")
                .withProvisionedThroughput(ptIndex)
                .withKeySchema(new KeySchemaElement().withAttributeName("CreateDate").withKeyType(KeyType.HASH), // Partition
                                                                                                                 // key
                        new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort
                                                                                                        // key
                .withProjection(
                        new Projection().withProjectionType("INCLUDE").withNonKeyAttributes("Description", "Status"));

        // TitleIndex
        GlobalSecondaryIndex titleIndex = new GlobalSecondaryIndex().withIndexName("TitleIndex")
                .withProvisionedThroughput(ptIndex)
                .withKeySchema(new KeySchemaElement().withAttributeName("Title").withKeyType(KeyType.HASH), // Partition
                                                                                                            // key
                        new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort
                                                                                                        // key
                .withProjection(new Projection().withProjectionType("KEYS_ONLY"));

        // DueDateIndex
        GlobalSecondaryIndex dueDateIndex = new GlobalSecondaryIndex().withIndexName("DueDateIndex")
                .withProvisionedThroughput(ptIndex)
                .withKeySchema(new KeySchemaElement().withAttributeName("DueDate").withKeyType(KeyType.HASH)) // Partition
                                                                                                              // key
                .withProjection(new Projection().withProjectionType("ALL"));

        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withProvisionedThroughput(
                        new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1))
                .withAttributeDefinitions(attributeDefinitions).withKeySchema(tableKeySchema)
                .withGlobalSecondaryIndexes(createDateIndex, titleIndex, dueDateIndex);

        System.out.println("Creating table " + tableName + "...");
        dynamoDB.createTable(createTableRequest);

        // Wait for table to become active
        System.out.println("Waiting for " + tableName + " to become ACTIVE...");
        try {
            Table table = dynamoDB.getTable(tableName);
            table.waitForActive();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void queryIndex(String indexName) {

        Table table = dynamoDB.getTable(tableName);

        System.out.println("\n***********************************************************\n");
        System.out.print("Querying index " + indexName + "...");

        Index index = table.getIndex(indexName);

        ItemCollection<QueryOutcome> items = null;

        QuerySpec querySpec = new QuerySpec();

        if (indexName == "CreateDateIndex") {
            System.out.println("Issues filed on 2013-11-01");
            querySpec.withKeyConditionExpression("CreateDate = :v_date and begins_with(IssueId, :v_issue)")
                    .withValueMap(new ValueMap().withString(":v_date", "2013-11-01").withString(":v_issue", "A-"));
            items = index.query(querySpec);
        } else if (indexName == "TitleIndex") {
            System.out.println("Compilation errors");
            querySpec.withKeyConditionExpression("Title = :v_title and begins_with(IssueId, :v_issue)")
                    .withValueMap(
                            new ValueMap().withString(":v_title", "Compilation error").withString(":v_issue", "A-"));
            items = index.query(querySpec);
        } else if (indexName == "DueDateIndex") {
            System.out.println("Items that are due on 2013-11-30");
            querySpec.withKeyConditionExpression("DueDate = :v_date")
                    .withValueMap(new ValueMap().withString(":v_date", "2013-11-30"));
            items = index.query(querySpec);
        } else {
            System.out.println("\nNo valid index name provided");
            return;
        }

        Iterator<Item> iterator = items.iterator();

        System.out.println("Query: printing results...");

        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }

    }

    public static void deleteTable(String tableName) {

        System.out.println("Deleting table " + tableName + "...");

        Table table = dynamoDB.getTable(tableName);
        table.delete();

        // Wait for table to be deleted
        System.out.println("Waiting for " + tableName + " to be deleted...");
        try {
            table.waitForDelete();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void loadData() {

        System.out.println("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");

    }

    public static void putItem(

            String issueId, String title, String description, String createDate, String lastUpdateDate, String dueDate,
            Integer priority, String status) {

        Table table = dynamoDB.getTable(tableName);

        Item item = new Item().withPrimaryKey("IssueId", issueId).withString("Title", title)
                .withString("Description", description).withString("CreateDate", createDate)
                .withString("LastUpdateDate", lastUpdateDate).withString("DueDate", dueDate)
                .withNumber("Priority", priority).withString("Status", status);

        table.putItem(item);
    }

}
```