代码之家  ›  专栏  ›  技术社区  ›  rohitwtbs

如何基于数组中的值在dynamoDB中进行扫描?

  •  0
  • rohitwtbs  · 技术社区  · 6 年前

    这是我的代码,其中有一个数组中的值列表。我需要从项目表中获取与数组中id匹配的所有项目。

                var arr=[];
                for(var index in data.Items){
                    if(data.Items[index].hasOwnProperty('projectId'))
                    arr.push(data.Items[index].projectId);
                };
    
                var params = {
                    TableName: 'projects',
                    FilterExpression: 'id IN (:id)',
                    ExpressionAttributeValues: {
                        ':id': arr
                    }
    
                };
    
                dynamodbclient.scan(params, function (err, docs) {
                    if (err) {
                        console.log("Error", err);
                    } else {
                        console.log("Success");
                        callback(err, docs.Items);
    
                    }
                });
    

    然而,我没有得到正确的结果。

    1 回复  |  直到 6 年前
        1
  •  1
  •   notionquest    6 年前

    选项1-静态:-

    如果您知道它前面的所有值,请构造 FilterExpression 如下所述:-

    var params = {
        TableName : "projects",
        FilterExpression : "id IN (:id1, :id2)",
        ExpressionAttributeValues : {
            ":id1" : "id val 1",
            ":id2" : "id val 2"
    
        }
    };
    

    选项2-动态:-

    var titleValues = ["The Big New Movie 2012", "The Big New Movie"];
    var titleObject = {};
    var index = 0;
    titleValues.forEach(function(value) {
        index++;
        var titleKey = ":titlevalue"+index;
        titleObject[titleKey.toString()] = value;
    });
    
    var params = {
        TableName : "Movies",
        FilterExpression : "title IN ("+Object.keys(titleObject).toString()+ ")",
        ExpressionAttributeValues : titleObject
    };
    
    docClient.scan(params, onScan);
    
    function onScan(err, data) {
        if (err) {
            console.error("Unable to scan the table. Error JSON:", JSON.stringify(
                    err, null, 2));
        } else {
            // print all the movies
            console.log("Scan succeeded.");
            data.Items.forEach(function(movie) {
                console.log("Item :", JSON.stringify(movie));
            });
    
            // continue scanning if we have more movies
            if (typeof data.LastEvaluatedKey != "undefined") {
                console.log("Scanning for more...");
                params.ExclusiveStartKey = data.LastEvaluatedKey;
                docClient.scan(params, onScan);
            }
        }
    }