Dynamodb:使用两个以上属性的查询

2024-07-08 11:09:11 发布

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

在Dynamodb中,需要在索引中指定可用于进行查询的属性。

如何使用两个以上的属性进行查询?

使用boto的示例。

Table.create('users', 
        schema=[
            HashKey('id') # defaults to STRING data_type
        ], throughput={
            'read': 5,
            'write': 15,
        }, global_indexes=[
            GlobalAllIndex('FirstnameTimeIndex', parts=[
                HashKey('first_name'),
                RangeKey('creation_date', data_type=NUMBER),
            ],
            throughput={
                'read': 1,
                'write': 1,
            }),
            GlobalAllIndex('LastnameTimeIndex', parts=[
                HashKey('last_name'),
                RangeKey('creation_date', data_type=NUMBER),
            ],
            throughput={
                'read': 1,
                'write': 1,
            })
        ],
        connection=conn)

如何查找名为“John”、姓为“Doe”、使用boto在“3-21-2015”创建的用户?


Tags: namenumberreaddatadate属性typeboto
1条回答
网友
1楼 · 发布于 2024-07-08 11:09:11

您的数据建模过程必须考虑您的数据检索需求,在DynamoDB中,您只能通过hash或hash+range键进行查询。

如果按主键查询不足以满足您的需求,那么您当然可以通过创建辅助索引(本地或全局)来使用备用键。

但是,在某些情况下,可以将多个属性的连接用作主键,以避免维护辅助索引的成本。

如果需要按名字、姓氏和创建日期获取用户,我建议您在哈希和范围键中包含这些属性,这样就不需要创建其他索引。

哈希键应包含一个可由应用程序计算的值,同时提供统一的数据访问。例如,假设您选择按如下方式定义密钥:

散列键(名称):名字

范围键(创建):MM DD YYYY HH MM SS毫秒

如果所提到的属性不足以使键在表中唯一,则始终可以附加其他属性。

users = Table.create('users', schema=[
        HashKey('name'),
        RangeKey('created'),
     ], throughput={
        'read': 5,
        'write': 15,
     })

将用户添加到表中:

with users.batch_write() as batch:
     batch.put_item(data={
         'name': 'John#Doe',
         'first_name': 'John',
         'last_name': 'Doe',
         'created': '03-21-2015-03-03-02-3243',
     })

您在2015年3月21日创建的查找用户John Doe的代码应该如下:

name_john_doe = users.query_2(
   name__eq='John#Doe',
   created__beginswith='03-21-2015'
)

for user in name_john_doe:
     print user['first_name']

重要注意事项:

如果你的查询开始变得太复杂,哈希或范围键太长,有太多的连接字段,那么一定要使用二级索引。这是一个好兆头,说明只有一个主索引不足以满足您的需求。

二。我提到散列键应该提供统一的数据访问:

"Dynamo uses consistent hashing to partition its key space across its replicas and to ensure uniform load distribution. A uniform key distribution can help us achieve uniform load distribution assuming the access distribution of keys is not highly skewed." [DYN]

哈希键不仅允许唯一地标识记录,而且是确保负载分布的机制。范围键(使用时)有助于指示将主要一起检索的记录,因此,存储也可以针对这种需要进行优化。

下面的链接对该主题有完整的解释:

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.UniformWorkload

相关问题 更多 >

    热门问题