检索存储在Dynamo

时间:2016-10-06 00:10:14

标签: java json amazon-dynamodb

目前是否可以检索存储在Dynamo中的json对象的子集?例如,我有一个名为JSON类型记录的属性,它是一个JSON对象数组:

records:
[
    {"K1": "V1" },
    {"K2": "V2" },
    {"K3": "V3" },
    {"K4": "V4" }
]

我将它们存储在Dynamo中的JSON格式中。我想知道我是否只能检索键值对1到2而不是第3和第4个?我不确定是否可以提供特定的过滤器表达式来执行此操作。

如果有可能,我很想听听如何做到的方法?

谢谢!

1 个答案:

答案 0 :(得分:0)

首先,DynamoDB中没有JSON数据类型。如果您的意思是数据存储为DynamoDB数据类型 MAP ,则以下解决方案应该适合您。

简而言之,过滤器表达式应如下所示: -

FilterExpression : 'records.K1 = :recordsK1Value and records.K2 = :recordsK2Value'

如果你需要在输出中只有“records.K1”和“records.K2”,你可以使用项目表达式。

ProjectionExpression : 'records.K1, records.K2'

完整代码: -

public List<String> queryMoviesAndFilterByMapAttribute() {

    List<String> moviesJsonList = new ArrayList<>();

    DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);

    Table table = dynamoDB.getTable("Movies");

    QuerySpec querySpec = new QuerySpec();

    querySpec.withKeyConditionExpression("yearkey = :yearval and title = :titleval")
            //.withProjectionExpression("records.K1, records.K2")
            .withFilterExpression("records.K1 = :recordsK1Value and records.K2 = :recordsK2Value").withValueMap(
                    new ValueMap().withNumber(":yearval", 1991).withString(":titleval", "Movie with map attribute")
                            .withString(":recordsK1Value", "V1").withString(":recordsK2Value", "V2"));

    IteratorSupport<Item, QueryOutcome> iterator = table.query(querySpec).iterator();

    while (iterator.hasNext()) {
        Item movieItem = iterator.next();
        System.out.println("Movie data ====================>" + movieItem.toJSONPretty());
        moviesJsonList.add(movieItem.toJSON());
    }

    return moviesJsonList;

}

包含所有字段的示例输出(即没有项目表达式): -

Movie data ====================>{
  "yearkey" : 1991,
  "records" : {
    "K1" : "V1",
    "K2" : "V2",
    "K3" : "V3",
    "K4" : "V4"
  },
  "title" : "Movie with map attribute"
}

取消注释项目表达式后的示例输出: -

请注意,输出中不存在其他字段,例如年份,标题,K3和K4。

Movie data ====================>{
  "records" : {
    "K1" : "V1",
    "K2" : "V2"
  }
}