

のバージョン 4 (V4) AWS SDK for .NET がリリースされました。

重要な変更とアプリケーションの移行については、[「移行トピック](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)

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon DynamoDB と での式の使用 AWS SDK for .NET
<a name="dynamodb-expressions"></a>

**注記**  
このトピックの情報は、.NET Framework および AWS SDK for .NET バージョン 3.3 以前のプロジェクトに固有のものです。

次のコード例は、 を使用して式で DynamoDB AWS SDK for .NET をプログラムする方法を示しています。*式*は、DynamoDB テーブルの項目から読み取る属性を示します。また、項目を書き込むときも式を使用して、満たす必要がある条件 (*条件付き更新*とも呼ばれます) と、属性を更新する方法を示します。更新の例として、属性を新しい値で置き換えたり、新しいデータをリストやマップに追加したりします。詳細については、「[式を使用した項目の読み取りと書き込み](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html)」を参照してください。

**Topics**
+ [サンプルデータ](#dynamodb-expressions-sample-data)
+ [式と項目のプライマリキーを使用して単一の項目を取得する](#dynamodb-expressions-get-item)
+ [式およびテーブルのプライマリキーを使用して複数の項目を取得する](#dynamodb-expressions-query)
+ [式および他の項目属性を使って複数の項目を取得する](#dynamodb-expressions-scan)
+ [項目の出力](#dynamodb-expressions-print-item)
+ [式を使用して項目を作成または置換する](#dynamodb-expressions-put-item)
+ [式を使用して項目を更新する](#dynamodb-expressions-update-item)
+ [式を使用して項目を削除する](#dynamodb-expressions-delete-item)
+ [詳細情報](#dynamodb-expressions-resources)

## サンプルデータ
<a name="dynamodb-expressions-sample-data"></a>

このトピックのコード例では、`ProductCatalog` という名前の DynamoDB テーブルに存在する以下の 2 つの項目を例として使用します。これらの項目は、架空の自転車店のカタログの製品エントリに関する情報を示します。これらの項目は、「[導入事例: ProductCatalog 項目](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.CaseStudy.html)」で提供されている例に基づきます。`BOOL`、`L`、`M`、`N`、`NS`、`S`、`SS` などのデータ型記述子は、[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."
        ]
      }
    }
  }
}
```

## 式と項目のプライマリキーを使用して単一の項目を取得する
<a name="dynamodb-expressions-get-item"></a>

次の例では、`Amazon.DynamoDBv2.AmazonDynamoDBClient.GetItem` メソッドと一連の式を使用して、`Id` が `205` である項目を取得して出力します。項目の属性のうち返されるものは、`Id`、`Title`、`Description`、`Color`、`RelatedItems`、`Pictures`、`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);
```

前の例で、`ProjectionExpression` プロパティは返される属性を指定しています。`ExpressionAttributeNames` プロパティで、プレースホルダー `#pr` は `ProductReviews` 属性を表し、プレースホルダー `#ri` は `RelatedItems` 属性を表します。`PrintItem` の呼び出しは、「[項目の出力](#dynamodb-expressions-print-item)」で説明されているようにカスタム関数を参照します。

## 式およびテーブルのプライマリキーを使用して複数の項目を取得する
<a name="dynamodb-expressions-query"></a>

次の例では、`Amazon.DynamoDBv2.AmazonDynamoDBClient.Query` メソッドと一連の式を使用して、`Id` が `301` で `Price` の値が `150` より大きい項目を取得して出力します。返される項目の属性は、`Id`、`Title`、および `ThreeStar` のすべての `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("=====");
}
```

前の例で、`ProjectionExpression` プロパティは返される属性を指定しています。`ExpressionAttributeNames` プロパティで、プレースホルダー `#pr` は `ProductReviews` 属性を表し、プレースホルダー `#p` は `Price` 属性を表します。`#pr.ThreeStar` は、`ThreeStar` 属性だけを返すように指定します。`ExpressionAttributeValues` プロパティは、プレースホルダー `:val` が値 `150` を表すことを指定します。`FilterExpression` プロパティは、`#p`（`Price`）が `:val`（`150`）より大きくなければならないことを指定します。`PrintItem` の呼び出しは、「[項目の出力](#dynamodb-expressions-print-item)」で説明されているようにカスタム関数を参照します。

## 式および他の項目属性を使って複数の項目を取得する
<a name="dynamodb-expressions-scan"></a>

次の例では、`Amazon.DynamoDBv2.AmazonDynamoDBClient.Scan` メソッドと一連の式を使用して、`ProductCategory` が `Bike` であるすべての項目を取得して出力します。返される項目の属性は、`Id`、`Title`、および `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("=====");
}
```

前の例で、`ProjectionExpression` プロパティは返される属性を指定しています。`ExpressionAttributeNames` プロパティで、プレースホルダー `#pr` は `ProductReviews` 属性を表し、プレースホルダー `#pc` は `ProductCategory` 属性を表します。`ExpressionAttributeValues` プロパティは、プレースホルダー `:catg` が値 `Bike` を表すことを指定します。`FilterExpression` プロパティは、`#pc`（`ProductCategory`）が `:catg`（`Bike`）と等しくなければならないことを示します。`PrintItem` の呼び出しは、「[項目の出力](#dynamodb-expressions-print-item)」で説明されているようにカスタム関数を参照します。

## 項目の出力
<a name="dynamodb-expressions-print-item"></a>

次の例では、項目の属性と値を出力する方法を示します。この例は、「[式と項目のプライマリキーを使用して単一の項目を取得する](#dynamodb-expressions-get-item)」、「[式およびテーブルのプライマリキーを使用して複数の項目を取得する](#dynamodb-expressions-query)」、「[式および他の項目属性を使って複数の項目を取得する](#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");
}
```

前の例では、各属性値に含まれる複数のデータ型固有のプロパティを評価して、属性を出力する正しい形式を決定しています。このようなプロパティとしては `B`、`BOOL`、`BS`、`L`、`M`、`N`、`NS`、`NULL`、`S`、`SS` などがあり、これらは [JSON データ形式](DataFormat.html)に対応しています。`B`、`N`、`NULL`、`S` などのプロパティでは、対応するプロパティが `null` ではない場合、属性は対応する `null` ではないデータ型になります。`BS`、`L`、`M`、`NS`、`SS` などのプロパティでは、`Count` がゼロより大きい場合、属性は対応するゼロ値ではないデータ型になります。属性のすべてのデータ型固有プロパティが `null` であるか、または `Count` がゼロに等しい場合、属性は `BOOL` データ型に対応します。

## 式を使用して項目を作成または置換する
<a name="dynamodb-expressions-put-item"></a>

次の例では、`Amazon.DynamoDBv2.AmazonDynamoDBClient.PutItem` メソッドと一連の式を使用して、`Title` が `18-Bicycle 301` である項目を更新します。項目が存在しない場合、新しい項目が追加されます。

```
// 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);
```

前の例で、`ExpressionAttributeNames` プロパティは、プレースホルダー `#title` が `Title` 属性を表すことを指定します。`ExpressionAttributeValues` プロパティは、プレースホルダー `:product` が値 `18-Bicycle 301` を表すことを指定します。`ConditionExpression` プロパティは、`#title`（`Title`）が `:product`（`18-Bicycle 301`）と等しくなければならないことを示します。`CreateItemData` の呼び出しは、次のカスタム関数を参照します。

```
// 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;
}
```

前の例では、サンプルデータを含む項目の例が呼び出し元に返されます。一連の属性と対応する値は、`BOOL`、`L`、`M`、`N`、`NS`、`S`、`SS` のようなデータ型を使用して構成されます。これらは [JSON データ形式](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html)内のものと対応しています。

## 式を使用して項目を更新する
<a name="dynamodb-expressions-update-item"></a>

次の例では、`Amazon.DynamoDBv2.AmazonDynamoDBClient.UpdateItem` メソッドと一連の式を使用して、`Title` が `18" Girl's Bike` である項目の `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);
```

前の例で、`ExpressionAttributeNames` プロパティは、プレースホルダー `#title` が `Title` 属性を表すことを指定します。`ExpressionAttributeValues` プロパティは、プレースホルダー `:newproduct` が値 `18" Girl's Bike` を表すことを指定します。`UpdateExpression` プロパティは、`#title`（`Title`）を `:newproduct`（`18" Girl's Bike`）に変更することを指定します。

## 式を使用して項目を削除する
<a name="dynamodb-expressions-delete-item"></a>

次の例では、`Amazon.DynamoDBv2.AmazonDynamoDBClient.DeleteItem` メソッドと一連の式を使用して、`Id` が `301` で `Title` が `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);
```

前の例で、`ExpressionAttributeNames` プロパティは、プレースホルダー `#title` が `Title` 属性を表すことを指定します。`ExpressionAttributeValues` プロパティは、プレースホルダー `:product` が値 `18-Bicycle 301` を表すことを指定します。`ConditionExpression` プロパティは、`#title`（`Title`）が `:product`（`18-Bicycle 301`）と等しくなければならないことを示します。

## 詳細情報
<a name="dynamodb-expressions-resources"></a>

詳細な説明とコード例については、以下を参照してください。
+  [DynamoDB Series - Expressions](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [プロジェクト式を使用した項目属性へのアクセス](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) 
+  [属性の名前および値でのプレースホルダーの使用](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html) 
+  [条件式を使用した条件の指定](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) 
+  [更新式を使用した項目および属性の変更](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html) 
+  [AWS SDK for .NET 低レベル API を使用したアイテムの操作](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [AWS SDK for .NET 低レベル API を使用したテーブルのクエリ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [AWS SDK for .NET 低レベル API を使用したテーブルのスキャン](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [AWS SDK for .NET 低レベル API を使用したローカルセカンダリインデックスの操作](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [AWS SDK for .NET 低レベル API を使用したグローバルセカンダリインデックスの使用](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 