在 java 中从本地 DynamoDB 检索所选数据

Retrieve selected data from DynamoDB local in java

我在本地 dynamoDB 中创建了一个 table。这些字段是,

id (N)
name (S)
school (S)
classname (S)

现在我想检索学校等于 "xschool" 的所有记录并打印。

尝试了下面的代码,但在查询中出现错误,

QuerySpec spec = new QuerySpec().withProjectionExpression("sid, classname, school")
            .withKeyConditionExpression("school = :v_school").
            withValueMap(new ValueMap().withString(":v_school", "abcschool"));

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

        Iterator<Item> iterator = items.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }

我是 dynamoDB 的新手,对此有任何建议。

来自 DynamoDB documentation:

The Query operation enables you to query a table or a secondary index. You must provide a partition key value and an equality condition.

您收到的错误消息意味着 school 不是您的 table 的分区键。要解决此问题,您可以

  • 更改 table 定义,使 school 成为分区键或
  • 使用 scan 而不是查询。
AmazonDynamoDB dynamoDBClient = createClient();
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);        

String tableName = "student";
Table table = dynamoDB.getTable(tableName);

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":sc", schoolname);

ItemCollection<ScanOutcome> items = table.scan("school = :sc", // FilterExpression
    "sid, school, firstname, classname", // ProjectionExpression
    null, // ExpressionAttributeNames - not used in this example
    expressionAttributeValues);

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

试试这个,我想这对你有用