/** * Queries an Amazon DynamoDB table and returns the matching results as an * unmodifiable list of instantiated objects. * @param queryExpression The query expression. * @return The query results. * @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#query */ public PaginatedQueryList<T> query(DynamoDBQueryExpression<T> queryExpression) { return mapper.<T>query(model.targetType(), queryExpression); }
@Test public void testListEnvironmentsEmptyResult() throws Exception { when(environmentDDBRecords.stream()).thenReturn(Stream.empty()); doReturn(environmentDDBRecords) .when(dynamoDBMapper) .query(eq(EnvironmentDDBRecord.class), any()); final List<Environment> result = environmentRepositoryDDB.listEnvironments(cluster, null); verify(dynamoDBMapper).query(eq(EnvironmentDDBRecord.class), any()); verify(environmentMapper, never()).toEnvironment(environmentDDBRecord); assertThat(result.size()).isEqualTo(0); }
@Override public List<EnvironmentRevision> listEnvironmentRevisions( @NonNull final EnvironmentId environmentId) throws InternalServiceException { try { return dynamoDBMapper .query( EnvironmentRevisionDDBRecord.class, new DynamoDBQueryExpression<EnvironmentRevisionDDBRecord>() .withHashKeyValues( EnvironmentRevisionDDBRecord.withHashKey( environmentId.generateAccountIdClusterEnvironmentName()))) .stream() .map(environmentMapper::toEnvironmentRevision) .collect(Collectors.toList()); } catch (final AmazonServiceException e) { throw new InternalServiceException( String.format( "Could not query environment revisions for environment %s", environmentId.toString()), e); } }
@Test public void testListEnvironmentsInternalError() throws Exception { doThrow(AmazonServiceException.class) .when(dynamoDBMapper) .query(eq(EnvironmentDDBRecord.class), any()); thrown.expect(InternalServiceException.class); thrown.expectMessage( String.format("Could not query environments for cluster %s", cluster.toString())); environmentRepositoryDDB.listEnvironments(cluster, null); }
@Test public void testListEnvironmentsWithoutEnvironmentNamePrefix() throws Exception { when(environmentDDBRecords.stream()).thenReturn(Stream.of(environmentDDBRecord)); doReturn(environmentDDBRecords) .when(dynamoDBMapper) .query(eq(EnvironmentDDBRecord.class), any()); when(environmentMapper.toEnvironment(environmentDDBRecord)).thenReturn(environment); final List<Environment> result = environmentRepositoryDDB.listEnvironments(cluster, null); verify(dynamoDBMapper) .query(eq(EnvironmentDDBRecord.class), ddbQueryExpressionCaptor.capture()); verify(environmentMapper).toEnvironment(environmentDDBRecord); final EnvironmentDDBRecord queriedEnvironmentDDBRecord = ddbQueryExpressionCaptor.getValue().getHashKeyValues(); assertThat(ddbQueryExpressionCaptor.getValue().getRangeKeyConditions()).isNull(); assertThat(queriedEnvironmentDDBRecord.getAccountIdCluster()) .isEqualTo(cluster.generateAccountIdCluster()); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0)).isEqualTo(environment); }
@Override public List<Environment> listEnvironments( @NonNull final Cluster cluster, final String environmentNamePrefix) throws InternalServiceException { try { final DynamoDBQueryExpression<EnvironmentDDBRecord> queryExpression = new DynamoDBQueryExpression<EnvironmentDDBRecord>() .withHashKeyValues( EnvironmentDDBRecord.withHashKeys(cluster.generateAccountIdCluster())); if (environmentNamePrefix != null) { queryExpression.withRangeKeyCondition( ENVIRONMENT_NAME_RANGE_KEY, new Condition() .withComparisonOperator(ComparisonOperator.BEGINS_WITH) .withAttributeValueList(new AttributeValue().withS(environmentNamePrefix))); } return dynamoDBMapper .query(EnvironmentDDBRecord.class, queryExpression) .stream() .map(environmentMapper::toEnvironment) .collect(Collectors.toList()); } catch (final AmazonServiceException e) { throw new InternalServiceException( String.format("Could not query environments for cluster %s", cluster.toString()), e); } }
@Test public void testListEnvironmentsWithEnvironmentNamePrefix() throws Exception { final String environmentNamePrefix = "environmentNamePrefix"; when(environmentDDBRecords.stream()).thenReturn(Stream.of(environmentDDBRecord)); doReturn(environmentDDBRecords) .when(dynamoDBMapper) .query(eq(EnvironmentDDBRecord.class), any()); when(environmentMapper.toEnvironment(environmentDDBRecord)).thenReturn(environment); final List<Environment> result = environmentRepositoryDDB.listEnvironments(cluster, environmentNamePrefix); verify(dynamoDBMapper) .query(eq(EnvironmentDDBRecord.class), ddbQueryExpressionCaptor.capture()); verify(environmentMapper).toEnvironment(environmentDDBRecord); final EnvironmentDDBRecord queriedEnvironmentDDBRecord = ddbQueryExpressionCaptor.getValue().getHashKeyValues(); final Map<String, Condition> queryConditions = ddbQueryExpressionCaptor.getValue().getRangeKeyConditions(); assertThat(queriedEnvironmentDDBRecord.getAccountIdCluster()) .isEqualTo(cluster.generateAccountIdCluster()); assertThat(queryConditions).isNotEmpty().hasSize(1); assertThat(queryConditions).containsKey(ENVIRONMENT_NAME_RANGE_KEY); assertThat(queryConditions) .containsValue( new Condition() .withComparisonOperator(ComparisonOperator.BEGINS_WITH) .withAttributeValueList(new AttributeValue().withS(environmentNamePrefix))); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0)).isEqualTo(environment); }
.withAttributeValueList(new AttributeValue().withS(clusterNamePrefix))); clusters = dynamoDBMapper.query(EnvironmentDDBRecord.class, query);
@Override public <T> PaginatedQueryList<T> query(Class<T> domainClass, DynamoDBQueryExpression<T> queryExpression) { PaginatedQueryList<T> results = dynamoDBMapper.query(domainClass, queryExpression); maybeEmitEvent(results, AfterQueryEvent::new); return results; }
/** * Queries an Amazon DynamoDB table and returns the matching results as an * unmodifiable list of instantiated objects. * @param queryExpression The query expression. * @return The query results. * @see com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper#query */ public PaginatedQueryList<T> query(DynamoDBQueryExpression<T> queryExpression) { return mapper.<T>query(model.targetType(), queryExpression); }
@Override public <T> PaginatedQueryList<T> query(Class<T> domainClass, DynamoDBQueryExpression<T> queryExpression) { PaginatedQueryList<T> results = dynamoDBMapper.query(domainClass, queryExpression); maybeEmitEvent(new AfterQueryEvent<T>(results)); return results; }
AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider()); DynamoDBMapper mapper = new DynamoDBMapper(client); String hashKey = "123"; long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L); Date twoWeeksAgo = new Date(); twoWeeksAgo.setTime(twoWeeksAgoMilli); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); String twoWeeksAgoStr = dateFormatter.format(twoWeeksAgo); Condition rangeKeyCondition = new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr.toString())); Reply replyKey = new Reply(); replyKey.setId(hashKey); DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>() .withHashKeyValues(replyKey) .withRangeKeyCondition("ReplyDateTime", rangeKeyCondition); List<Reply> latestReplies = mapper.query(Reply.class, queryExpression);
.withConsistentRead(false); return mapper.query(SongDatabaseMappingAdapter.class, queryExpression);
@Override public List<Event> findEventsByTeam(String team) { DynamoDBQueryExpression<Event> homeQuery = new DynamoDBQueryExpression<>(); Event eventKey = new Event(); eventKey.setHomeTeam(team); homeQuery.setHashKeyValues(eventKey); List<Event> homeEvents = mapper.query(Event.class, homeQuery); Map<String, AttributeValue> eav = new HashMap<>(); eav.put(":v1", new AttributeValue().withS(team)); DynamoDBQueryExpression<Event> awayQuery = new DynamoDBQueryExpression<Event>() .withIndexName(Event.AWAY_TEAM_INDEX) .withConsistentRead(false) .withKeyConditionExpression("awayTeam = :v1") .withExpressionAttributeValues(eav); List<Event> awayEvents = mapper.query(Event.class, awayQuery); // need to create a new list because PaginatedList from query is immutable List<Event> allEvents = new LinkedList<>(); allEvents.addAll(homeEvents); allEvents.addAll(awayEvents); allEvents.sort( (e1, e2) -> e1.getEventDate() <= e2.getEventDate() ? -1 : 1 ); return allEvents; }
private static void FindRepliesInLast15Days(DynamoDBMapper mapper, String forumName, String threadSubject) throws Exception { System.out.println("FindRepliesInLast15Days: Replies within last 15 days."); String hashKey = forumName + "#" + threadSubject; long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L); Date twoWeeksAgo = new Date(); twoWeeksAgo.setTime(twoWeeksAgoMilli); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); String twoWeeksAgoStr = dateFormatter.format(twoWeeksAgo); Condition rangeKeyCondition = new Condition() .withComparisonOperator(ComparisonOperator.GT.toString()) .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr.toString())); Reply replyKey = new Reply(); replyKey.setId(hashKey); DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>() .withHashKeyValues(replyKey) .withRangeKeyCondition("ReplyDateTime", rangeKeyCondition); List<Reply> latestReplies = mapper.query(Reply.class, queryExpression); for (Reply reply : latestReplies) { System.out.format("Id=%s, Message=%s, PostedBy=%s %n, ReplyDateTime=%s %n", reply.getId(), reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime() ); } }
public static void main(String [] args) { AmazonDynamoDBClient client = new AmazonDynamoDBClient(new BasicAWSCredentials("akey1", "skey1")); client.setEndpoint("http://localhost:8000"); DynamoDBMapper mapper = new DynamoDBMapper(client); client.createTable(new CreateTableRequest() .withTableName("nested-data-test") .withAttributeDefinitions(new AttributeDefinition().withAttributeName("desc").withAttributeType("S")) .withKeySchema(new KeySchemaElement().withKeyType("HASH").withAttributeName("desc")) .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L))); NestedData u = new NestedData(); u.setDesc("else"); Map<String, String> c = new HashMap<String, String>(); c.put("type", "some"); u.setConf(c); mapper.save(u); DynamoDBQueryExpression<NestedData> queryExpression = new DynamoDBQueryExpression<NestedData>(); queryExpression.withHashKeyValues(u); queryExpression.withFilterExpression("conf.#t = :type") .addExpressionAttributeNamesEntry("#t", "type") // returns nothing if use "Type" .addExpressionAttributeValuesEntry(":type", new AttributeValue("some")); for(NestedData u2 : mapper.query(NestedData.class, queryExpression)) { System.out.println(u2.getDesc()); // "else" } }
@Override public List<Event> findEventsByCity(String city) { Map<String, AttributeValue> eav = new HashMap<>(); eav.put(":v1", new AttributeValue().withS(city)); DynamoDBQueryExpression<Event> query = new DynamoDBQueryExpression<Event>() .withIndexName(Event.CITY_INDEX) .withConsistentRead(false) .withKeyConditionExpression("city = :v1") .withExpressionAttributeValues(eav); return mapper.query(Event.class, query); // NOTE: without an index, this query would require a full table scan with a filter: /* DynamoDBScanExpression scanExpression = new DynamoDBScanExpression() .withFilterExpression("city = :val1") .withExpressionAttributeValues(eav); return mapper.scan(Event.class, scanExpression); */ }
.withRangeKeyCondition("ReplyDateTime", rangeKeyCondition); List<Reply> betweenReplies = mapper.query(Reply.class, queryExpression);