Query Date Range in DynamoDB Using Java (Guide w/ Code Examples)
![Rafal Wilinski](https://pbs.twimg.com/profile_images/1390706809548197895/SVCKpLNE_400x400.png)
Provided by Rafal Wilinski
This example queries the MyTable
table for items where the date
attribute is between one month ago and now. The Calendar
class is used to get the current date and a date one month ago, which are then passed as parameters to the query.
import java.util.Calendar; import java.util.HashMap; import java.util.Map; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.QueryRequest; import com.amazonaws.services.dynamodbv2.model.QueryResult; public class QueryDateRangeExample { public static void main(String[] args) { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); Calendar calendar = Calendar.getInstance(); java.util.Date now = calendar.getTime(); calendar.add(Calendar.MONTH, -1); java.util.Date oneMonthAgo = calendar.getTime(); Map<String, AttributeValue> attributeValues = new HashMap<>(); attributeValues.put(":start", new AttributeValue().withS(oneMonthAgo.toString())); attributeValues.put(":end", new AttributeValue().withS(now.toString())); QueryRequest queryRequest = new QueryRequest() .withTableName("MyTable") .withKeyConditionExpression("date BETWEEN :start AND :end") .withExpressionAttributeValues(attributeValues); QueryResult result = client.query(queryRequest); result.getItems().forEach(item -> System.out.println(item)); } }
Similar Code Examples
- Batch Update Using DynamoDB Mapper
- GetItem in DynamoDB Using Java
- Query Global Secondary Index in DynamoDB Using Java
- Get Multiple Items in DynamoDB Using Java
- Delete in DynamoDB Using Java
- Remove Attribute in DynamoDB Using Java
- Conditional Update in DynamoDB Using Java
- Update Multiple Attributes in DynamoDB Using Java
- Delete Record in DynamoDB Using Java
- Batch Put Item in DynamoDB Using Java
- Query Index in DynamoDB Using Java
- Query Hash Key Only in DynamoDB Using Java
- Delete Expression in DynamoDB Using Java
- Update Expression in DynamoDB Using Java
- Batch Delete Using DynamoDB Mapper
Tired of switching accounts and regions? Use Dynobase.
Try 7-day free trial. No strings attached.
Product Features
DynamoDB Tools
DynamoDB Info
© 2024 Dynobase