python - 如何查询 DynamoDB 并获取存在 "col3"而不是 0/null 的所有行 (boto3)

标签 python aws-lambda amazon-dynamodb boto3 serverless-framework

这是我通过无服务器框架构建的 DynamoDB 表,为“aaa_id”添加了辅助列索引:

    Devices:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: Devices
        BillingMode: PAY_PER_REQUEST
        AttributeDefinitions:
          - AttributeName: serial
            AttributeType: S
          - AttributeName: aaa_id
            AttributeType: N
        KeySchema:
          - AttributeName: serial
            KeyType: HASH
        GlobalSecondaryIndexes:
          - IndexName: aaa_id
            KeySchema:
              - AttributeName: aaa_id
                KeyType: HASH
            Projection:
              ProjectionType: ALL

我想查询我的 DynamoDB 并获取表中“aaa_id”列存在或不为 0(或者为 null,如果对于 Number 类型列可能的话)的所有项目。有些行不包括它。 最好使用query方法而不是scan,因为我知道它不那么重

我已经研究这个问题好几个小时了。请帮忙。

我的一些失败尝试:

import json
import boto3


def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Devices')

    try:
        response = table.query(
            IndexName='aaa_id',
            FilterExpression='aaa_id <> :empty',
            ExpressionAttributeValues={':empty': {'N': '0'}}
        )
        
        items = response['Items']
        return {
            'statusCode': 200,
            'body': json.dumps(items)
        }
        
    except Exception as e:
        print(e)
        return {
            'statusCode': 500,
            'body': json.dumps('Error querying the database')
        }


#################################

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


def lambda_handler(event, context):

    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Devices')

    try:
        response = table.query(
            IndexName='aaa_id',
            KeyConditionExpression=Key('aaa_id').gt(0) & Attr('aaa_id').not_exists(),
            ExpressionAttributeValues={
                ':empty': {'N': ''}
            }
        )

        data = response['Items']
        while 'LastEvaluatedKey' in response:
            response = table.query(
                IndexName='aaa_id',
                KeyConditionExpression=Key('aaa_id').gt(0) & Attr('aaa_id').not_exists(),
                ExpressionAttributeValues={
                    ':empty': {'N': ''}
                },
                ExclusiveStartKey=response['LastEvaluatedKey']
            )
            data.extend(response['Items'])

        return {
            'statusCode': 200,
            'body': json.dumps(data),
            'success': True
        }

    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps(str(e)),
            'success': False
        }

#######################

import json
import boto3
from boto3.dynamodb.conditions import Key

def lambda_handler(event, context):

    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Devices')

    try:
        response = table.query(
            IndexName='aaa_id-index',
            KeyConditionExpression=Key('aaa_id').gt(0)
        )
        
        items = response['Items']
        
        while 'LastEvaluatedKey' in response:
            response = table.query(
                IndexName='aaa_id-index',
                KeyConditionExpression=Key('aaa_id').gt(0),
                ExclusiveStartKey=response['LastEvaluatedKey']
            )
            items.extend(response['Items'])
        
        return {
            'statusCode': 200,
            'body': json.dumps(items),
            'success': True
        }
    
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)}),
            'success': False
        }



##################################



import boto3
import json


def lambda_handler(event, context):

    dynamodb = boto3.client('dynamodb')
        
    
    try:
        response = dynamodb.query(
            TableName="Devices",
            IndexName='aaa_id-index',
            KeyConditionExpression='aaa_id <> :empty',
            # ExpressionAttributeValues={':empty': {'S': ''}}
        )
        
        return {
            'statusCode': 200,
            'body': json.dumps(response['Items']),
            'status': 'success'
        }
        
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)}),
            'status': 'error'
        }

最佳答案

你把事情搞得太复杂了。首先,数字类型不能为 null,因为 DynamoDB 是无模式的,您只需省略任何值即可。

其次,索引可以是稀疏的。由于您对 0 的项目不感兴趣,因此只需不为其设置值,这反过来意味着该项目将不存在于索引中。

然后您只需扫描索引,因为您知道其中的所有值都不为 null 且不为 0。在这种情况下,Scan 非常高效,因为它可以准确读取您想要的内容。

response = table.scan(
            IndexName='aaa_id'
        )

关于python - 如何查询 DynamoDB 并获取存在 "col3"而不是 0/null 的所有行 (boto3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75645700/

相关文章:

amazon-web-services - Dynamodb 查询操作

python - 如何在 selenium 中使用 chrome webdriver 在 python 中下载文件?

javascript - 在 Python 中解析 BeautifulSoup 后的脚本标签

amazon-web-services - 将标签添加到现有 S3 对象时是否会生成任何事件?

aws-lambda - 使用无服务器在部署阶段(CodePipeline)将 secret 传递给 lambda?

aws-lambda - 无服务器部署 - 堆栈策略忽略条件并阻止所有资源上的 update::delete

java - 通过 dynamoDb 表的 Id(hashKey) 检索数据时出错

java - 在 DynamoDB 中删除属性

python - 在pytorch中将矩阵行乘以向量元素?

python - Gzip 到 base64 编码将字符添加到 JSON 字符串