boto dynamodb2:我只能使用范围键查询表吗?

2024-07-08 10:42:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的一个python应用程序中,我正在使用boto,我想只使用range key查询dynamodb表。我不想用扫描。

评分表的模式

ratings = Table.create('ratings', schema=[
    HashKey('user_id', data_type=NUMBER),
    RangeKey('photo_id', data_type=NUMBER)
], throughput={
    'read': 5,
    'write': 15,
}, indexes = [
    AllIndex('rating_allindex', parts=[
        HashKey('user_id', data_type=NUMBER),
        RangeKey('photo_id', data_type=NUMBER)
    ])
])


from boto.dynamodb2.table import Table
ratings = Table('ratings')
# photo_id is range_key and user_id is hash_key
ratings_list = ratings.query(photo_id__eq=1)

执行此操作时,会出现此错误Query condition missed key schema element user_id。 再次,我想我可以给我的哈希键一个过滤条件

ratings_list = ratings.query(user_id__gte=1, photo_id__eq=1)

但它显示了错误,Query key condition not supported。我想只有过滤器eq才允许使用hash密钥。我如何实现我想要的?


Tags: keyidnumberdataschematypetablerange
3条回答

在DynamoDB上使用Query操作时,您必须提供一个哈希键,它并不像您在文档中看到的那样被定义为范围键条件的一部分,因此您必须使用您已经知道的用户id eq。

如果需要在一个API调用中从多个散列键获取行,则必须使用Scan(可以使用batchGet获取多个行,但这与场景无关)

附:看来你的二级索引和范围键是一样的,这是个错误吗?

使用photo_id作为散列键的global secondary index可以实现所需的行为。

在AWS SDKv2中,可以使用awsdynamodscanexpression扫描表,例如iOS:

 AWSDynamoDBObjectMapper *dynamoDBObjectMapper = [AWSDynamoDBObjectMapper defaultDynamoDBObjectMapper];
 AWSDynamoDBScanExpression *scanExpression = [AWSDynamoDBScanExpression new];
 scanExpression.exclusiveStartKey = nil;
 scanExpression.limit = @20;
 [[[dynamoDBObjectMapper scan:[DDBTableRow class]
                   expression:scanExpression]
   continueWithExecutor:[BFExecutor mainThreadExecutor] withSuccessBlock:^id(BFTask *task) {...}

如果需要条件,可以使用AWSDynamoDBCondition:

 AWSDynamoDBCondition *condition = [AWSDynamoDBCondition new];
 AWSDynamoDBAttributeValue *attribute = [AWSDynamoDBAttributeValue new];
 attribute.N = @"400";
 condition.attributeValueList = @[attribute];
 condition.comparisonOperator = AWSDynamoDBComparisonOperatorEQ;
 scanExpression.scanFilter = @{@"latitude": condition};

相关问题 更多 >

    热门问题