有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中带过滤器表达式的DynamoDb查询

我在AWS中有一个名为school data的DynamoDb表。以下是获取所有学校名称的现有代码:

private DynamoDBQueryExpression<School> createQueryBySchoolName(String schoolName) {
    String matchSchoolName = "schoolName = :schoolName";
    Map<String, AttributeValue> schoolNames = new HashMap<>();
    schoolNames.put(":schoolName", new AttributeValue().withS(schoolName));

    return new DynamoDBQueryExpression<School>()
            .withIndexName("schoolName-index")
            .withKeyConditionExpression(matchSchoolName)
            .withExpressionAttributeValues(schoolNames)
            .withConsistentRead(false);
}

上面的查询工作正常。但现在我需要把所有学校的名字和地址都找出来。下面是表中的3列:

id   schoolName  details

“详细信息”列中的数据如下所示:

{
"zone": "North",
"type": "Convent",
"address": {
    "id": "138",
    "street1": "123 Street",
    "street2": "456 Road"
}
}

所以,我需要把所有名为“ABC”的学校和地址为“123街”的1号街联系起来。因此,我将上述查询更新如下:

private DynamoDBQueryExpression<School> createQueryBySchoolName(String schoolName) {
    String matchSchoolName = "schoolName = :schoolName";
    Map<String, AttributeValue> schoolNames = new HashMap<>();
    schoolNames.put(":schoolName", new AttributeValue().withS(schoolName));
    schoolNames.put(":streetName", new AttributeValue().withS("123 Street"));


    return new DynamoDBQueryExpression<School>()
            .withIndexName("schoolName-index")
            .withKeyConditionExpression(matchSchoolName)
            .withFilterExpression("details.address.street1 = :streetName")
            .withExpressionAttributeValues(schoolNames)
            .withConsistentRead(false);
}

但是,这不会返回任何数据。你能告诉我我做错了什么吗


共 (1) 个答案

  1. # 1 楼答案

    您需要为DynamoDBQueryExpression设置HashKeyValue并添加页面限制

    private DynamoDBQueryExpression<School> createQueryBySchoolName(String schoolName) {
    String matchSchoolName = "schoolName = :schoolName";
    Map<String, AttributeValue> schoolNames = new HashMap<>();
    schoolNames.put(":schoolName", new AttributeValue().withS(schoolName));
    schoolNames.put(":streetName", new AttributeValue().withS("123 Street"));
    
    
    return new DynamoDBQueryExpression<Voucher>()
            .withHashKeyValues(schoolName)
            .withIndexName("schoolName-index")
            .withKeyConditionExpression(matchSchoolName)
            .withFilterExpression("details.address.street1 = :streetName")
            .withExpressionAttributeValues(schoolNames)
            .withConsistentRead(false)
            .withLimit(pPageSize);
    

    }