Delete items from dynamodb based on date - amazon-dynamodb

I am new to dynamodb, I am able to delete an item based on key.
Below is the code snippet:
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("hash", new AttributeValue().withS("hashEncodedStringValue"));
DeleteItemRequest deleteItemRequest = new DeleteItemRequest().withTableName("HashTable").withKey(key);
I need to delete items less than 7 days old from my table. And my table has a field called 'created_at' in this format "2017-10-25 14:54:52.278"

If you want dynamodb to delete it automatically after 7 days you can create TTL field and update the timestamp, dynamodb will automatically delete it.
Reference:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/howitworks-ttl.html
CRUD Operations with Java:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPICRUDExample.html
Hope it helps.

Related

Unable to Upsert data in DynamoDB using WriteRequest JAVA

I have a java application which is building a DynamoDB client write request as
WriteRequest.builder().putRequest(PutRequest.builder().item(attributeValueMap).build()).build();
The above request is replacing the items with same PartitionKey and SortKey instead of upserting the data into the table. Any idea what am I doing wrong or do I need a to pass any additional parameter in PutRequest ?
As the commenter mentions, you want to use UpdateItem if you want to "patch" an item. PutItem will replace the entire item. You can read more about the differences here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData
This is a simplified code sample for how that works in Javav2 SDK.
HashMap<String,AttributeValue> itemKey = new HashMap<>();
itemKey.put(key, AttributeValue.builder()
.s(keyVal)
.build());
HashMap<String,AttributeValueUpdate> updatedValues = new HashMap<>();
// Put your attributes/values you wish to update here.
// Attributes you don't include won't be effected by the update
updatedValues.put(name, AttributeValueUpdate.builder()
.value(AttributeValue.builder().s(updateVal).build())
.action(AttributeAction.PUT)
.build());
UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(tableName)
.key(itemKey)
.attributeUpdates(updatedValues)
.build();
ddb.updateItem(request);

How to clone a record and create a new records in app maker?

I have a table. I want to clone a record. I added a button and in the OnClick event I have tried
var rowDataSource = widget.datasource;
// Instead of using the row datasource for create, explicitly use the data source of your list.
var listDatasource = app.datasources.Change;
var createDataSource = listDatasource.modes.create;
createDataSource.item.Systems.SystemName = rowDataSource.item.Systems.SystemName;
createDataSource.item.changeType = rowDataSource.item.changeType;
widget.datasource.createItem();
widget.datasource.saveChanges();
But this gave me error
can't associate Data with Draft Records since I am using relational Database and my databases are in manual save mode.
How to clone all field from one record and create a new record??
Here Author name comes from the relational database and Timestamp is from the tables database.

Updating multiple records in DynamoDB

How can i update multiple records in DynamoDB in single query?
I have a csv file as an input based on the csv file I have to update multiple records(only one attribute) in the DB.
Is there any API available for this?
or This can be done using batch processing(Spring-batch)?
DynamoDB doesn't have batchUpdate API directly. It does have batch get item and batch write item API.
However, you can use batchWriteItem API to update the item.
1) Use the below BatchWriteItemSpec class to construct the request
BatchWriteItemSpec
2) Use the below TableWriteItems class to construct the item that need to be updated
TableWriteItems
3) Use the below addItemToPut method (or withItemsToPut) to add the new attribute
addItemToPut
The batchWriteItem API creates a new item if the item (i.e. partition key) is not available. If the partition key is available, it will update the existing item. Your use case falls under this category.
Code Sample:-
files - is the the table name
fileName - is the partition key
transcriptionnew - Adding the new attribute (or can update the existing attribute value as well)
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
Item itemUpdate1 = new Item();
itemUpdate1.withKeyComponent("fileName", "file1")
.withString("transcriptionnew", "new value");
Item itemUpdate2 = new Item();
itemUpdate2.withKeyComponent("fileName", "file2")
.withString("transcriptionnew", "new value");
TableWriteItems tableWriteItems = new TableWriteItems("files").withItemsToPut(itemUpdate1, itemUpdate2);
BatchWriteItemSpec batchWriteItemSpec = new BatchWriteItemSpec().withTableWriteItems(tableWriteItems);
BatchWriteItemOutcome batchWriteItemOutCome = dynamoDB.batchWriteItem(batchWriteItemSpec);
if (batchWriteItemOutCome.getUnprocessedItems().isEmpty()) {
//All items are processed
return true;
}

Updating Cassandra Map Value through querybuilder

Cassandra support updating specific value in Collection by syntax
ALTER TABLE users ADD todo map<timestamp, text>
UPDATE users SET todo['2012-10-2 12:00'] = 'throw my precious into mount doom'
WHERE user_id = 'frodo';
http://www.datastax.com/documentation/cql/3.0/cql/cql_using/use_map_t.html
Did not see any example of using QueryBuilder to update specific row in Map. How it can be done?
I think you have several options.
1/ Build your own query based on the CQL one.
Example: Consider that you have a table named Interactions and in your schema a column of type named 'attributes'.
String update ="UPDATE demo.Interactions SET attributes=attributes + {'i':'j'} where id='ff';
SimpleStatement statement = new SimpleStatement(update);
session.execute(statement);
2/ Use Java API.
Java API is not that documented indeed.
Let's take an example
a- Create an update object using queryBuilder
Update update = QueryBuilder.update(keyspace, tableName);
b- Then populate with 'put' or 'putAll' functions. put/putAll will add/update content
update.with(QueryBuilder.putAll(key, map));
To remove a key, set the content of a key to null, like:
for (Object item : map.keySet()) {
update.with(
QueryBuilder.put(columName, item, null)
);
}
Then execute the query.
Following methods are available for different types:
LIST:
QueryBuilder.appendAll(...)
QueryBuilder.discardAll(...)
SET:
QueryBuilder.addAll(...)
QueryBuilder.removeAll(...)
MAP:
QueryBuilder.putAll(...)
QueryBuilder.put(...)
The list is not exhautive.
Have a look in QueryBuilder class if you do not find what you are looking for.
Best regards and best luck with Cassandra.

How to query range key programmatically in DynamoDB

How to query range key programmatically in DynamoDB, I am using .Net AWSSDK ,I am able to query on Hash key with below code :
GetItemRequest request = new GetItemRequest
{
TableName = tableName
};
request.Key = new Dictionary<string,AttributeValue>();
request.Key.Add("ID",new AttributeValue { S = PKValue });
GetItemResponse response = client.GetItem(request);
Please suggest,
Thanks in advance.
There are two kinds of primary key in DynamoDB: Hash-only or Hash-Range.
In the above code I guess your table is Hash-only and you use the hash key to retrieve an element with hashkey equals to PKValue.
If your table is in H-R schema and you want to retrieve a specific element with a hashKey and rangeKey, you can reuse the above code and in addition, add the {"RangeKey", new AttributeValue } into your your request.KEY
On the other hand, query means a different thing in DynamoDB. Query will return you a list of rows sorted in some order.

Resources