

¡Se AWS SDK para .NET ha publicado la versión 4 (V4) del\!

Para obtener información sobre los cambios más importantes y la migración de sus aplicaciones, consulte el [tema sobre migración](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html).

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Uso de expresiones con Amazon DynamoDB y AWS SDK para .NET
<a name="dynamodb-expressions"></a>

**nota**  
La información de este tema es específica de los proyectos basados en .NET Framework y en la AWS SDK para .NET versión 3.3 y anteriores.

Los siguientes ejemplos de código muestran cómo utilizar el AWS SDK para .NET para programar DynamoDB con expresiones. Las *expresiones* se utilizan para indicar los atributos que se desea leer de un elemento en una tabla de DynamoDB. Además, se pueden utilizar al escribir un elemento para indicar las condiciones que se deben cumplir (lo que recibe el nombre también de *actualización condicional*) y la manera en que se deben actualizar los atributos. Algunos ejemplos de actualización sustituyen el atributo por un valor nuevo o añaden datos nuevos a una lista o mapa. Para obtener más información acerca del uso de expresiones, consulte el tema sobre [cómo leer y escribir elementos mediante expresiones](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html).

**Topics**
+ [Datos de ejemplo](#dynamodb-expressions-sample-data)
+ [Obtención de un elemento individual utilizando expresiones y la clave principal del elemento](#dynamodb-expressions-get-item)
+ [Obtención de varios elementos utilizando expresiones y la clave principal de la tabla](#dynamodb-expressions-query)
+ [Obtención de varios elementos utilizando expresiones y otros atributos del elemento](#dynamodb-expressions-scan)
+ [Imprimir un elemento](#dynamodb-expressions-print-item)
+ [Crear o reemplazar un elemento utilizando expresiones](#dynamodb-expressions-put-item)
+ [Actualizar un elemento utilizando expresiones](#dynamodb-expressions-update-item)
+ [Eliminación de un elemento utilizando expresiones](#dynamodb-expressions-delete-item)
+ [Más información](#dynamodb-expressions-resources)

## Datos de ejemplo
<a name="dynamodb-expressions-sample-data"></a>

Los ejemplos de código de este tema hacen referencia a los dos elementos de ejemplo siguientes de una tabla de DynamoDB llamada `ProductCatalog`. Estos elementos describen información sobre entradas de producto en un catálogo ficticio de una tienda de bicicletas. Estos elementos se basan en el ejemplo proporcionado en [Case Study: A ProductCatalog ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.CaseStudy.html) Item. Los descriptores de tipos de datos como `BOOL`, `L`, `M`, `N`, `NS`, `S` y `SS` equivalen a los del [formato de datos JSON](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html).

```
{
  "Id": {
    "N": "205"
  },
  "Title": {
    "S": "20-Bicycle 205"
  },
  "Description": {
    "S": "205 description"
  },
  "BicycleType": {
    "S": "Hybrid"
  },
  "Brand": {
    "S": "Brand-Company C"
  },
  "Price": {
    "N": "500"
  },
  "Gender": {
    "S": "B"
  },
  "Color": {
    "SS": [
      "Red",
      "Black"
    ]
  },
  "ProductCategory": {
    "S": "Bike"
  },
  "InStock": {
    "BOOL": true
  },
  "QuantityOnHand": {
    "N": "1"
  },
  "RelatedItems": {
    "NS": [
      "341",
      "472",
      "649"
    ]
  },
  "Pictures": {
    "L": [
      {
        "M": {
          "FrontView": {
            "S": "http://example/products/205_front.jpg"
          }
        }
      },
      {
        "M": {
          "RearView": {
            "S": "http://example/products/205_rear.jpg"
          }
        }
      },
      {
        "M": {
          "SideView": {
            "S": "http://example/products/205_left_side.jpg"
          }
        }
      }
    ]
  },
  "ProductReviews": {
    "M": {
      "FiveStar": {
        "SS": [
          "Excellent! Can't recommend it highly enough! Buy it!",
          "Do yourself a favor and buy this."
        ]
      },
      "OneStar": {
        "SS": [
          "Terrible product! Do not buy this."
        ]
      }
    }
  }
},
{
  "Id": {
    "N": "301"
  },
  "Title": {
    "S": "18-Bicycle 301"
  },
  "Description": {
    "S": "301 description"
  },
  "BicycleType": {
    "S": "Road"
  },
  "Brand": {
    "S": "Brand-Company C"
  },
  "Price": {
    "N": "185"
  },
  "Gender": {
    "S": "F"
  },
  "Color": {
    "SS": [
      "Blue",
      "Silver"
    ]
  },
  "ProductCategory": {
    "S": "Bike"
  },
  "InStock": {
    "BOOL": true
  },
  "QuantityOnHand": {
    "N": "3"
  },
  "RelatedItems": {
    "NS": [
      "801",
      "822",
      "979"
    ]
  },
  "Pictures": {
    "L": [
      {
        "M": {
          "FrontView": {
            "S": "http://example/products/301_front.jpg"
          }
        }
      },
      {
        "M": {
          "RearView": {
            "S": "http://example/products/301_rear.jpg"
          }
        }
      },
      {
        "M": {
          "SideView": {
            "S": "http://example/products/301_left_side.jpg"
          }
        }
      }
    ]
  },
  "ProductReviews": {
    "M": {
      "FiveStar": {
        "SS": [
          "My daughter really enjoyed this bike!"
        ]
      },
      "ThreeStar": {
        "SS": [
          "This bike was okay, but I would have preferred it in my color.",
	      "Fun to ride."
        ]
      }
    }
  }
}
```

## Obtención de un elemento individual utilizando expresiones y la clave principal del elemento
<a name="dynamodb-expressions-get-item"></a>

En el siguiente ejemplo se muestra el método `Amazon.DynamoDBv2.AmazonDynamoDBClient.GetItem` y un conjunto de expresiones para obtener y luego imprimir el elemento que tenga un `Id` `205`. Solo se devuelven los siguientes atributos del elemento: `Id`, `Title`, `Description`, `Color`, `RelatedItems`, `Pictures` y `ProductReviews`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new GetItemRequest
{
  TableName = "ProductCatalog",
  ProjectionExpression = "Id, Title, Description, Color, #ri, Pictures, #pr",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#ri", "RelatedItems" }
  },
  Key = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "205" } }
  },
};
var response = client.GetItem(request);

// PrintItem() is a custom function.
PrintItem(response.Item);
```

En el ejemplo anterior, la propiedad `ProjectionExpression` especifica los atributos que se deben devolver. La propiedad `ExpressionAttributeNames` especifica el marcador de posición `#pr` para que represente el atributo `ProductReviews` y el marcador de posición `#ri` para que represente el atributo `RelatedItems`. La llamada a `PrintItem` hace referencia a una función personalizada, tal como se describe en [Imprimir un elemento](#dynamodb-expressions-print-item).

## Obtención de varios elementos utilizando expresiones y la clave principal de la tabla
<a name="dynamodb-expressions-query"></a>

En el siguiente ejemplo se muestra el método `Amazon.DynamoDBv2.AmazonDynamoDBClient.Query` y un conjunto de expresiones para obtener y luego imprimir el elemento que tenga un `Id` `301`, pero únicamente si el valor de `Price` es mayor que `150`. Solo se devuelven los siguientes atributos del elemento: `Id`, `Title` y todos los atributos de `ThreeStar` en `ProductReviews`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new QueryRequest
{
  TableName = "ProductCatalog",
  KeyConditions = new Dictionary<string,Condition>
  {
    { "Id", new Condition()
      {
        ComparisonOperator = ComparisonOperator.EQ,
        AttributeValueList = new List<AttributeValue>
        {
          new AttributeValue { N = "301" }
        }
      }
    }
  },
  ProjectionExpression = "Id, Title, #pr.ThreeStar",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#p", "Price" }
  },
  ExpressionAttributeValues = new Dictionary<string,AttributeValue>
  {
    { ":val", new AttributeValue { N = "150" } }
  },
  FilterExpression = "#p > :val"
};
var response = client.Query(request);

foreach (var item in response.Items)
{
  // Write out the first page of an item's attribute keys and values.
  // PrintItem() is a custom function.
  PrintItem(item);
  Console.WriteLine("=====");
}
```

En el ejemplo anterior, la propiedad `ProjectionExpression` especifica los atributos que se deben devolver. La propiedad `ExpressionAttributeNames` especifica el marcador de posición `#pr` para que represente el atributo `ProductReviews` y el marcador de posición `#p` para que represente el atributo `Price`. `#pr.ThreeStar` especifica que solo se devuelva el atributo `ThreeStar`. La propiedad `ExpressionAttributeValues` especifica el marcador de posición `:val` para que represente el valor `150`. La propiedad `FilterExpression` especifica que `#p` (`Price`) debe ser mayor que `:val` (`150`). La llamada a `PrintItem` hace referencia a una función personalizada, tal como se describe en [Imprimir un elemento](#dynamodb-expressions-print-item).

## Obtención de varios elementos utilizando expresiones y otros atributos del elemento
<a name="dynamodb-expressions-scan"></a>

En el siguiente ejemplo se muestra el método `Amazon.DynamoDBv2.AmazonDynamoDBClient.Scan` y un conjunto de expresiones para obtener y luego imprimir todos los elementos que tengan un elemento `ProductCategory` `Bike`. Solo se devuelven los siguientes atributos del elemento: `Id`, `Title` y todos los atributos de `ProductReviews`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new ScanRequest
{
  TableName = "ProductCatalog",
  ProjectionExpression = "Id, Title, #pr",
  ExpressionAttributeValues = new Dictionary<string,AttributeValue>
  {
    { ":catg", new AttributeValue { S = "Bike" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#pc", "ProductCategory" }
  },
  FilterExpression = "#pc = :catg",  
};
var response = client.Scan(request);

foreach (var item in response.Items)
{
  // Write out the first page/scan of an item's attribute keys and values.
  // PrintItem() is a custom function.
  PrintItem(item);
  Console.WriteLine("=====");
}
```

En el ejemplo anterior, la propiedad `ProjectionExpression` especifica los atributos que se deben devolver. La propiedad `ExpressionAttributeNames` especifica el marcador de posición `#pr` para que represente el atributo `ProductReviews` y el marcador de posición `#pc` para que represente el atributo `ProductCategory`. La propiedad `ExpressionAttributeValues` especifica el marcador de posición `:catg` para que represente el valor `Bike`. La propiedad `FilterExpression` especifica que `#pc` (`ProductCategory`) debe ser igual que `:catg` (`Bike`). La llamada a `PrintItem` hace referencia a una función personalizada, tal como se describe en [Imprimir un elemento](#dynamodb-expressions-print-item).

## Imprimir un elemento
<a name="dynamodb-expressions-print-item"></a>

El siguiente ejemplo muestra cómo imprimir los atributos y valores de un elemento. Este ejemplo se utiliza en los ejemplos anteriores que muestran cómo [Obtener un elemento individual utilizando expresiones y la clave principal del elemento](#dynamodb-expressions-get-item), [Obtener varios elementos utilizando expresiones y la clave principal de la tabla](#dynamodb-expressions-query) y [Obtener varios elementos utilizando expresiones y otros atributos del elemento](#dynamodb-expressions-scan).

```
// using Amazon.DynamoDBv2.Model;

// Writes out an item's attribute keys and values.
public static void PrintItem(Dictionary<string, AttributeValue> attrs)
{
  foreach (KeyValuePair<string, AttributeValue> kvp in attrs)
  {
    Console.Write(kvp.Key + " = ");
    PrintValue(kvp.Value);
  }
}

// Writes out just an attribute's value.
public static void PrintValue(AttributeValue value)
{
  // Binary attribute value.
  if (value.B != null)
  {
    Console.Write("Binary data");
  }
  // Binary set attribute value.
  else if (value.BS.Count > 0)
  {
    foreach (var bValue in value.BS)
    {
      Console.Write("\n  Binary data");
    }
  }
  // List attribute value.
  else if (value.L.Count > 0)
  {
    foreach (AttributeValue attr in value.L)
    {
      PrintValue(attr);
    }
  }
  // Map attribute value.
  else if (value.M.Count > 0)
  {
    Console.Write("\n");
    PrintItem(value.M);
  }
  // Number attribute value.
  else if (value.N != null)
  {
    Console.Write(value.N);
  }
  // Number set attribute value.
  else if (value.NS.Count > 0)
  {
    Console.Write("{0}", string.Join("\n", value.NS.ToArray()));
  }
  // Null attribute value.
  else if (value.NULL)
  {
    Console.Write("Null");
  }
  // String attribute value.
  else if (value.S != null)
  {
    Console.Write(value.S);
  }
  // String set attribute value.
  else if (value.SS.Count > 0)
  {
    Console.Write("{0}", string.Join("\n", value.SS.ToArray()));
  }
  // Otherwise, boolean value.
  else
  {
    Console.Write(value.BOOL);
  }
 
  Console.Write("\n");
}
```

En el ejemplo anterior, cada valor de atributo tiene varias data-type-specific propiedades que se pueden evaluar para determinar el formato correcto para imprimir el atributo. Estas propiedades incluyen `B`, `BOOL`, `BS`, `L`, `M`, `N`, `NS`, `NULL`, `S` y `SS`, que corresponden a aquellas propiedades con el [formato de datos JSON](DataFormat.html). Para propiedades como `B`, `N`, `NULL` y `S`, si la propiedad correspondiente no es `null`, entonces el atributo será del tipo de datos no `null` correspondiente. En el caso de propiedades como `BS` `L``M`,`NS`,, y`SS`, si `Count` es mayor que cero, el atributo es del tipo de non-zero-value datos correspondiente. Si todas las data-type-specific propiedades del atributo son cero `null` o son `Count` iguales a cero, el atributo corresponde al tipo de `BOOL` datos.

## Crear o reemplazar un elemento utilizando expresiones
<a name="dynamodb-expressions-put-item"></a>

En el siguiente ejemplo se muestra el método `Amazon.DynamoDBv2.AmazonDynamoDBClient.PutItem` y un conjunto de expresiones para actualizar el elemento que tenga un `Title` `18-Bicycle 301`. Si el elemento no existe todavía, se añade uno nuevo.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new PutItemRequest
{
  TableName = "ProductCatalog",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":product", new AttributeValue { S = "18-Bicycle 301" } }
  },
  ConditionExpression = "#title = :product", 
  // CreateItemData() is a custom function.
  Item = CreateItemData()
};
client.PutItem(request);
```

En el ejemplo anterior, la propiedad `ExpressionAttributeNames` especifica el marcador de posición `#title` para que represente el atributo `Title`. La propiedad `ExpressionAttributeValues` especifica el marcador de posición `:product` para que represente el valor `18-Bicycle 301`. La propiedad `ConditionExpression` especifica que `#title` (`Title`) debe ser igual que `:product` (`18-Bicycle 301`). La llamada a `CreateItemData` hace referencia a la siguiente función personalizada:

```
// using Amazon.DynamoDBv2.Model;

// Provides a sample item that can be added to a table.
public static Dictionary<string, AttributeValue> CreateItemData()
{
  var itemData = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "301" } },
    { "Title", new AttributeValue { S = "18\" Girl's Bike" } },
    { "BicycleType", new AttributeValue { S = "Road" } },
    { "Brand" , new AttributeValue { S = "Brand-Company C" } },
    { "Color", new AttributeValue { SS = new List<string>{ "Blue", "Silver" } } },
    { "Description", new AttributeValue { S = "301 description" } },
    { "Gender", new AttributeValue { S = "F" } },
    { "InStock", new AttributeValue { BOOL = true } },
    { "Pictures", new AttributeValue { L = new List<AttributeValue>{ 
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "FrontView", new AttributeValue { S = "http://example/products/301_front.jpg" } } } } },
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "RearView", new AttributeValue {S = "http://example/products/301_rear.jpg" } } } } },
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "SideView", new AttributeValue { S = "http://example/products/301_left_side.jpg" } } } } }
    } } },
    { "Price", new AttributeValue { N = "185" } },
    { "ProductCategory", new AttributeValue { S = "Bike" } },
    { "ProductReviews", new AttributeValue { M = new Dictionary<string,AttributeValue>{
      { "FiveStar", new AttributeValue { SS = new List<string>{
        "My daughter really enjoyed this bike!" } } },
      { "OneStar", new AttributeValue { SS = new List<string>{
        "Fun to ride.",
        "This bike was okay, but I would have preferred it in my color." } } }
    } } },
    { "QuantityOnHand", new AttributeValue { N = "3" } },
    { "RelatedItems", new AttributeValue { NS = new List<string>{ "979", "822", "801" } } }
  };

  return itemData;
}
```

En el ejemplo anterior, se devuelve un elemento de ejemplo con datos de muestra al intermediario. Se crean una serie de atributos y valores correspondientes utilizando tipos de datos como `BOOL`, `L`, `M`, `N`, `NS`, `S` y `SS`, que equivalen a los del [formato de datos JSON](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html).

## Actualizar un elemento utilizando expresiones
<a name="dynamodb-expressions-update-item"></a>

El siguiente ejemplo muestra el método `Amazon.DynamoDBv2.AmazonDynamoDBClient.UpdateItem` y un conjunto de expresiones para cambiar el `Title` a `18" Girl's Bike` para el elemento con un `Id` `301`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new UpdateItemRequest
{
  TableName = "ProductCatalog",
  Key = new Dictionary<string,AttributeValue>
  {
     { "Id", new AttributeValue { N = "301" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":newproduct", new AttributeValue { S = "18\" Girl's Bike" } }
  },
  UpdateExpression = "SET #title = :newproduct"
};
client.UpdateItem(request);
```

En el ejemplo anterior, la propiedad `ExpressionAttributeNames` especifica el marcador de posición `#title` para que represente el atributo `Title`. La propiedad `ExpressionAttributeValues` especifica el marcador de posición `:newproduct` para que represente el valor `18" Girl's Bike`. La propiedad `UpdateExpression` especifica que se cambie `#title` (`Title`) por `:newproduct` (`18" Girl's Bike`).

## Eliminación de un elemento utilizando expresiones
<a name="dynamodb-expressions-delete-item"></a>

El siguiente ejemplo muestra el método `Amazon.DynamoDBv2.AmazonDynamoDBClient.DeleteItem` y un conjunto de expresiones para eliminar el elemento con un `Id` `301` pero solo si el `Title` del elemento es `18-Bicycle 301`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new DeleteItemRequest
{
  TableName = "ProductCatalog",
  Key = new Dictionary<string,AttributeValue>
  {
     { "Id", new AttributeValue { N = "301" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":product", new AttributeValue { S = "18-Bicycle 301" } }
  },
  ConditionExpression = "#title = :product"
};
client.DeleteItem(request);
```

En el ejemplo anterior, la propiedad `ExpressionAttributeNames` especifica el marcador de posición `#title` para que represente el atributo `Title`. La propiedad `ExpressionAttributeValues` especifica el marcador de posición `:product` para que represente el valor `18-Bicycle 301`. La propiedad `ConditionExpression` especifica que `#title` (`Title`) debe ser igual que `:product` (`18-Bicycle 301`).

## Más información
<a name="dynamodb-expressions-resources"></a>

Para obtener más información y ejemplos de código, consulte:
+  [Serie de DynamoDB: expresiones](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [Acceso a atributos de elemento con expresiones de proyección](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) 
+  [Uso de marcadores de posición para nombres y valores de atributo](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html) 
+  [Especificación de condiciones con expresiones de condición](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) 
+  [Modificación de elementos y atributos con expresiones de actualización](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html) 
+  [Trabajar con elementos mediante la API AWS SDK para .NET de bajo nivel](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [Consulta de tablas mediante la API de bajo nivel AWS SDK para .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [Escaneo de tablas mediante la API de bajo nivel AWS SDK para .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [Trabajar con índices secundarios locales mediante la API de bajo nivel AWS SDK para .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [Trabajar con índices secundarios globales mediante la API de bajo nivel AWS SDK para .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 