DynamoDBMapper 负载与查询 [英] DynamoDBMapper load vs query

查看:17
本文介绍了DynamoDBMapper 负载与查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The DynamoDBMapper provides different ways to read one item from a table:

  • 查询
  • 加载

是否有推荐,使用哪一个?在快速测试中,以下两个代码片段为具有主键 = 哈希和范围键 = 日期的表返回相同的MyEntry"项,而查询方法大约快 10%.

Is there a recommendation, which of them to use? In a quick test, the following two code snippets return the same "MyEntry" item for a table with primary key=hash and range key=date, whereas the query method is roughly 10% faster.

加载

public MyEntry getEntryForDay(final Integer hash, final LocalDate date) {
    return mapper.load(MyEntry.class, hash, date);
}

查询

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

推荐答案

好的,现在我越来越习惯使用 DynamoDB,结果发现 mapper.query 代码中的错误导致性能下降:

Ok, now as I'm getting more used to work with DynamoDB it turns out that a bug in the mapper.query code is causing the poorer performance:

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

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

The correct code for the mapper query is:

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

这篇关于DynamoDBMapper 负载与查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆