下面列出了怎么用com.amazonaws.services.dynamodbv2.model.ComparisonOperator的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
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);
}
}
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);
}
}
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);
}
}
@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());
}
}
/**
* 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());
}
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);
}
}
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));
}
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;
}
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;
}
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;
}
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);
}
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);
}
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);
}
}
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;
}
@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);
}
}
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);
}
}
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);
}
}
/**
* 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;
}
/**
* 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());
}
/**
* 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.");
}
}
@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);
}
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));
}
@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;
}
@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);
}
}
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() );
}
}
/**
* 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;
}
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");
}
}
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;
}
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);
}
}