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

The following examples show how to use com.amazonaws.services.dynamodbv2.model.Condition. 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: 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 #3
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 #4
Source File: DynamoDBClient.java    From emr-dynamodb-connector with Apache License 2.0 6 votes vote down vote up
public RetryResult<ScanResult> scanTable(
    String tableName, DynamoDBQueryFilter dynamoDBQueryFilter, Integer segment, Integer
    totalSegments, Map<String, AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
  final ScanRequest scanRequest = new ScanRequest(tableName)
      .withExclusiveStartKey(exclusiveStartKey)
      .withLimit(Ints.checkedCast(limit))
      .withSegment(segment)
      .withTotalSegments(totalSegments)
      .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);

  if (dynamoDBQueryFilter != null) {
    Map<String, Condition> scanFilter = dynamoDBQueryFilter.getScanFilter();
    if (!scanFilter.isEmpty()) {
      scanRequest.setScanFilter(scanFilter);
    }
  }

  RetryResult<ScanResult> retryResult = getRetryDriver().runWithRetry(new Callable<ScanResult>() {
    @Override
    public ScanResult call() {
      log.debug("Executing DynamoDB scan: " + scanRequest);
      return dynamoDB.scan(scanRequest);
    }
  }, reporter, PrintCounter.DynamoDBReadThrottle);
  return retryResult;
}
 
Example #5
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 #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: 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 #8
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 #9
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 #10
Source File: DynamoDBQueryUtils.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private static Condition constructTimeCondition(FilterCriteria filter) {
    boolean hasBegin = filter.getBeginDate() != null;
    boolean hasEnd = filter.getEndDate() != null;

    final Condition timeCondition;
    if (!hasBegin && !hasEnd) {
        timeCondition = null;
    } else if (!hasBegin && hasEnd) {
        timeCondition = new Condition().withComparisonOperator(ComparisonOperator.LE).withAttributeValueList(
                new AttributeValue().withS(AbstractDynamoDBItem.DATEFORMATTER.format(filter.getEndDate())));
    } else if (hasBegin && !hasEnd) {
        timeCondition = new Condition().withComparisonOperator(ComparisonOperator.GE).withAttributeValueList(
                new AttributeValue().withS(AbstractDynamoDBItem.DATEFORMATTER.format(filter.getBeginDate())));
    } else {
        timeCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN).withAttributeValueList(
                new AttributeValue().withS(AbstractDynamoDBItem.DATEFORMATTER.format(filter.getBeginDate())),
                new AttributeValue().withS(AbstractDynamoDBItem.DATEFORMATTER.format(filter.getEndDate())));
    }
    return timeCondition;
}
 
Example #11
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 #12
Source File: MapperLoadingStrategyConfigITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
private static PaginatedList<RangeKeyTestClass> getTestPaginatedScanList(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.scan(RangeKeyTestClass.class, scanExpression, new DynamoDBMapperConfig(paginationLoadingStrategy));
}
 
Example #13
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 #14
Source File: IndexRangeKeyAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/** 
 * Tests the exception when user specifies an invalid index name in the query.
 */
@Test
public void testInvalidIndexNameException() {
	IndexRangeKeyTestClass hashKeyItem = new IndexRangeKeyTestClass();
	hashKeyItem.setKey(0);
	try {
		mapper.query(IndexRangeKeyTestClass.class,
				new DynamoDBQueryExpression<IndexRangeKeyTestClass>()
					.withHashKeyValues(hashKeyItem)
					.withRangeKeyCondition(INDEX_BAR_RANGE_KEY, 
							new Condition()
								.withAttributeValueList(new AttributeValue().withN("0"))
								.withComparisonOperator(ComparisonOperator.GE.toString()))
					.withIndexName("some_index"));
		fail("some_index is not a valid index name.");
	} catch (IllegalArgumentException iae) {
		System.out.println(iae.getMessage());
	} catch (Exception e) {
		fail("Should trigger an IllegalArgumentException.");
	}
}
 
Example #15
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 #16
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 #17
Source File: LowLevelQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesUsingAFilterExpression(String forumName, String threadSubject) {

        Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);

        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val", new AttributeValue().withS("User B"));

        QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(keyConditions)
            .withFilterExpression("PostedBy = :val").withExpressionAttributeValues(expressionAttributeValues)
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }
    }
 
Example #18
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 #19
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 #20
Source File: LowLevelQuery.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
/**
 * A simple helper function that returns a KeyCondition map filled in with
 * the partition key equality condition for a the Reply example table, given
 * a forumName and threadSubject.
 */
private static Map<String, Condition> makeReplyKeyConditions(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);

    return keyConditions;
}
 
Example #21
Source File: DynamoDBNAryFilter.java    From emr-dynamodb-connector with Apache License 2.0 5 votes vote down vote up
@Override
public Condition createCondition() {
  Condition condition = new Condition();
  condition.setComparisonOperator(operator.getDynamoDBName());

  List<AttributeValue> attributeValueList = new ArrayList<>();
  for (String value : columnValues) {
    attributeValueList.add(HiveDynamoDBTypeFactory.getTypeObjectFromHiveType(columnType)
        .getAttributeValue(value));
  }
  condition.setAttributeValueList(attributeValueList);

  return condition;
}
 
Example #22
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;
}
 
Example #23
Source File: TransactionManagerDBFacadeIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
private QueryRequest createQueryRequest(final boolean filterAttributes) {
    Condition hashKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(key0.get(ID_ATTRIBUTE));
    QueryRequest request = new QueryRequest()
            .withTableName(INTEG_HASH_TABLE_NAME)
            .withKeyConditions(Collections.singletonMap(ID_ATTRIBUTE, hashKeyCondition));
    if (filterAttributes) {
        request.setAttributesToGet(attributesToGet);
    }
    return request;
}
 
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: AbstractDynamoDBQueryCriteria.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
public AbstractDynamoDBQueryCriteria(DynamoDBEntityInformation<T, ID> dynamoDBEntityInformation) {
	this.clazz = dynamoDBEntityInformation.getJavaType();
	this.attributeConditions = new LinkedMultiValueMap<String, Condition>();
	this.propertyConditions = new LinkedMultiValueMap<String, Condition>();
	this.hashKeyPropertyName = dynamoDBEntityInformation.getHashKeyPropertyName();
	this.entityInformation = dynamoDBEntityInformation;
	this.attributeNamesByPropertyName = new HashMap<String, String>();

}
 
Example #26
Source File: DynamoDBEntityWithHashKeyOnlyCriteria.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
protected Query<T> buildFinderQuery(DynamoDBOperations dynamoDBOperations) {
	if (isApplicableForGlobalSecondaryIndex()) {

		List<Condition> hashKeyConditions = getHashKeyConditions();
		QueryRequest queryRequest = buildQueryRequest(dynamoDBOperations.getOverriddenTableName(entityInformation.getDynamoDBTableName()),
				getGlobalSecondaryIndexName(), getHashKeyAttributeName(), null, null, hashKeyConditions, null);
		return new MultipleEntityQueryRequestQuery<T>(dynamoDBOperations,entityInformation.getJavaType(), queryRequest);
	} else {
		return new MultipleEntityScanExpressionQuery<T>(dynamoDBOperations, clazz, buildScanExpression());
	}
}
 
Example #27
Source File: TransactionManagerDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public ScanResult scan(
        String tableName,
        List<String> attributesToGet,
        Map<String, Condition> scanFilter) throws AmazonServiceException, AmazonClientException {
    ScanRequest request = new ScanRequest()
            .withTableName(tableName)
            .withAttributesToGet(attributesToGet)
            .withScanFilter(scanFilter);
    return scan(request);
}
 
Example #28
Source File: DynamoDBQueryUtils.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static Condition maybeAddTimeFilter(final DynamoDBQueryExpression<DynamoDBItem<?>> queryExpression,
        final FilterCriteria filter) {
    final Condition timeCondition = constructTimeCondition(filter);
    if (timeCondition != null) {
        queryExpression.setRangeKeyConditions(
                Collections.singletonMap(DynamoDBItem.ATTRIBUTE_NAME_TIMEUTC, timeCondition));
    }
    return timeCondition;
}
 
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: 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));
}