DynamoDBMapper加载与查询

Rol*_*ger 10 amazon-dynamodb

DynamoDBMapper提供了从表中读取一个项目的不同方法:

  • 询问
  • 加载

是否有推荐,哪些可以使用?在快速测试中,以下两个代码段为具有主键= hash和range key = date的表返回相同的"MyEntry"项,而查询方法大约快10%.

加载

public MyEntry getEntryForDay(final Integer hash, final LocalDate date) {
    return mapper.load(MyEntry.class, hash, date);
}
Run Code Online (Sandbox Code Playgroud)

询问

public MyEntry getEntryForDay(final Integer hash, final LocalDate date) {
    final MyEntry hashKeyValues = new MyEntry ();
    hashKeyValues.setHash(hash);
    final Condition rangeKeyCondition = new Condition()//
            .withComparisonOperator(ComparisonOperator.EQ.toString())//
            .withAttributeValueList(new AttributeValue().withS(new LocalDateMarshaller().marshall(date)));
    final DynamoDBQueryExpression<MyEntry> queryExpression = new DynamoDBQueryExpression<MyEntry>()//
            .withHashKeyValues(hashKeyValues)//
            .withRangeKeyCondition("date", rangeKeyCondition)//
            .withLimit(1);
    final List<MyEntry> storedEntries = mapper
            .query(MyEntry.class, queryExpression);
    if (storedEntries.size() == 0) {
        return null;
    }
    return storedEntries.get(0);
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*rtz 8

加载和查询是不同的操作:

如果您只有一个散列键模式,它们执行相同的操作 - 使用指定的散列键检索该项.

如果您有散列范围架构,则load会检索由单个散列+范围对标识的特定项.查询检索具有指定散列键并满足范围键条件的所有项.

由于您对哈希键和范围键都使用了相等运算符,因此操作完全相同.


Rol*_*ger 5

好的,现在我越来越习惯于使用 DynamoDB,结果是 mapper.query 代码中的一个错误导致了更差的性能:

  • “withLimit(1)”实际上并不限制列表中返回的总结果,而是在“PaginatedQueryList”中返回结果,并且实际项目在访问时从数据库延迟加载。WithLimit(1) 实际上限制了每个请求加载的项目。
  • 实际的错误是“if (storedEntries.size() == 0)”部分,因为 size() 调用实际上加载了列表中的所有项目。使用 withLimit(1) 这会导致最差的性能。

映射器查询的正确代码是:

public MyEntry getEntryForDay(final Integer hash, final LocalDate date) {
    final MyEntry hashKeyValues = new MyEntry ();
    hashKeyValues.setHash(hash);
    final Condition rangeKeyCondition = new Condition()//
            .withComparisonOperator(ComparisonOperator.EQ.toString())//
            .withAttributeValueList(new AttributeValue().withS(new LocalDateMarshaller().marshall(date)));
    final DynamoDBQueryExpression<MyEntry> queryExpression = new DynamoDBQueryExpression<MyEntry>()//
            .withHashKeyValues(hashKeyValues)//
            .withRangeKeyCondition("date", rangeKeyCondition)//
            .withLimit(1);
    final List<MyEntry> storedEntries = mapper
            .query(MyEntry.class, queryExpression);
    if (storedEntries.isEmpty()) {
        return null;
    }
    return storedEntries.get(0);
}
Run Code Online (Sandbox Code Playgroud)