Author: alien

  • Khóa học miễn phí DynamoDB – Indexes nhận dự án làm có lương

    DynamoDB – Indexes



    DynamoDB uses indexes for primary key attributes to improve accesses. They accelerate application accesses and data retrieval, and support better performance by reducing application lag.

    Secondary Index

    A secondary index holds an attribute subset and an alternate key. You use it through either a query or scan operation, which targets the index.

    Its contents include attributes you project or copy. In creation, you define an alternate key for the index, and any attributes you wish to project in the index. DynamoDB then performs a copy of the attributes into the index, including primary key attributes sourced from the table. After performing these tasks, you simply use a query/scan as if performing on a table.

    DynamoDB automatically maintains all secondary indices. On item operations, such as adding or deleting, it updates any indexes on the target table.

    DynamoDB offers two types of secondary indexes −

    • Global Secondary Index − This index includes a partition key and sort key, which may differ from the source table. It uses the label “global” due to the capability of queries/scans on the index to span all table data, and over all partitions.

    • Local Secondary Index − This index shares a partition key with the table, but uses a different sort key. Its “local” nature results from all of its partitions scoping to a table partition with identical partition key value.

    The best type of index to use depends on application needs. Consider the differences between the two presented in the following table −

    Quality Global Secondary Index Local Secondary Index
    Key Schema It uses a simple or composite primary key. It always uses a composite primary key.
    Key Attributes The index partition key and sort key can consist of string, number, or binary table attributes. The partition key of the index is an attribute shared with the table partition key. The sort key can be string, number, or binary table attributes.
    Size Limits Per Partition Key Value They carry no size limitations. It imposes a 10GB maximum limit on total size of indexed items associated with a partition key value.
    Online Index Operations You can spawn them at table creation, add them to existing tables, or delete existing ones. You must create them at table creation, but cannot delete them or add them to existing tables.
    Queries It allows queries covering the entire table, and every partition. They address single partitions through the partition key value provided in the query.
    Consistency Queries of these indices only offer the eventually consistent option. Queries of these offer the options of eventually consistent or strongly consistent.
    Throughput Cost It includes throughput settings for reads and writes. Queries/scans consume capacity from the index, not the table, which also applies to table write updates. Queries/scans consume table read capacity. Table writes update local indexes, and consume table capacity units.
    Projection Queries/scans can only request attributes projected into the index, with no retrievals of table attributes. Queries/scans can request those attributes not projected; furthermore, automatic fetches of them occur.

    When creating multiple tables with secondary indexes, do it sequentially; meaning make a table and wait for it to reach ACTIVE state before creating another and again waiting. DynamoDB does not permit concurrent creation.

    Each secondary index requires certain specifications −

    • Type − Specify local or global.

    • Name − It uses naming rules identical to tables.

    • Key Schema − Only top level string, number, or binary type are permitted, with index type determining other requirements.

    • Attributes for Projection − DynamoDB automatically projects them, and allows any data type.

    • Throughput − Specify read/write capacity for global secondary indexes.

    The limit for indexes remains 5 global and 5 local per table.

    You can access the detailed information about indexes with DescribeTable. It returns the name, size, and item count.

    Note − These values updates every 6 hours.

    In queries or scans used to access index data, provide the table and index names, desired attributes for the result, and any conditional statements. DynamoDB offers the option to return results in either ascending or descending order.

    Note − The deletion of a table also deletes all indexes.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Scan nhận dự án làm có lương

    DynamoDB – Scan



    Scan Operations read all table items or secondary indices. Its default function results in returning all data attributes of all items within an index or table. Employ the ProjectionExpression parameter in filtering attributes.

    Every scan returns a result set, even on finding no matches, which results in an empty set. Scans retrieve no more than 1MB, with the option to filter data.

    Note − The parameters and filtering of scans also apply to querying.

    Types of Scan Operations

    Filtering − Scan operations offer fine filtering through filter expressions, which modify data after scans, or queries; before returning results. The expressions use comparison operators. Their syntax resembles condition expressions with the exception of key attributes, which filter expressions do not permit. You cannot use a partition or sort key in a filter expression.

    Note − The 1MB limit applies prior to any application of filtering.

    Throughput Specifications − Scans consume throughput, however, consumption focuses on item size rather than returned data. The consumption remains the same whether you request every attribute or only a few, and using or not using a filter expression also does not impact consumption.

    Pagination − DynamoDB paginates results causing division of results into specific pages. The 1MB limit applies to returned results, and when you exceed it, another scan becomes necessary to gather the rest of the data. The LastEvaluatedKey value allows you to perform this subsequent scan. Simply apply the value to the ExclusiveStartkey. When the LastEvaluatedKey value becomes null, the operation has completed all pages of data. However, a non-null value does not automatically mean more data remains. Only a null value indicates status.

    The Limit Parameter − The limit parameter manages the result size. DynamoDB uses it to establish the number of items to process before returning data, and does not work outside of the scope. If you set a value of x, DynamoDB returns the first x matching items.

    The LastEvaluatedKey value also applies in cases of limit parameters yielding partial results. Use it to complete scans.

    Result Count − Responses to queries and scans also include information related to ScannedCount and Count, which quantify scanned/queried items and quantify items returned. If you do not filter, their values are identical. When you exceed 1MB, the counts represent only the portion processed.

    Consistency − Query results and scan results are eventually consistent reads, however, you can set strongly consistent reads as well. Use the ConsistentRead parameter to change this setting.

    Note − Consistent read settings impact consumption by using double the capacity units when set to strongly consistent.

    Performance − Queries offer better performance than scans due to scans crawling the full table or secondary index, resulting in a sluggish response and heavy throughput consumption. Scans work best for small tables and searches with less filters, however, you can design lean scans by obeying a few best practices such as avoiding sudden, accelerated read activity and exploiting parallel scans.

    A query finds a certain range of keys satisfying a given condition, with performance dictated by the amount of data it retrieves rather than the volume of keys. The parameters of the operation and the number of matches specifically impact performance.

    Parallel Scan

    Scan operations perform processing sequentially by default. Then they return data in 1MB portions, which prompts the application to fetch the next portion. This results in long scans for large tables and indices.

    This characteristic also means scans may not always fully exploit the available throughput. DynamoDB distributes table data across multiple partitions; and scan throughput remains limited to a single partition due to its single-partition operation.

    A solution for this problem comes from logically dividing tables or indices into segments. Then “workers” parallel (concurrently) scan segments. It uses the parameters of Segment and TotalSegments to specify segments scanned by certain workers and specify the total quantity of segments processed.

    Worker Number

    You must experiment with worker values (Segment parameter) to achieve the best application performance.

    Note − Parallel scans with large sets of workers impacts throughput by possibly consuming all throughput. Manage this issue with the Limit parameter, which you can use to stop a single worker from consuming all throughput.

    The following is a deep scan example.

    Note − The following program may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.ItemCollection;
    import com.amazonaws.services.dynamodbv2.document.ScanOutcome;
    import com.amazonaws.services.dynamodbv2.document.Table;
    
    public class ScanOpSample {
       static DynamoDB dynamoDB = new DynamoDB(
          new AmazonDynamoDBClient(new ProfileCredentialsProvider()));
       static String tableName = "ProductList";
    
       public static void main(String[] args) throws Exception {
          findProductsUnderOneHun();                       //finds products under 100 dollars
       }
       private static void findProductsUnderOneHun() {
          Table table = dynamoDB.getTable(tableName);
          Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
          expressionAttributeValues.put(":pr", 100);
    
          ItemCollection<ScanOutcome> items = table.scan (
             "Price < :pr",                                  //FilterExpression
             "ID, Nomenclature, ProductCategory, Price",     //ProjectionExpression
             null,                                           //No ExpressionAttributeNames
             expressionAttributeValues);
    
          System.out.println("Scanned " + tableName + " to find items under $100.");
          Iterator<Item> iterator = items.iterator();
    
          while (iterator.hasNext()) {
             System.out.println(iterator.next().toJSONPretty());
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Batch Writing nhận dự án làm có lương

    DynamoDB – Batch Writing



    Batch writing operates on multiple items by creating or deleting several items. These operations utilize BatchWriteItem, which carries the limitations of no more than 16MB writes and 25 requests. Each item obeys a 400KB size limit. Batch writes also cannot perform item updates.

    What is Batch Writing?

    Batch writes can manipulate items across multiple tables. Operation invocation happens for each individual request, which means operations do not impact each other, and heterogeneous mixes are permitted; for example, one PutItem and three DeleteItem requests in a batch, with the failure of the PutItem request not impacting the others. Failed requests result in the operation returning information (keys and data) pertaining to each failed request.

    Note − If DynamoDB returns any items without processing them, retry them; however, use a back-off method to avoid another request failure based on overloading.

    DynamoDB rejects a batch write operation when one or more of the following statements proves to be true −

    • The request exceeds the provisioned throughput.

    • The request attempts to use BatchWriteItems to update an item.

    • The request performs several operations on a single item.

    • The request tables do not exist.

    • The item attributes in the request do not match the target.

    • The requests exceed size limits.

    Batch writes require certain RequestItem parameters −

    • Deletion operations need DeleteRequest key subelements meaning an attribute name and value.

    • The PutRequest items require an Item subelement meaning an attribute and attribute value map.

    Response − A successful operation results in an HTTP 200 response, which indicates characteristics like capacity units consumed, table processing metrics, and any unprocessed items.

    Batch Writes with Java

    Perform a batch write by creating a DynamoDB class instance, a TableWriteItems class instance describing all operations, and calling the batchWriteItem method to use the TableWriteItems object.

    Note − You must create a TableWriteItems instance for every table in a batch write to multiple tables. Also, check your request response for any unprocessed requests.

    You can review the following example of a batch write −

    DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
       new ProfileCredentialsProvider()));
    
    TableWriteItems forumTableWriteItems = new TableWriteItems("Forum")
       .withItemsToPut(
       new Item()
       .withPrimaryKey("Title", "XYZ CRM")
       .withNumber("Threads", 0));
    
    TableWriteItems threadTableWriteItems = new TableWriteItems(Thread)
       .withItemsToPut(
       new Item()
       .withPrimaryKey("ForumTitle","XYZ CRM","Topic","Updates")
       .withHashAndRangeKeysToDelete("ForumTitle","A partition key value",
       "Product Line 1", "A sort key value"));
    
    BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem (
       forumTableWriteItems, threadTableWriteItems);
    

    The following program is another bigger example for better understanding of how a batch writes with Java.

    Note − The following example may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document;
    
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Map;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
    import com.amazonaws.services.dynamodbv2.model.WriteRequest;
    
    public class BatchWriteOpSample {
       static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
          new ProfileCredentialsProvider()));
       static String forumTableName = "Forum";
       static String threadTableName = "Thread";
    
       public static void main(String[] args) throws IOException {
          batchWriteMultiItems();
       }
       private static void batchWriteMultiItems() {
          try {
             // Place new item in Forum
             TableWriteItems forumTableWriteItems = new TableWriteItems(forumTableName)
                                                                           //Forum
                .withItemsToPut(new Item()
                .withPrimaryKey("Name", "Amazon RDS")
                .withNumber("Threads", 0));
    
             // Place one item, delete another in Thread
             // Specify partition key and range key
             TableWriteItems threadTableWriteItems = new TableWriteItems(threadTableName)
                .withItemsToPut(new Item()
                .withPrimaryKey("ForumName","Product
                Support","Subject","Support Thread 1")
                .withString("Message", "New OS Thread 1 message")
                .withHashAndRangeKeysToDelete("ForumName","Subject", "Polymer Blaster",
                "Support Thread 100"));
    
             System.out.println("Processing request...");
             BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem (
                   forumTableWriteItems, threadTableWriteItems);
             do {
                // Confirm no unprocessed items
                Map<String, List<WriteRequest>> unprocessedItems
                   = outcome.getUnprocessedItems();
    
                if (outcome.getUnprocessedItems().size() == 0) {
                   System.out.println("All items processed.");
                } else {
                   System.out.println("Gathering unprocessed items...");
                   outcome = dynamoDB.batchWriteItemUnprocessed(unprocessedItems);
                }
             } while (outcome.getUnprocessedItems().size() > 0);
          } catch (Exception e) {
             System.err.println("Could not get items: ");
             e.printStackTrace(System.err);
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Update Items nhận dự án làm có lương

    DynamoDB – Update Items



    Updating an item in DynamoDB mainly consists of specifying the full primary key and table name for the item. It requires a new value for each attribute you modify. The operation uses UpdateItem, which modifies the existing items or creates them on discovery of a missing item.

    In updates, you might want to track the changes by displaying the original and new values, before and after the operations. UpdateItem uses the ReturnValues parameter to achieve this.

    Note − The operation does not report capacity unit consumption, but you can use the ReturnConsumedCapacity parameter.

    Use the GUI console, Java, or any other tool to perform this task.

    How to Update Items Using GUI Tools?

    Navigate to the console. In the navigation pane on the left side, select Tables. Choose the table needed, and then select the Items tab.

    Update Items Using GUI Tools

    Choose the item desired for an update, and select Actions | Edit.

    Choose Item

    Modify any attributes or values necessary in the Edit Item window.

    Update Items Using Java

    Using Java in the item update operations requires creating a Table class instance, and calling its updateItem method. Then you specify the item”s primary key, and provide an UpdateExpression detailing attribute modifications.

    The Following is an example of the same −

    DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
       new ProfileCredentialsProvider()));
    
    Table table = dynamoDB.getTable("ProductList");
    
    Map<String, String> expressionAttributeNames = new HashMap<String, String>();
    expressionAttributeNames.put("#M", "Make");
    expressionAttributeNames.put("#P", "Price
    expressionAttributeNames.put("#N", "ID");
    
    Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
    expressionAttributeValues.put(":val1",
       new HashSet<String>(Arrays.asList("Make1","Make2")));
    expressionAttributeValues.put(":val2", 1);       //Price
    
    UpdateItemOutcome outcome =  table.updateItem(
       "internalID",                                 // key attribute name
       111,                                          // key attribute value
       "add #M :val1 set #P = #P - :val2 remove #N", // UpdateExpression
       expressionAttributeNames,
       expressionAttributeValues);
    

    The updateItem method also allows for specifying conditions, which can be seen in the following example −

    Table table = dynamoDB.getTable("ProductList");
    Map<String, String> expressionAttributeNames = new HashMap<String, String>();
    expressionAttributeNames.put("#P", "Price");
    
    Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
    expressionAttributeValues.put(":val1", 44);  // change Price to 44
    expressionAttributeValues.put(":val2", 15);  // only if currently 15
    
    UpdateItemOutcome outcome = table.updateItem (new PrimaryKey("internalID",111),
       "set #P = :val1",                        // Update
       "#P = :val2",                            // Condition
       expressionAttributeNames,
       expressionAttributeValues);
    

    Update Items Using Counters

    DynamoDB allows atomic counters, which means using UpdateItem to increment/decrement attribute values without impacting other requests; furthermore, the counters always update.

    The following is an example that explains how it can be done.

    Note − The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document;
    
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.Table;
    
    import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
    import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
    import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
    import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
    import com.amazonaws.services.dynamodbv2.model.ReturnValue;
    
    public class UpdateItemOpSample {
       static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
          new ProfileCredentialsProvider()));
       static String tblName = "ProductList";
    
       public static void main(String[] args) throws IOException {
          createItems();
          retrieveItem();
    
          // Execute updates
          updateMultipleAttributes();
          updateAddNewAttribute();
          updateExistingAttributeConditionally();
    
          // Item deletion
          deleteItem();
       }
       private static void createItems() {
          Table table = dynamoDB.getTable(tblName);
          try {
             Item item = new Item()
                .withPrimaryKey("ID", 303)
                .withString("Nomenclature", "Polymer Blaster 4000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
                .withNumber("Price", 50000)
                .withBoolean("InProduction", true)
                .withString("Category", "Laser Cutter");
                table.putItem(item);
    
             item = new Item()
                .withPrimaryKey("ID", 313)
                .withString("Nomenclature", "Agitatatron 2000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
                .withNumber("Price", 40000)
                .withBoolean("InProduction", true)
                .withString("Category", "Agitator");
                table.putItem(item);
          } catch (Exception e) {
             System.err.println("Cannot create items.");
             System.err.println(e.getMessage());
          }
       }
       private static void updateAddNewAttribute() {
          Table table = dynamoDB.getTable(tableName);
          try {
             Map<String, String> expressionAttributeNames = new HashMap<String, String>();
             expressionAttributeNames.put("#na", "NewAttribute");
             UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey("ID", 303)
                .withUpdateExpression("set #na = :val1")
                .withNameMap(new NameMap()
                .with("#na", "NewAttribute"))
                .withValueMap(new ValueMap()
                .withString(":val1", "A value"))
                .withReturnValues(ReturnValue.ALL_NEW);
                UpdateItemOutcome outcome =  table.updateItem(updateItemSpec);
    
             // Confirm
             System.out.println("Displaying updated item...");
             System.out.println(outcome.getItem().toJSONPretty());
          } catch (Exception e) {
             System.err.println("Cannot add an attribute in " + tableName);
             System.err.println(e.getMessage());
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Batch Retrieve nhận dự án làm có lương

    DynamoDB – Batch Retrieve



    Batch Retrieve operations return attributes of a single or multiple items. These operations generally consist of using the primary key to identify the desired item(s). The BatchGetItem operations are subject to the limits of individual operations as well as their own unique constraints.

    The following requests in batch retrieval operations result in rejection −

    • Make a request for more than 100 items.
    • Make a request exceeding throughput.

    Batch retrieve operations perform partial processing of requests carrying the potential to exceed limits.

    For example − a request to retrieve multiple items large enough in size to exceed limits results in part of the request processing, and an error message noting the unprocessed portion. On return of unprocessed items, create a back-off algorithm solution to manage this rather than throttling tables.

    The BatchGet operations perform eventually with consistent reads, requiring modification for strongly consistent ones. They also perform retrievals in parallel.

    Note − The order of the returned items. DynamoDB does not sort the items. It also does not indicate the absence of the requested items. Furthermore, those requests consume capacity units.

    All the BatchGet operations require RequestItems parameters such as the read consistency, attribute names, and primary keys.

    Response − A successful operation results in an HTTP 200 response, which indicates characteristics like capacity units consumed, table processing metrics, and any unprocessed items.

    Batch Retrievals with Java

    Using Java in BatchGet operations requires creating a DynamoDB class instance, TableKeysAndAttributes class instance describing a primary key values list for the items, and passing the TableKeysAndAttributes object to the BatchGetItem method.

    The following is an example of a BatchGet operation −

    DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
       new ProfileCredentialsProvider()));
    
    TableKeysAndAttributes forumTableKeysAndAttributes = new TableKeysAndAttributes
       (forumTableName);
    
    forumTableKeysAndAttributes.addHashOnlyPrimaryKeys (
       "Title",
       "Updates",
       "Product Line 1"
    );
    TableKeysAndAttributes threadTableKeysAndAttributes = new TableKeysAndAttributes (
       threadTableName);
    
    threadTableKeysAndAttributes.addHashAndRangePrimaryKeys (
       "ForumTitle",
       "Topic",
       "Product Line 1",
       "P1 Thread 1",
       "Product Line 1",
       "P1 Thread 2",
       "Product Line 2",
       "P2 Thread 1"
    );
    BatchGetItemOutcome outcome = dynamoDB.batchGetItem (
       forumTableKeysAndAttributes, threadTableKeysAndAttributes);
    
    for (String tableName : outcome.getTableItems().keySet()) {
       System.out.println("Table items " + tableName);
       List<Item> items = outcome.getTableItems().get(tableName);
       for (Item item : items) {
          System.out.println(item);
       }
    }
    

    You can review the following larger example.

    Note − The following program may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This program also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Map;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.BatchGetItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.TableKeysAndAttributes;
    import com.amazonaws.services.dynamodbv2.model.KeysAndAttributes;
    
    public class BatchGetOpSample {
       static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
          new ProfileCredentialsProvider()));
    
       static String forumTableName = "Forum";
       static String threadTableName = "Thread";
    
       public static void main(String[] args) throws IOException {
          retrieveMultipleItemsBatchGet();
       }
       private static void retrieveMultipleItemsBatchGet() {
          try {
             TableKeysAndAttributes forumTableKeysAndAttributes =
                new TableKeysAndAttributes(forumTableName);
    
             //Create partition key
             forumTableKeysAndAttributes.addHashOnlyPrimaryKeys (
                "Name",
                "XYZ Melt-O-tron",
                "High-Performance Processing"
             );
             TableKeysAndAttributes threadTableKeysAndAttributes =
                new TableKeysAndAttributes(threadTableName);
    
             //Create partition key and sort key
             threadTableKeysAndAttributes.addHashAndRangePrimaryKeys (
                "ForumName",
                "Subject",
                "High-Performance Processing",
                "HP Processing Thread One",
                "High-Performance Processing",
                "HP Processing Thread Two",
                "Melt-O-Tron",
                "MeltO Thread One"
             );
             System.out.println("Processing...");
             BatchGetItemOutcome outcome = dynamoDB.batchGetItem(forumTableKeysAndAttributes,
                threadTableKeysAndAttributes);
    
             Map<String, KeysAndAttributes> unprocessed = null;
             do {
                for (String tableName : outcome.getTableItems().keySet()) {
                   System.out.println("Table items for " + tableName);
                   List<Item> items = outcome.getTableItems().get(tableName);
    
                   for (Item item : items) {
                      System.out.println(item.toJSONPretty());
                   }
                }
                // Confirm no unprocessed items
                unprocessed = outcome.getUnprocessedKeys();
    
                if (unprocessed.isEmpty()) {
                   System.out.println("All items processed.");
                } else {
                   System.out.println("Gathering unprocessed items...");
                   outcome = dynamoDB.batchGetItemUnprocessed(unprocessed);
                }
             } while (!unprocessed.isEmpty());
          } catch (Exception e) {
             System.err.println("Could not get items.");
             System.err.println(e.getMessage());
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Delete Items nhận dự án làm có lương

    DynamoDB – Delete Items



    Deleting an item in the DynamoDB only requires providing the table name and the item key. It is also strongly recommended to use of a conditional expression which will be necessary to avoid deleting the wrong items.

    As usual, you can either use the GUI console, Java, or any other needed tool to perform this task.

    Delete Items Using the GUI Console

    Navigate to the console. In the navigation pane on the left side, select Tables. Then select the table name, and the Items tab.

    Delete Items Using the GUI Console

    Choose the items desired for deletion, and select Actions | Delete.

    Select Actions

    A Delete Item(s) dialog box then appears as shown in the following screeshot. Choose “Delete” to confirm.

    Delete Item

    How to Delete Items Using Java?

    Using Java in item deletion operations merely involves creating a DynamoDB client instance, and calling the deleteItem method through using the item”s key.

    You can see the following example, where it has been explained in detail.

    DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
       new ProfileCredentialsProvider()));
    
    Table table = dynamoDB.getTable("ProductList");
    DeleteItemOutcome outcome = table.deleteItem("IDnum", 151);
    

    You can also specify the parameters to protect against incorrect deletion. Simply use a ConditionExpression.

    For example −

    Map<String,Object> expressionAttributeValues = new HashMap<String,Object>();
    expressionAttributeValues.put(":val", false);
    
    DeleteItemOutcome outcome = table.deleteItem("IDnum",151,
       "Ship = :val",
       null,                   // doesn''t use ExpressionAttributeNames
       expressionAttributeValues);
    

    The following is a larger example for better understanding.

    Note − The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document;
    
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.Table;
    
    import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
    import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
    import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
    import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
    import com.amazonaws.services.dynamodbv2.model.ReturnValue;
    
    public class DeleteItemOpSample {
       static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
          new ProfileCredentialsProvider()));
    
       static String tblName = "ProductList";
       public static void main(String[] args) throws IOException {
          createItems();
          retrieveItem();
    
          // Execute updates
          updateMultipleAttributes();
          updateAddNewAttribute();
          updateExistingAttributeConditionally();
    
          // Item deletion
          deleteItem();
       }
       private static void createItems() {
          Table table = dynamoDB.getTable(tblName);
          try {
             Item item = new Item()
                .withPrimaryKey("ID", 303)
                .withString("Nomenclature", "Polymer Blaster 4000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
                .withNumber("Price", 50000)
                .withBoolean("InProduction", true)
                .withString("Category", "Laser Cutter");
                table.putItem(item);
    
             item = new Item()
                .withPrimaryKey("ID", 313)
                .withString("Nomenclature", "Agitatatron 2000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
                .withNumber("Price", 40000)
                .withBoolean("InProduction", true)
                .withString("Category", "Agitator");
                table.putItem(item);
          } catch (Exception e) {
             System.err.println("Cannot create items.");
             System.err.println(e.getMessage());
          }
       }
       private static void deleteItem() {
          Table table = dynamoDB.getTable(tableName);
          try {
             DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
                .withPrimaryKey("ID", 303)
                .withConditionExpression("#ip = :val")
                .withNameMap(new NameMap()
                .with("#ip", "InProduction"))
                .withValueMap(new ValueMap()
                .withBoolean(":val", false))
                .withReturnValues(ReturnValue.ALL_OLD);
             DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec);
    
             // Confirm
             System.out.println("Displaying deleted item...");
             System.out.println(outcome.getItem().toJSONPretty());
          } catch (Exception e) {
             System.err.println("Cannot delete item in " + tableName);
             System.err.println(e.getMessage());
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Creating Items nhận dự án làm có lương

    DynamoDB – Creating Items



    Creating an item in DynamoDB consists primarily of item and attribute specification, and the option of specifying conditions. Each item exists as a set of attributes, with each attribute named and assigned a value of a certain type.

    Value types include scalar, document, or set. Items carry a 400KB size limit, with the possibility of any amount of attributes capable of fitting within that limit. Name and value sizes (binary and UTF-8 lengths) determine item size. Using short attribute names aids in minimizing item size.

    Note − You must specify all primary key attributes, with primary keys only requiring the partition key; and composite keys requiring both the partition and sort key.

    Also, remember tables possess no predefined schema. You can store dramatically different datasets in one table.

    Use the GUI console, Java, or another tool to perform this task.

    How to Create an Item Using the GUI Console?

    Navigate to the console. In the navigation pane on the left side, select Tables. Choose the table name for use as the destination, and then select the Items tab as shown in the following screenshot.

    Create Item

    Select Create Item. The Create Item screen provides an interface for entering the required attribute values. Any secondary indices must also be entered.

    Select Create Item

    If you require more attributes, select the action menu on the left of the Message. Then select Append, and the desired data type.

    Message

    After entering all essential information, select Save to add the item.

    How to Use Java in Item Creation?

    Using Java in item creation operations consists of creating a DynamoDB class instance, Table class instance, Item class instance, and specifying the primary key and attributes of the item you will create. Then add your new item with the putItem method.

    Example

    DynamoDB dynamoDB = new DynamoDB (new AmazonDynamoDBClient(
       new ProfileCredentialsProvider()));
    Table table = dynamoDB.getTable("ProductList");
    
    // Spawn a related items list
    List<Number> RELItems = new ArrayList<Number>();
    RELItems.add(123);
    RELItems.add(456);
    RELItems.add(789);
    
    //Spawn a product picture map
    Map<String, String> photos = new HashMap<String, String>();
    photos.put("Anterior", "http://xyz.com/products/101_front.jpg");
    photos.put("Posterior", "http://xyz.com/products/101_back.jpg");
    photos.put("Lateral", "http://xyz.com/products/101_LFTside.jpg");
    
    //Spawn a product review map
    Map<String, List<String>> prodReviews = new HashMap<String, List<String>>();
    List<String> fiveStarRVW = new ArrayList<String>();
    fiveStarRVW.add("Shocking high performance.");
    fiveStarRVW.add("Unparalleled in its market.");
    prodReviews.put("5 Star", fiveStarRVW);
    List<String> oneStarRVW = new ArrayList<String>();
    oneStarRVW.add("The worst offering in its market.");
    prodReviews.put("1 Star", oneStarRVW);
    
    // Generate the item
    Item item = new Item()
       .withPrimaryKey("Id", 101)
       .withString("Nomenclature", "PolyBlaster 101")
       .withString("Description", "101 description")
       .withString("Category", "Hybrid Power Polymer Cutter")
       .withString("Make", "Brand – XYZ")
       .withNumber("Price", 50000)
       .withString("ProductCategory", "Laser Cutter")
       .withBoolean("Availability", true)
       .withNull("Qty")
       .withList("ItemsRelated", RELItems)
       .withMap("Images", photos)
       .withMap("Reviews", prodReviews);
    
    // Add item to the table
    PutItemOutcome outcome = table.putItem(item);
    

    You can also look at the following larger example.

    Note − The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    The following sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document;
    
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.Table;
    
    import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
    import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
    import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
    import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
    import com.amazonaws.services.dynamodbv2.model.ReturnValue;
    
    public class CreateItemOpSample {
       static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
          new ProfileCredentialsProvider()));
       static String tblName = "ProductList";
    
       public static void main(String[] args) throws IOException {
          createItems();
          retrieveItem();
    
          // Execute updates
          updateMultipleAttributes();
          updateAddNewAttribute();
          updateExistingAttributeConditionally();
    
          // Item deletion
          deleteItem();
       }
       private static void createItems() {
          Table table = dynamoDB.getTable(tblName);
          try {
             Item item = new Item()
                .withPrimaryKey("ID", 303)
                .withString("Nomenclature", "Polymer Blaster 4000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
                .withNumber("Price", 50000)
                .withBoolean("InProduction", true)
                .withString("Category", "Laser Cutter");
    
             table.putItem(item);
             item = new Item()
                .withPrimaryKey("ID", 313)
                .withString("Nomenclature", "Agitatatron 2000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
                .withNumber("Price", 40000)
                .withBoolean("InProduction", true)
                .withString("Category", "Agitator");
    
             table.putItem(item);
          } catch (Exception e) {
             System.err.println("Cannot create items.");
             System.err.println(e.getMessage());
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Getting Items nhận dự án làm có lương

    DynamoDB – Getting Items



    Retrieving an item in DynamoDB requires using GetItem, and specifying the table name and item primary key. Be sure to include a complete primary key rather than omitting a portion.

    For example, omitting the sort key of a composite key.

    GetItem behaviour conforms to three defaults −

    • It executes as an eventually consistent read.
    • It provides all attributes.
    • It does not detail its capacity unit consumption.

    These parameters allow you to override the default GetItem behaviour.

    Retrieve an Item

    DynamoDB ensures reliability through maintaining multiple copies of items across multiple servers. Each successful write creates these copies, but takes substantial time to execute; meaning eventually consistent. This means you cannot immediately attempt a read after writing an item.

    You can change the default eventually consistent read of GetItem, however, the cost of more current data remains consumption of more capacity units; specifically, two times as much. Note DynamoDB typically achieves consistency across every copy within a second.

    You can use the GUI console, Java, or another tool to perform this task.

    Item Retrieval Using Java

    Using Java in item retrieval operations requires creating a DynamoDB Class Instance, Table Class Instance, and calling the Table instance”s getItem method. Then specify the primary key of the item.

    You can review the following example −

    DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
       new ProfileCredentialsProvider()));
    Table table = dynamoDB.getTable("ProductList");
    Item item = table.getItem("IDnum", 109);
    

    In some cases, you need to specify the parameters for this operation.

    The following example uses .withProjectionExpression and GetItemSpec for retrieval specifications −

    GetItemSpec spec = new GetItemSpec()
       .withPrimaryKey("IDnum", 122)
       .withProjectionExpression("IDnum, EmployeeName, Department")
       .withConsistentRead(true);
    
    Item item = table.getItem(spec);
    System.out.println(item.toJSONPretty());
    

    You can also review a the following bigger example for better understanding.

    Note − The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document;
    
    import java.io.IOException
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.Table;
    
    import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
    import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
    import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
    import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
    import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
    import com.amazonaws.services.dynamodbv2.model.ReturnValue;
    
    public class GetItemOpSample {
       static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
          new ProfileCredentialsProvider()));
    
       static String tblName = "ProductList";
       public static void main(String[] args) throws IOException {
          createItems();
          retrieveItem();
    
          // Execute updates
          updateMultipleAttributes();
          updateAddNewAttribute();
          updateExistingAttributeConditionally();
    
          // Item deletion
          deleteItem();
       }
       private static void createItems() {
          Table table = dynamoDB.getTable(tblName);
          try {
             Item item = new Item()
                .withPrimaryKey("ID", 303)
                .withString("Nomenclature", "Polymer Blaster 4000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
                .withNumber("Price", 50000)
                .withBoolean("InProduction", true)
                .withString("Category", "Laser Cutter");
                table.putItem(item);
    
             item = new Item()
                .withPrimaryKey("ID", 313)
                .withString("Nomenclature", "Agitatatron 2000")
                .withStringSet( "Manufacturers",
                new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
                .withNumber("Price", 40000)
                .withBoolean("InProduction", true)
                .withString("Category", "Agitator");
    
             table.putItem(item);
          } catch (Exception e) {
             System.err.println("Cannot create items.");
             System.err.println(e.getMessage());
          }
       }
       private static void retrieveItem() {
          Table table = dynamoDB.getTable(tableName);
          try {
             Item item = table.getItem("ID", 303, "ID, Nomenclature, Manufacturers", null);
             System.out.println("Displaying retrieved items...");
             System.out.println(item.toJSONPretty());
          } catch (Exception e) {
             System.err.println("Cannot retrieve items.");
             System.err.println(e.getMessage());
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – Querying nhận dự án làm có lương

    DynamoDB – Querying



    Queries locate items or secondary indices through primary keys. Performing a query requires a partition key and specific value, or a sort key and value; with the option to filter with comparisons. The default behavior of a query consists of returning every attribute for items associated with the provided primary key. However, you can specify the desired attributes with the ProjectionExpression parameter.

    A query utilizes the KeyConditionExpression parameters to select items, which requires providing the partition key name and value in the form of an equality condition. You also have the option to provide an additional condition for any sort keys present.

    A few examples of the sort key conditions are −

    Sr.No Condition & Description
    1

    x = y

    It evaluates to true if the attribute x equals y.

    2

    x < y

    It evaluates to true if x is less than y.

    3

    x <= y

    It evaluates to true if x is less than or equal to y.

    4

    x > y

    It evaluates to true if x is greater than y.

    5

    x >= y

    It evaluates to true if x is greater than or equal to y.

    6

    x BETWEEN y AND z

    It evaluates to true if x is both >= y, and <= z.

    DynamoDB also supports the following functions: begins_with (x, substr)

    It evaluates to true if attribute x starts with the specified string.

    The following conditions must conform to certain requirements −

    • Attribute names must start with a character within the a-z or A-Z set.

    • The second character of an attribute name must fall in the a-z, A-Z, or 0-9 set.

    • Attribute names cannot use reserved words.

    Attribute names out of compliance with the constraints above can define a placeholder.

    The query processes by performing retrievals in sort key order, and using any condition and filter expressions present. Queries always return a result set, and on no matches, it returns an empty one.

    The results always return in sort key order, and data type based order with the modifiable default as the ascending order.

    Querying with Java

    Queries in Java allow you to query tables and secondary indices. They require specification of partition keys and equality conditions, with the option to specify sort keys and conditions.

    The general required steps for a query in Java include creating a DynamoDB class instance, Table class instance for the target table, and calling the query method of the Table instance to receive the query object.

    The response to the query contains an ItemCollection object providing all the returned items.

    The following example demonstrates detailed querying −

    DynamoDB dynamoDB = new DynamoDB (
       new AmazonDynamoDBClient(new ProfileCredentialsProvider()));
    
    Table table = dynamoDB.getTable("Response");
       QuerySpec spec = new QuerySpec()
       .withKeyConditionExpression("ID = :nn")
    .withValueMap(new ValueMap()
       .withString(":nn", "Product Line 1#P1 Thread 1"));
    
    ItemCollection<QueryOutcome> items = table.query(spec);
    Iterator<Item> iterator = items.iterator();
    Item item = null;
    
    while (iterator.hasNext()) {
       item = iterator.next();
       System.out.println(item.toJSONPretty());
    }
    

    The query method supports a wide variety of optional parameters. The following example demonstrates how to utilize these parameters −

    Table table = dynamoDB.getTable("Response");
    QuerySpec spec = new QuerySpec()
       .withKeyConditionExpression("ID = :nn and ResponseTM > :nn_responseTM")
       .withFilterExpression("Author = :nn_author")
       .withValueMap(new ValueMap()
       .withString(":nn", "Product Line 1#P1 Thread 1")
       .withString(":nn_responseTM", twoWeeksAgoStr)
       .withString(":nn_author", "Member 123"))
       .withConsistentRead(true);
    
    ItemCollection<QueryOutcome> items = table.query(spec);
    Iterator<Item> iterator = items.iterator();
    
    while (iterator.hasNext()) {
       System.out.println(iterator.next().toJSONPretty());
    }
    

    You can also review the following larger example.

    Note − The following program may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Iterator;
    
    import com.amazonaws.auth.profile.ProfileCredentialsProvider;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
    import com.amazonaws.services.dynamodbv2.document.DynamoDB;
    import com.amazonaws.services.dynamodbv2.document.Item;
    import com.amazonaws.services.dynamodbv2.document.ItemCollection;
    
    import com.amazonaws.services.dynamodbv2.document.Page;
    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;
    
    public class QueryOpSample {
       static DynamoDB dynamoDB = new DynamoDB(
          new AmazonDynamoDBClient(new ProfileCredentialsProvider()));
       static String tableName = "Reply";
    
       public static void main(String[] args) throws Exception {
          String forumName = "PolyBlaster";
          String threadSubject = "PolyBlaster Thread 1";
          getThreadReplies(forumName, threadSubject);
       }
       private static void getThreadReplies(String forumName, String threadSubject) {
          Table table = dynamoDB.getTable(tableName);
          String replyId = forumName + "#" + threadSubject;
          QuerySpec spec = new QuerySpec()
             .withKeyConditionExpression("Id = :v_id")
             .withValueMap(new ValueMap()
             .withString(":v_id", replyId));
    
          ItemCollection<QueryOutcome> items = table.query(spec);
          System.out.println("ngetThreadReplies results:");
          Iterator<Item> iterator = items.iterator();
    
          while (iterator.hasNext()) {
             System.out.println(iterator.next().toJSONPretty());
          }
       }
    }
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DynamoDB – API Interface nhận dự án làm có lương

    DynamoDB – API Interface



    DynamoDB offers a wide set of powerful API tools for table manipulation, data reads, and data modification.

    Amazon recommends using AWS SDKs (e.g., the Java SDK) rather than calling low-level APIs. The libraries make interacting with low-level APIs directly unnecessary. The libraries simplify common tasks such as authentication, serialization, and connections.

    Manipulate Tables

    DynamoDB offers five low-level actions for Table Management −

    • CreateTable − This spawns a table and includes throughput set by the user. It requires you to set a primary key, whether composite or simple. It also allows one or multiple secondary indexes.

    • ListTables − This provides a list of all tables in the current AWS user”s account and tied to their endpoint.

    • UpdateTable − This alters throughput, and global secondary index throughput.

    • DescribeTable − This provides table metadata; for example, state, size, and indices.

    • DeleteTable − This simply erases the table and its indices.

    Read Data

    DynamoDB offers four low-level actions for data reading −

    • GetItem − It accepts a primary key and returns attributes of the associated item. It permits changes to its default eventually consistent read setting.

    • BatchGetItem − It executes several GetItem requests on multiple items through primary keys, with the option of one or multiple tables. Its returns no more than 100 items and must remain under 16MB. It permits eventually consistent and strongly consistent reads.

    • Scan − It reads all the table items and produces an eventually consistent result set. You can filter results through conditions. It avoids the use of an index and scans the entire table, so do not use it for queries requiring predictability.

    • Query − It returns a single or multiple table items or secondary index items. It uses a specified value for the partition key, and permits the use of comparison operators to narrow scope. It includes support for both types of consistency, and each response obeys a 1MB limit in size.

    Modify Data

    DynamoDB offers four low-level actions for data modification −

    • PutItem − This spawns a new item or replaces existing items. On discovery of identical primary keys, by default, it replaces the item. Conditional operators allow you to work around the default, and only replace items under certain conditions.

    • BatchWriteItem − This executes both multiple PutItem and DeleteItem requests, and over several tables. If one request fails, it does not impact the entire operation. Its cap sits at 25 items, and 16MB in size.

    • UpdateItem − It changes the existing item attributes, and permits the use of conditional operators to execute updates only under certain conditions.

    • DeleteItem − It uses the primary key to erase an item, and also allows the use of conditional operators to specify the conditions for deletion.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc