AWS DynamoDB浅析

AWS DynamoDB是一个NOSQL数据库。

可以通过IAM直接控制权限,和AWS其他服务连用非常方便。

DynamoDB的几个概念

Partition Key:分区键。如果没有Sort key,那么Partition Key必须唯一,如有Sort key,Partition Key可以重复。

Sort key: 排序键。

Composite Key:Partition Key和Sort key的合称,是一个逻辑概念。

GSI: 独立于Partition Key和Sort key之外的第二套索引机制。可以创建多个GSI。

用Boto3查询DyanmoDB

使用GSI来查询数据,需要指定indexname:

这里假设分区键叫key1,排序键叫sortkey,GSI叫gsi-index

import boto3
from boto3.dynamodb.conditions import Attr, Key

def query_app(self, key1: str, sortkey: str):
        response = self.table.query(
            IndexName='gsi-index',
            KeyConditionExpression = Key("key1").eq(key1) & Key("sortkey").begins_with(sortkey),
            ScanIndexForward = False
        )
        code = response.get('ResponseMetadata').get('HTTPStatusCode')
        if code == 200:
            logging.info(f"query item successfully!")
            return response.get("Items")
        else:
            logging.warning(f"query item fail!, response is {code}")

query和scan的区别:

  1. query是利用key来查询。(推荐。)
  2. scan是全表扫描以后再过滤。、

参考资料:

PowerPoint Presentation (sides-share.s3.cn-north-1.amazonaws.com.cn)

猜你喜欢

转载自blog.csdn.net/rav009/article/details/132663792
AWS
今日推荐