使用Java中的动态属性查询Dynamo表

时间:2015-06-10 22:21:37

标签: java amazon-dynamodb

我想查询我的Dynamo表以检索具有未知属性键值的项目。我能够成功使用DynamoDBMapper类,它使用带注释的类从数据库中获取值,但是使用这种方法,我需要指定将提前拉出的所有属性。

我尝试按照指南使用Dynamo SDK for Java演练 http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryingJavaDocumentAPI.html。以下代码是我提出的,使用与网站上相同的导入库:

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());
    }
}

在执行过程中,我收到错误:

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

使用映射器切换到对我有用的方法QuerySpec().withHashKey("Date",datekey)会产生类似的错误:

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

我甚至不确定它是如何编译的,但我想这是一个不同的问题。是否删除了这些方法,或者我只是错误地使用它们?

1 个答案:

答案 0 :(得分:1)

尝试这样的想法,对我来说这项工作:

    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;