首页 > 解决方案 > DynamoDB 嵌套项目插入 Android

问题描述

嘿,我正在尝试将 DynamoDB 与我的 android 应用程序集成,并将项目插入到具有嵌套对象的数据库中,这些对象具有自己的属性Video,如下所示:

User{ 
      "Name" : "MyName"
      "Video": {
                    "videoType": "BRIGHTCOVE",
                    "viewingTime": 156,
                    "videoSize": 7120441,
                    "url": "5378655747001",
                    "URL": "5378655747001"
                }
      "Password" : "123456"

知道如何完成并在项目中插入项目吗?到目前为止,我只设法添加了普通的密钥对值,例如Nameand Passwordwithdocument.put方法

标签: androiddatabaseamazon-web-serviceskotlinamazon-dynamodb

解决方案


put操作参数需要如下所示。该Video属性是一个Map简单的键/值对。

{
  "TableName": "YOUR_TABLE_NAME",
  "Item": {
    "Name": {
      "S": "MyName"
    },
    "Password": {
      "S": "123456"
    },
    "Video": {
      "M": {      
        "videoType": {
          "S": "BRIGHTCOVE"
        },
        "viewingTime": {
          "N": "156"
        },
        "videoSize": {
          "N": "7120441"
        },
        "url": {
          "S": "5378655747001"
        },
        "URL": {
          "S": "5378655747001"
        }
      }
    }
  }
}


在 Java 中(未测试)

public static void main(String[] args) {
        // Create the DynamoDB Client with the region you want
        AmazonDynamoDB dynamoDB = createDynamoDbClient("YOUR REGION");
        
        try {
            PutItemRequest putItemRequest = new PutItemRequest();
            putItemRequest.setTableName("YOUR TABLE NAME");

            Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); 
            item.put("PK", new AttributeValue("PK"));
            item.put("SK", new AttributeValue("SK"));
            
            Map<String, AttributeValue> attributeValues = new HashMap<String, AttributeValue>(); 
            attributeValues.put("videoType", new AttributeValue("BRIGHTCOVE"));
            attributeValues.put("viewingTime", new AttributeValue().withN("156"));
            attributeValues.put("videoSize", new AttributeValue().withN("7120441"));
            attributeValues.put("url", new AttributeValue("5378655747001"));
            attributeValues.put("URL", new AttributeValue("5378655747001"));

            item.put("Video", new AttributeValue().withM(attributeValues);
            putItemRequest.setItem(item);
            
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
            System.out.println("Successfully put item.");
            // Handle putItemResult

        } catch (Exception e) {
            // handle errors
        }
    }

推荐阅读