com.amazonaws.services.dynamodbv2.model.ComparisonOperator Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.model.ComparisonOperator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LowLevelQuery.java    From aws-dynamodb-examples with Apache License 2.0 8 votes vote down vote up
private static void findRepliesForAThread(String forumName, String threadSubject) {

        String replyId = forumName + "#" + threadSubject;
        
        Condition hashKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withS(replyId));
        
        Map<String, Condition> keyConditions = new HashMap<String, Condition>();
        keyConditions.put("Id", hashKeyCondition);
        
        QueryRequest queryRequest = new QueryRequest()
            .withTableName(tableName)
            .withKeyConditions(keyConditions);

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }
    }
 
Example #2
Source File: LowLevelQuery.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(String forumName, String threadSubject) {

        long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);

        Condition rangeKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.GT.toString())
            .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr));
        
        Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);
        keyConditions.put("ReplyDateTime", rangeKeyCondition);
        
        QueryRequest queryRequest = new QueryRequest().withTableName(tableName)
            .withKeyConditions(keyConditions)
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }

    }
 
Example #3
Source File: DynamoDBReader.java    From geowave with Apache License 2.0 6 votes vote down vote up
private List<QueryRequest> getAdapterOnlyQueryRequests(
    final String tableName,
    final ArrayList<Short> internalAdapterIds) {
  final List<QueryRequest> allQueries = new ArrayList<>();

  for (final short internalAdapterId : internalAdapterIds) {
    final QueryRequest singleAdapterQuery = new QueryRequest(tableName);

    final byte[] start = ByteArrayUtils.shortToByteArray(internalAdapterId);
    final byte[] end = new ByteArray(start).getNextPrefix();
    singleAdapterQuery.addKeyConditionsEntry(
        DynamoDBRow.GW_RANGE_KEY,
        new Condition().withComparisonOperator(ComparisonOperator.BETWEEN).withAttributeValueList(
            new AttributeValue().withB(ByteBuffer.wrap(start)),
            new AttributeValue().withB(ByteBuffer.wrap(end))));

    allQueries.add(singleAdapterQuery);
  }

  return allQueries;
}
 
Example #4
Source File: ObjectPersistenceQueryScanExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void FindBicyclesOfSpecificTypeWithMultipleThreads(
        DynamoDBMapper mapper, 
        int numberOfThreads,
        String bicycleType) throws Exception {
 
    System.out.println("FindBicyclesOfSpecificTypeWithMultipleThreads: Scan ProductCatalog With Multiple Threads.");
            
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
    scanExpression.addFilterCondition("ProductCategory", 
            new Condition()
                .withComparisonOperator(ComparisonOperator.EQ)
                .withAttributeValueList(new AttributeValue().withS("Bicycle")));
    scanExpression.addFilterCondition("BicycleType", 
            new Condition()
                .withComparisonOperator(ComparisonOperator.EQ)
                .withAttributeValueList(new AttributeValue().withS(bicycleType)));
    List<Bicycle> scanResult = mapper.parallelScan(Bicycle.class, scanExpression, numberOfThreads);
    for (Bicycle bicycle : scanResult) {
        System.out.println(bicycle);
    }
}
 
Example #5
Source File: MapperLoadingStrategyConfigITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
private static PaginatedList<RangeKeyTestClass> getTestPaginatedParallelScanList(PaginationLoadingStrategy paginationLoadingStrategy) {
    DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT);
    DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig);
    
    // Construct the scan expression with the exact same conditions
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
    scanExpression.addFilterCondition("key", 
            new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(
                    new AttributeValue().withN(Long.toString(hashKey))));
    scanExpression.addFilterCondition("rangeKey", 
            new Condition().withComparisonOperator(ComparisonOperator.GT).withAttributeValueList(
                    new AttributeValue().withN("1.0")));
    scanExpression.setLimit(PAGE_SIZE);
    
    return mapper.parallelScan(RangeKeyTestClass.class, scanExpression, PARALLEL_SEGMENT, new DynamoDBMapperConfig(paginationLoadingStrategy));
}
 
Example #6
Source File: ObjectPersistenceQueryScanExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void FindBooksPricedLessThanSpecifiedValue(
        DynamoDBMapper mapper,
        String value) throws Exception {
 
    System.out.println("FindBooksPricedLessThanSpecifiedValue: Scan ProductCatalog.");
            
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
    scanExpression.addFilterCondition("Price", 
            new Condition()
               .withComparisonOperator(ComparisonOperator.LT)
               .withAttributeValueList(new AttributeValue().withN(value)));
    scanExpression.addFilterCondition("ProductCategory", 
            new Condition()
                .withComparisonOperator(ComparisonOperator.EQ)
                .withAttributeValueList(new AttributeValue().withS("Book")));
    List<Book> scanResult = mapper.scan(Book.class, scanExpression);
    
    for (Book book : scanResult) {
        System.out.println(book);
    }
}
 
Example #7
Source File: DynamoDBEntityWithHashAndRangeKeyCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public DynamoDBQueryCriteria<T, ID> withPropertyEquals(String propertyName, Object value, Class<?> propertyType) {
	if (isHashKeyProperty(propertyName)) {
		return withHashKeyEquals(value);
	} else if (isRangeKeyProperty(propertyName)) {
		return withRangeKeyEquals(value);
	} else if (entityInformation.isCompositeHashAndRangeKeyProperty(propertyName)) {
		Assert.notNull(value,
				"Creating conditions on null composite id properties not supported: please specify a value for '"
						+ propertyName + "'");
		Object hashKey = entityInformation.getHashKey((ID) value);
		Object rangeKey = entityInformation.getRangeKey((ID) value);
		if (hashKey != null) {
			withHashKeyEquals(hashKey);
		}
		if (rangeKey != null) {
			withRangeKeyEquals(rangeKey);
		}
		return this;
	} else {
		Condition condition = createSingleValueCondition(propertyName, ComparisonOperator.EQ, value, propertyType, false);
		return withCondition(propertyName, condition);
	}

}
 
Example #8
Source File: DynamoDBEntityWithHashKeyOnlyCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
public DynamoDBScanExpression buildScanExpression() {

		if (sort != null) {
			throw new UnsupportedOperationException("Sort not supported for scan expressions");
		}

		DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
		if (isHashKeySpecified()) {
			scanExpression.addFilterCondition(
					getHashKeyAttributeName(),
					createSingleValueCondition(getHashKeyPropertyName(), ComparisonOperator.EQ, getHashKeyAttributeValue(),
							getHashKeyAttributeValue().getClass(), true));
		}

		for (Map.Entry<String, List<Condition>> conditionEntry : attributeConditions.entrySet()) {
			for (Condition condition : conditionEntry.getValue()) {
				scanExpression.addFilterCondition(conditionEntry.getKey(), condition);
			}
		}
		return scanExpression;
	}
 
Example #9
Source File: ScanITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests scanning the table with AND/OR logic operator.
 */
@Test
public void testScanWithConditionalOperator() {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
        .withLimit(SCAN_LIMIT)
        .withScanFilter(ImmutableMapParameter.of(
                "value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL),
                "non-existent-field", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL)
                ))
        .withConditionalOperator(ConditionalOperator.AND);

    List<SimpleClass> andConditionResult = mapper.scan(SimpleClass.class, scanExpression);
    assertTrue(andConditionResult.isEmpty());

    List<SimpleClass> orConditionResult = mapper.scan(SimpleClass.class,
            scanExpression.withConditionalOperator(ConditionalOperator.OR));
    assertFalse(orConditionResult.isEmpty());
}
 
Example #10
Source File: AbstractDynamoDBQueryCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
protected List<Condition> getHashKeyConditions() {
	List<Condition> hashKeyConditions = null;
	if (isApplicableForGlobalSecondaryIndex()
			&& entityInformation.getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getHashKeyPropertyName())) {
		hashKeyConditions = getHashKeyAttributeValue() == null ? null : Arrays.asList(createSingleValueCondition(
				getHashKeyPropertyName(), ComparisonOperator.EQ, getHashKeyAttributeValue(), getHashKeyAttributeValue()
						.getClass(), true));
		if (hashKeyConditions == null) {
			if (attributeConditions.containsKey(getHashKeyAttributeName())) {
				hashKeyConditions = attributeConditions.get(getHashKeyAttributeName());
			}

		}

	}
	return hashKeyConditions;
}
 
Example #11
Source File: DynamoDBEntityWithHashAndRangeKeyCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
public DynamoDBScanExpression buildScanExpression() {

		if (sort != null) {
			throw new UnsupportedOperationException("Sort not supported for scan expressions");
		}
		DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
		if (isHashKeySpecified()) {
			scanExpression.addFilterCondition(
					getHashKeyAttributeName(),
					createSingleValueCondition(getHashKeyPropertyName(), ComparisonOperator.EQ, getHashKeyAttributeValue(),
							getHashKeyAttributeValue().getClass(), true));
		}
		if (isRangeKeySpecified()) {
			scanExpression.addFilterCondition(
					getRangeKeyAttributeName(),
					createSingleValueCondition(getRangeKeyPropertyName(), ComparisonOperator.EQ, getRangeKeyAttributeValue(),
							getRangeKeyAttributeValue().getClass(), true));
		}
		for (Map.Entry<String, List<Condition>> conditionEntry : attributeConditions.entrySet()) {
			for (Condition condition : conditionEntry.getValue()) {
				scanExpression.addFilterCondition(conditionEntry.getKey(), condition);
			}
		}
		return scanExpression;
	}
 
Example #12
Source File: HashKeyOnlyTableWithGSIITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that we can query using the hash/range GSI on our hash-key only
 * table.
 */
@Test
public void testGSIQuery() throws Exception {
    DynamoDBMapper mapper = TestDynamoDBMapperFactory
            .createDynamoDBMapper(dynamo);
    String status = "foo-status";

    User user = new User();
    user.setId("123");
    user.setStatus(status);
    user.setTs("321");
    mapper.save(user);

    DynamoDBQueryExpression<User> expr = new DynamoDBQueryExpression<User>()
            .withIndexName("statusAndCreation")
            .withLimit(100)
            .withConsistentRead(false)
            .withHashKeyValues(user)
            .withRangeKeyCondition(
                    "ts",
                    new Condition()
                    .withComparisonOperator(ComparisonOperator.GT)
                    .withAttributeValueList(new AttributeValue("100")));

    PaginatedQueryList<User> query = mapper.query(User.class, expr);
    int size = query.size();
    if (DEBUG)
        System.err.println("size=" + size);
    assertTrue(1 == size);
    assertEquals(status, query.get(0).getStatus());
}
 
Example #13
Source File: MetaStore.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Override
public long getMaxVersion(final String materialName) {
    final List<Map<String, AttributeValue>> items = ddb.query(
            new QueryRequest()
            .withTableName(tableName)
            .withConsistentRead(Boolean.TRUE)
            .withKeyConditions(
                    Collections.singletonMap(
                            DEFAULT_HASH_KEY,
                            new Condition().withComparisonOperator(
                                    ComparisonOperator.EQ).withAttributeValueList(
                                            new AttributeValue().withS(materialName))))
                                            .withLimit(1).withScanIndexForward(false)
                                            .withAttributesToGet(DEFAULT_RANGE_KEY)).getItems();
    if (items.isEmpty()) {
        return -1L;
    } else {
        return Long.parseLong(items.get(0).get(DEFAULT_RANGE_KEY).getN());
    }
}
 
Example #14
Source File: SingleExpectedAttributeValueBuilder.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 6 votes vote down vote up
private void addExpectedValueIfPresent(final StaticBuffer column, final Map<String, ExpectedAttributeValue> expectedValueMap) {
    final String dynamoDbColumn = encodeKeyBuffer(column);

    if (expectedValueMap.containsKey(dynamoDbColumn)) {
        return;
    }

    if (transaction.contains(store, key, column)) {
        final StaticBuffer expectedValue = transaction.get(store, key, column);
        final ExpectedAttributeValue expectedAttributeValue;
        if (expectedValue == null) {
            expectedAttributeValue = new ExpectedAttributeValue().withExists(false);
        } else {
            final AttributeValue attributeValue = encodeValue(expectedValue);
            expectedAttributeValue = new ExpectedAttributeValue().withValue(attributeValue)
                                                                 .withComparisonOperator(ComparisonOperator.EQ);
        }
        expectedValueMap.put(dynamoDbColumn, expectedAttributeValue);
    }
}
 
Example #15
Source File: AbstractDynamoDBQueryCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
protected Condition createSingleValueCondition(String propertyName, ComparisonOperator comparisonOperator, Object o,
		Class<?> propertyType, boolean alreadyMarshalledIfRequired) {

	Assert.notNull(o, "Creating conditions on null property values not supported: please specify a value for '"
			+ propertyName + "'");

	Object attributeValue = !alreadyMarshalledIfRequired ? getPropertyAttributeValue(propertyName, o) : o;

	boolean marshalled = !alreadyMarshalledIfRequired && attributeValue != o
			&& !entityInformation.isCompositeHashAndRangeKeyProperty(propertyName);

	Class<?> targetPropertyType = marshalled ? String.class : propertyType;
	List<AttributeValue> attributeValueList = new ArrayList<AttributeValue>();
	attributeValueList = addAttributeValue(attributeValueList, attributeValue, propertyName, targetPropertyType, true);
	return new Condition().withComparisonOperator(comparisonOperator).withAttributeValueList(attributeValueList);

}
 
Example #16
Source File: LowLevelQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesPostedWithinTimePeriod(String forumName, String threadSubject) {

        long startDateMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        long endDateMilli = (new Date()).getTime() - (5L * 24L * 60L * 60L * 1000L);
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String startDate = df.format(startDateMilli);
        String endDate = df.format(endDateMilli);

        Condition sortKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN.toString())
            .withAttributeValueList(new AttributeValue().withS(startDate), new AttributeValue().withS(endDate));

        Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);
        keyConditions.put("ReplyDateTime", sortKeyCondition);

        QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(keyConditions)
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }
    }
 
Example #17
Source File: LowLevelQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(String forumName, String threadSubject) {

        long twoWeeksAgoMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);

        Condition sortKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
            .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr));

        Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);
        keyConditions.put("ReplyDateTime", sortKeyCondition);

        QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(keyConditions)
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }

    }
 
Example #18
Source File: LowLevelQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesForAThread(String forumName, String threadSubject) {

        String replyId = forumName + "#" + threadSubject;

        Condition partitionKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withS(replyId));

        Map<String, Condition> keyConditions = new HashMap<String, Condition>();
        keyConditions.put("Id", partitionKeyCondition);

        QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(keyConditions);

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }
    }
 
Example #19
Source File: AbstractDynamoDBQueryCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
protected Condition createCollectionCondition(String propertyName, ComparisonOperator comparisonOperator, Iterable<?> o,
		Class<?> propertyType) {

	Assert.notNull(o, "Creating conditions on null property values not supported: please specify a value for '"
			+ propertyName + "'");
	List<AttributeValue> attributeValueList = new ArrayList<AttributeValue>();
	boolean marshalled = false;
	for (Object object : o) {
		Object attributeValue = getPropertyAttributeValue(propertyName, object);
		if (attributeValue != null) {
			marshalled = attributeValue != object && !entityInformation.isCompositeHashAndRangeKeyProperty(propertyName);
		}
		Class<?> targetPropertyType = marshalled ? String.class : propertyType;
		attributeValueList = addAttributeValue(attributeValueList, attributeValue, propertyName, targetPropertyType, false);

	}

	return new Condition().withComparisonOperator(comparisonOperator).withAttributeValueList(attributeValueList);

}
 
Example #20
Source File: MapperLoadingStrategyConfigITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private static PaginatedList<RangeKeyTestClass> getTestPaginatedQueryList(PaginationLoadingStrategy paginationLoadingStrategy) {
    DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(ConsistentReads.CONSISTENT);
    DynamoDBMapper mapper = new DynamoDBMapper(dynamo, mapperConfig);
    
    // Construct the query expression for the tested hash-key value and any range-key value greater that 1.0
    RangeKeyTestClass keyObject = new RangeKeyTestClass();
    keyObject.setKey(hashKey);
    DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>().withHashKeyValues(keyObject);
    queryExpression.withRangeKeyCondition("rangeKey",
            new Condition().withComparisonOperator(ComparisonOperator.GT.toString()).withAttributeValueList(
                    new AttributeValue().withN("1.0"))).withLimit(PAGE_SIZE);
    
    return mapper.query(RangeKeyTestClass.class, queryExpression, new DynamoDBMapperConfig(paginationLoadingStrategy));
}
 
Example #21
Source File: LowLevelLocalSecondaryIndexExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void query(String indexName) {

        System.out.println("\n***********************************************************\n");
        System.out.println("Querying table " + tableName + "...");

        QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withConsistentRead(true)
            .withScanIndexForward(true).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);

        HashMap<String, Condition> keyConditions = new HashMap<String, Condition>();

        keyConditions.put("CustomerId", new Condition().withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withS("[email protected]")));

        if (indexName == "IsOpenIndex") {
            System.out.println("\nUsing index: '" + indexName + "': Bob's orders that are open.");
            System.out.println("Only a user-specified list of attributes are returned\n");
            queryRequest.setIndexName(indexName);

            keyConditions.put("IsOpen", new Condition().withComparisonOperator(ComparisonOperator.EQ)
                .withAttributeValueList(new AttributeValue().withN("1")));

            // ProjectionExpression
            queryRequest.setProjectionExpression("OrderCreationDate, ProductCategory, ProductName, OrderStatus");

        }
        else if (indexName == "OrderCreationDateIndex") {
            System.out.println("\nUsing index: '" + indexName + "': Bob's orders that were placed after 01/31/2013.");
            System.out.println("Only the projected attributes are returned\n");
            queryRequest.setIndexName(indexName);

            keyConditions.put("OrderCreationDate", new Condition().withComparisonOperator(ComparisonOperator.GT)
                .withAttributeValueList(new AttributeValue().withN("20130131")));

            // Select
            queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES);

        }
        else {
            System.out.println("\nNo index: All of Bob's orders, by OrderId:\n");
        }

        queryRequest.setKeyConditions(keyConditions);

        QueryResult result = client.query(queryRequest);
        List<Map<String, AttributeValue>> items = result.getItems();
        Iterator<Map<String, AttributeValue>> itemsIter = items.iterator();
        while (itemsIter.hasNext()) {
            Map<String, AttributeValue> currentItem = itemsIter.next();

            Iterator<String> currentItemIter = currentItem.keySet().iterator();
            while (currentItemIter.hasNext()) {
                String attr = (String) currentItemIter.next();
                if (attr == "OrderId" || attr == "IsOpen" || attr == "OrderCreationDate") {
                    System.out.println(attr + "---> " + currentItem.get(attr).getN());
                }
                else {
                    System.out.println(attr + "---> " + currentItem.get(attr).getS());
                }
            }
            System.out.println();
        }
        System.out.println("\nConsumed capacity: " + result.getConsumedCapacity() + "\n");

    }
 
Example #22
Source File: ScanITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testScan() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(SCAN_LIMIT);
    scanExpression.addFilterCondition("value", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString()));
    scanExpression.addFilterCondition("extraData", new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL.toString()));
    List<SimpleClass> list = util.scan(SimpleClass.class, scanExpression);

    int count = 0;
    Iterator<SimpleClass> iterator = list.iterator();
    while (iterator.hasNext()) {
        count++;
        SimpleClass next = iterator.next();
        assertNotNull(next.getExtraData());
        assertNotNull(next.getValue());
    }

    int totalCount = util.count(SimpleClass.class, scanExpression);

    assertNotNull(list.get(totalCount / 2));
    assertTrue(totalCount == count);
    assertTrue(totalCount == list.size());

    assertTrue(list.contains(list.get(list.size() / 2)));
    assertTrue(count == list.toArray().length);
}
 
Example #23
Source File: QueryITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that exception should be raised when user provides an index name
 * when making query with the primary range key.
 */
@Test
public void testUnnecessaryIndexNameException() {
    try {
        DynamoDBMapper mapper = TestDynamoDBMapperFactory
                .createDynamoDBMapper(dynamo);
        long hashKey = System.currentTimeMillis();
        RangeKeyTestClass keyObject = new RangeKeyTestClass();
        keyObject.setKey(hashKey);
        DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>()
                .withHashKeyValues(keyObject);
        queryExpression
                .withRangeKeyCondition(
                        "rangeKey",
                        new Condition().withComparisonOperator(
                                ComparisonOperator.GT.toString())
                                .withAttributeValueList(
                                        new AttributeValue().withN("1.0")))
                .withLimit(11).withIndexName("some_index");
        mapper.query(RangeKeyTestClass.class, queryExpression);
        fail("User should not provide index name when making query with the primary range key");
    } catch (IllegalArgumentException expected) {
        System.out.println(expected.getMessage());
    } catch (Exception e) {
        fail("Should trigger AmazonClientException.");
    }

}
 
Example #24
Source File: DynamoDBService2.java    From Doradus with Apache License 2.0 5 votes vote down vote up
@Override
  public List<DColumn> getColumns(String storeName, String rowKey, String startColumn, String endColumn, int count) {
  	Timer t = new Timer();
  	String key = storeName + "_" + rowKey;
  	HashMap<String,Condition> keyConditions = new HashMap<String,Condition>();
  	keyConditions.put("key", new Condition()
	.withComparisonOperator(ComparisonOperator.EQ)
	.withAttributeValueList(new AttributeValue().withS(key)));
  	if(startColumn != null && endColumn != null) {
      	keyConditions.put("column", new Condition()
  			.withComparisonOperator(ComparisonOperator.BETWEEN)
  			.withAttributeValueList(new AttributeValue().withS(startColumn), new AttributeValue(endColumn)));
  	} else if(startColumn != null) {
      	keyConditions.put("column", new Condition()
  			.withComparisonOperator(ComparisonOperator.GE)
  			.withAttributeValueList(new AttributeValue().withS(startColumn)));
  	} else if(endColumn != null) {
      	keyConditions.put("column", new Condition()
  			.withComparisonOperator(ComparisonOperator.LT)
  			.withAttributeValueList(new AttributeValue().withS(endColumn)));
  	}

QueryRequest request = new QueryRequest()
	.withTableName(getTenant().getName())
	.withLimit(Math.min(100,  count))
	.withKeyConditions(keyConditions);
QueryResult result = m_client.query(request);
List<DColumn> list = fromItems(result.getItems());
      m_logger.debug("get columns range for {} in {}", getTenant().getName(), t);
  	return list;
  }
 
Example #25
Source File: LowLevelQuery.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void findRepliesPostedWithinTimePeriod(String forumName, String threadSubject) {
    
    long startDateMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L); 
    long endDateMilli = (new Date()).getTime() - (5L*24L*60L*60L*1000L);    
    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    String startDate = df.format(startDateMilli);
    String endDate = df.format(endDateMilli);

    Condition rangeKeyCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.BETWEEN.toString())
        .withAttributeValueList(
            new AttributeValue().withS(startDate), 
            new AttributeValue().withS(endDate));
    
    Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);
    keyConditions.put("ReplyDateTime", rangeKeyCondition);
    
    QueryRequest queryRequest = new QueryRequest()
        .withTableName(tableName)
        .withKeyConditions(keyConditions)
        .withProjectionExpression("Message, ReplyDateTime, PostedBy");

    QueryResult result = client.query(queryRequest);
    for (Map<String, AttributeValue> item : result.getItems()) {
        printItem(item);
    }        
}
 
Example #26
Source File: DynamoDBEntityWithHashAndRangeKeyCriteria.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
private void checkComparisonOperatorPermittedForCompositeHashAndRangeKey(ComparisonOperator comparisonOperator) {

		if (!ComparisonOperator.EQ.equals(comparisonOperator) && !ComparisonOperator.CONTAINS.equals(comparisonOperator)
				&& !ComparisonOperator.BEGINS_WITH.equals(comparisonOperator)) {
			throw new UnsupportedOperationException("Only EQ,CONTAINS,BEGINS_WITH supported for composite id comparison");
		}

	}
 
Example #27
Source File: DynamoDBEntityWithHashKeyOnlyCriteria.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@Override
public DynamoDBQueryCriteria<T, ID> withPropertyEquals(String propertyName, Object value, Class<?> propertyType) {
	if (isHashKeyProperty(propertyName)) {
		return withHashKeyEquals(value);
	} else {
		Condition condition = createSingleValueCondition(propertyName, ComparisonOperator.EQ, value, propertyType, false);
		return withCondition(propertyName, condition);
	}
}
 
Example #28
Source File: DynamoDBManager.java    From dynamodb-geo with Apache License 2.0 5 votes vote down vote up
/**
 * Query Amazon DynamoDB
 * 
 * @param hashKey
 *            Hash key for the query request.
 * 
 * @param range
 *            The range of geohashs to query.
 * 
 * @return The query result.
 */
public List<QueryResult> queryGeohash(QueryRequest queryRequest, long hashKey, GeohashRange range) {
	List<QueryResult> queryResults = new ArrayList<QueryResult>();
	Map<String, AttributeValue> lastEvaluatedKey = null;

	do {
		Map<String, Condition> keyConditions = new HashMap<String, Condition>();

		Condition hashKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.EQ)
				.withAttributeValueList(new AttributeValue().withN(String.valueOf(hashKey)));
		keyConditions.put(config.getHashKeyAttributeName(), hashKeyCondition);

		AttributeValue minRange = new AttributeValue().withN(Long.toString(range.getRangeMin()));
		AttributeValue maxRange = new AttributeValue().withN(Long.toString(range.getRangeMax()));

		Condition geohashCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN)
				.withAttributeValueList(minRange, maxRange);
		keyConditions.put(config.getGeohashAttributeName(), geohashCondition);

		queryRequest.withTableName(config.getTableName()).withKeyConditions(keyConditions)
				.withIndexName(config.getGeohashIndexName()).withConsistentRead(true)
				.withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL).withExclusiveStartKey(lastEvaluatedKey);

		QueryResult queryResult = config.getDynamoDBClient().query(queryRequest);
		queryResults.add(queryResult);

		lastEvaluatedKey = queryResult.getLastEvaluatedKey();

	} while (lastEvaluatedKey != null);

	return queryResults;
}
 
Example #29
Source File: ObjectPersistenceQueryScanExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
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() );
 }
}
 
Example #30
Source File: DynamoDBEntityWithHashAndRangeKeyCriteria.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
protected List<Condition> getRangeKeyConditions() {
	List<Condition> rangeKeyConditions = null;
	if (isApplicableForGlobalSecondaryIndex()
			&& entityInformation.getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getRangeKeyPropertyName())) {
		rangeKeyConditions = getRangeKeyAttributeValue() == null ? null : Arrays.asList(createSingleValueCondition(
				getRangeKeyPropertyName(), ComparisonOperator.EQ, getRangeKeyAttributeValue(), getRangeKeyAttributeValue()
						.getClass(), true));

	}
	return rangeKeyConditions;
}