如何使用AWS Lambda从Dynamo DB检索多个项目

时间:2018-07-09 20:49:55

标签: amazon-web-services aws-lambda amazon-dynamodb boto3

如何从数据库获取多个项目。下面的代码抛出一个错误,因为它仅获取一项。我正在根据电子邮件值检索项目。

import json
import os
import boto3
import decimalencoder

dynamodb = boto3.resource('dynamodb')


def get(event, context):
    table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])

    # fetch a person from the database
    result = table.get_item(
        Key={
            'email': event['pathParameters']['email']
        }
    )

    # create a response
    response = {
        "statusCode": 200,
        "body": json.dumps(result['Item'], cls=decimalencoder.DecimalEncoder),
        "headers": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true"
        }
    }

    return response

1 个答案:

答案 0 :(得分:0)

要从数据库检索多行,请首先查询要过滤数据的ID。 然后维护一个列表,以在其中存储所有行值。

def lambda_handler(event,context):

    item = table.query(
              KeyConditionExpression=Key('hubID').eq(hubId)
           )

    if (item["Count"] == 0):
        response = {"msg": "Item not exist, can't perform READ"}

    else:
        i = 1
        lst = []
        while i < item["Count"]:

            response = {                          
                        "hubId" : item["Items"][i]["hubID"],
                        "deviceState": int(item["Items"][i]["deviceState"]),
                        "deviceId": item["Items"][i]["deviceID"],
                        "deviceType": item["Items"][i]["deviceType"],
                        "intensity": int(item["Items"][i]["intensity"])
                        }
            lst.append(response)
            i += 1
        print(lst) 

        response = lst

return response