Querying Dynamo tables with dynamic attributes in Java

3.3k views Asked by At

I would like to query my Dynamo tables to retrieve items that have unknown attribute key values. I was able to successfully use the DynamoDBMapper class which uses an annotated class to get values from the database, but with this method, I need to specify all the attributes that will be pulled ahead of time.

I tried to follow the guide for using the Dynamo SDK for Java walkthrough at http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryingJavaDocumentAPI.html. The following code is what I came up with, using the same Import libraries as on the site:

public static void queryTable(){
    Table table = dynamoDB.getTable("Task");

    String datekey = "20150601";

    QuerySpec spec = new QuerySpec()
            .withKeyConditionExpression("Date = :v_id")
            .withValueMap(new ValueMap()
                    .withString(":v_date", datekey));

    ItemCollection<QueryOutcome> items = table.query(spec);

    Iterator<Item> iterator = items.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next().toJSONPretty());
    }
}

During the execution I get the error:

java.lang.NoSuchMethodError: com.amazonaws.services.dynamodbv2.model.QueryRequest.withKeyConditionExpression

Switching to the method that worked for me with the mapper, QuerySpec().withHashKey("Date",datekey) gives the similar error:

java.lang.NoSuchMethodError: com.amazonaws.services.dynamodbv2.model.QueryRequest.withExpressionAttributeNames

I'm not even sure how it's compiling but I suppose that's a different question. Have these methods been removed or am I just using them wrong?

1

There are 1 answers

0
Wojciech On

Try somethink like this, for me this work:

    KeyAttribute keyAttribute = new KeyAttribute("hashColumnName", "hash");
    Table table = dynamoDB.getTable(T_TABLE_NAME);
    Index index = table.getIndex("end_date");  // index name
    RangeKeyCondition rangeKeyCondition = new RangeKeyCondition("end_date").between(dateStart, dateEnd );

    QuerySpec querySpec = new QuerySpec()
        .withConsistentRead(true)
        .withScanIndexForward(true)
        .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
        .withHashKey(keyAttribute)
        .withRangeKeyCondition(rangeKeyCondition)
        .withProjectionExpression
            ("id, end_date ");

    ItemCollection<QueryOutcome> items = index.query(querySpec);
    Iterator<Item> iterator = items.iterator();
    ArrayList<TDynamoEntity> tDynamoEntities = new ArrayList<>();
    while (iterator.hasNext()) {
        Item item= iterator.next();
        TDynamoEntity tDynamoEntity = new TDynamoEntity(item); //special constructor
        tDynamoEntities.add(tDynamoEntity);
    }
     return tDynamoEntities;