How to fetch/scan all items from `AWS dynamodb` using node.js

前端 未结 11 2813
清酒与你
清酒与你 2020-11-30 00:19

How to fetch/scan all items from AWS dynamodb using node.js. I am posting my code here.

var docClient = new aws.DynamoDB.DocumentCl         


        
11条回答
  •  春和景丽
    2020-11-30 01:05

    If you would like to get the data from DynamoDB without using Hash key value, you need to use Scan API.

    Note: The Scan API reads all the items in the table to get the results. So, it is a costly operation in DynamoDB.

    Alternate Approach : Use GSI

    Scan Code for the above sceanario:-

    var docClient = new AWS.DynamoDB.DocumentClient();
    
    var params = {
        TableName: "users",
        FilterExpression: "#user_status = :user_status_val",
        ExpressionAttributeNames: {
            "#user_status": "user_status",
        },
        ExpressionAttributeValues: { ":user_status_val": 'somestatus' }
    
    };
    
    docClient.scan(params, onScan);
    var count = 0;
    
    function onScan(err, data) {
        if (err) {
            console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
        } else {        
            console.log("Scan succeeded.");
            data.Items.forEach(function(itemdata) {
               console.log("Item :", ++count,JSON.stringify(itemdata));
            });
    
            // continue scanning if we have more items
            if (typeof data.LastEvaluatedKey != "undefined") {
                console.log("Scanning for more...");
                params.ExclusiveStartKey = data.LastEvaluatedKey;
                docClient.scan(params, onScan);
            }
        }
    }
    

提交回复
热议问题