簡體   English   中英

AWS Lambda Function 使用掃描或查詢從 DynamoDB 表中檢索項目

[英]AWS Lambda Function to Retrieve Item From DynamoDB Table Using Either Scan or Query

我的意圖是編寫一個 Lambda function 來使用 Scan 或 Query(哪個可行)從 DynamoDB 表中檢索指定的項目。 這是使用 REST 發布請求調用的。

在我當前版本的 Lambda function 中,我能夠使用 ScanCommand 從 DynamoDB 表中檢索所有項目,並且我嘗試實現不同的 FilterExpression 參數和/或 ExpressionAttributeValues(使用查詢時)。 不幸的是,我無法使用我定義的參數 petID 查詢/檢索特定項目。

在表中:

sk 是由請求的 petID 參數檢索項目的排序鍵。

/**
 * detail lost Pet Lambda Function 
 * Retrieves the singular lost pet using the pet ID / sk 
 * 
 * @param   {module} DynamoDBClient
 * @param   {module} QueryCommand
 * @param   {module} ScanCommand
 * @return  {function}  lambda  invokes post/get request lost pet alert function
 * 
 * @author  
 * @version 1.1
 */
const { DynamoDBClient, QueryCommand, ScanCommand } = require("@aws-sdk/client-dynamodb"); // CommonJS import
const aws = require('aws-sdk'); 

/**
 * Exports handler Function
 * Handles nodejs Lambda function using a try-catch statement
 * 
 * @param   {json}  event   Post/Get event parameter
 * @return  {json}  output  REST Post/Get lost pet alert data 
 * @throws  {404}   exception
 * @throws  {xxx}   exception
 *
 * @author  
 * @version 1.1
 */
exports.handler = async (event) => {

    try {

        console.log(event);     // log event parameter post
        
        let body = event.body;  // log event body ensure that it is string
        
        // [object Object]
        let bodyJSON2 = JSON.parse(body);
        console.log("bodyJSON2: " +bodyJSON2);
        
        let bodyJSON = JSON.stringify(body); // body JSON from parsed event.body
         
        console.log("bodyJSON: "+bodyJSON);
               
        let petID = bodyJSON.petID;         // pet id param
        
        if(!petID) {
           // throw new Error("Missing petID in request body JSON")
        }
        
        
        /**
         * detail petalert-lost parameters
         * Parameters & Configuration for the table
         * 
         * @param {Table}  petalert-lost        Dynamodb table identifier
         * @param {String} username             User profile identifier
         * @param {String} sk                   pet id identifier
         * @param {String} petname              pet name identifier
         * @param {String} found_desc           found Pet Alert description
         * @param {String} lastSeenTime         Time last seen parameter
         * @param {String} lastSeenLocation     Location last seen parameter
         * @param {String} reward               reward value parameter
         * @param {String} foundTime            foundTime value parameter
         * @param {String} phoneNumber          found phone Number parameter
         * @param {String} status_val           status value parameter
         * @param {Number} longitutde           longitude location parameter
         * @param {Number} latitude             lattitude location parameter
         * @param {String} photo1               photo1 parameter
         * @param {String} photo2               photo2 parameter
         * @param {String} photo3               photo3 parameter
         * @param {String} photo4               photo4 parameter
         * @param {String} phoneNumberAddedTime phone number added time
         * @return {dynamodb params} petalert-found
         * 
         * @author  
         * @version 1.1
         */
        // working scan
        const params = {
            TableName: "petalert-lost",
            Key: {
                "sk": petID
            }
            
            
        };
        
        // query param attempt
        const paramsQUERY = {
            TableName: "petalert-lost",
            KeyConditionExpression: 'sk = :petID',
            FilterExpression : "sk = :petID",
            Key: {
                "sk": petID
            },
            //KeyConditionExpression: "sk = :petID",
            
            // Key: {
            //     "petID": {
            //         S: petID
            //     }
            // },
            
        };


        const client = new DynamoDBClient({ region: "ap-southeast-1" });    // production client - singapore

        let command = new ScanCommand(params);
     
        const res = await client.send(command);

        console.log(res);

        console.log(res.Items);

        let petList = res.Items; 

        let response;


        /**
         * 200 Status Code
         * Passing Result
         * 
         * @param {Number} res.$metadata.httpStatusCode Containing the HTTP Status Code
         * @param {Struct} allPetList                   Containing the parameter response
         * @return {json}  response                     Json response
         * 
         * @author
         * @version 1.1
         */
        if (res.$metadata.httpStatusCode == 200) {
            response = {
                statusCode: 200,
                "isBase64Encoded": false,
                "headers": { "Access-Control-Allow-Origin": "*" },
                body: JSON.stringify(petList),
            };
            return response;
        }
        /**
         * !200 Status Code
         * Failure Result
         *
         * @param {Number} res.$metadata.httpStatusCode Containing the HTTP Status Code
         * @return {json}  response                     Json response
         * 
         * @author
         * @version 1.1
         */
        else if (res.$metadata.httpStatusCode != 200) {
            response = {
                statusCode: res.$metadata.httpStatusCode,
                "isBase64Encoded": false,
                "headers": { "Access-Control-Allow-Origin": "*" },
                body: JSON.stringify("retrieve detail lost pet alert FAIL"),
            };
            return response;
        }
    }
    /**
    * 456 Status Code
    * Error Exception Result
    * @param {Error} err           Containing error value
    * @return {json}  errResp      Error Json response
    * 
    * @author
    * @version 1.1
    */
    catch (err) {
        console.log("Error", err);

        const errResp = {
            //statusCode: err.$metadata.httpStatusCode,
            statusCode: 456,
            "isBase64Encoded": false,
            "headers": { "Access-Control-Allow-Origin": "*" },
            body: JSON.stringify(err.__type),
        };
        return errResp;

    }
    finally {

    }
};

您希望收到以petId為鍵的項目列表,要使用查詢, petId必須是表的分區鍵,如果不是,則需要創建 GSI 並將petId分區鍵。

我相信petId是您描述的排序鍵,因此 Query 將不起作用。

查詢看起來像這樣:

        const params = {
            TableName: "petalert-lost",
            KeyConditionExpression: 'sk = :petID',
            ExpressionAttributeValues: {
                ":petID":{"S":petID}
            }
            
        };



let command = new QueryCommand(params);
     
const res = await client.send(command);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM