代码之家  ›  专栏  ›  技术社区  ›  C-Bertram

Alexa,nodejs使用Lambda使用不同的参数多次查询DynamoDB表。异步函数

  •  0
  • C-Bertram  · 技术社区  · 7 年前

    我正在尝试开发一种技能,Alexa将读出用户指定日期的DynamoDB表中的信息。我已经在Lambda中使用nodejs查询了DynamoDB表,并且能够返回具有特定日期的所有项目。请参见下面的代码:

    function queryDynamoDate_multiple() {
    const startdate = this.attributes['startdate'];
    
    
    var say = '';
    var params = {
            TableName: 'RegalCinema',
            KeyConditionExpression: "#date = :yymmdd and #time between :time1 and :time2",
            ExpressionAttributeNames:{
            "#date": "date",
        "#time": "time"
    
            },
            ExpressionAttributeValues: {
            ":yymmdd":startdate,
        ":time1":'0',
        ":time2":'2'
    }};
    
      readDynamoItem(params, myResult=>{
    
    
            say = myResult;
    
            say = 'you asked,. The answer is: ' + myResult;
    
            this.response.speak(say).listen('try again');
            this.emit(':responseReady');
    
    
           });
    
        }
    

    .

    function readDynamoItem(params, callback) {
    var title = [];
    var time = [];
    var noofitems = 0;
    let speechOutput = "";
    
        docClient.query(params, (err, data) => {
            if (err) {
                this.emit(':tell', 'Test Error');
            } else {
                console.log("Query succeeded.");
                data.Items.forEach(function(item) {
                    console.log(" -", item.title + ": ");
                    noofitems = noofitems + 1;
                    title[noofitems] = item.title;
                    time[noofitems] = item.time;
    
        });
    
            for (var l = 1; l <= noofitems ; l++){
            if ( l== noofitems){
                speechOutput = speechOutput +" and "+ title[l] + " at " + time[l] + ". ";
            } else if ( l == 1) {
                speechOutput = speechOutput + title[l] + " at " + time[l];
            } else {
                speechOutput = speechOutput + ", " + title[l] + " at "+ time[l];
            } 
    }
    
    callback(speechOutput)
            }
        });
    
    }
    

    我现在想多天(最多7天)处理并返回所有项目。因为您只能使用“equals”而不是“between”两个值查询表中的主分区键。我怀疑我唯一的选择是使用参数的不同日期多次运行此函数。然而,我很难做到这一点,在阅读了一些内容后,我认为这是由于函数的异步性质。

    我需要在这个函数中循环一定次数(介于1到7之间),并在每次运行的日期中添加一次。理想情况下,我希望将标题存储在一个数组中,时间存储在另一个数组中(就像我已经在做的那样)。我在处理日期值方面没有问题。我的问题是返回一次运行函数的结果,并将其放入一个数组中,该数组已在上次运行函数时填充。

    我希望这是有意义的。任何帮助或指导都将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  0
  •   F_SO_K    7 年前

    您似乎将日期作为分区键,将时间作为范围键。

    选项:

    • 使用每个日期多次查询(您已经建议过了)
    • 添加新的datetime属性,然后使用扫描而不是查询来返回两个值之间的datetime。这将评估表中的每一行,但因为这听起来像是您需要做的,所以这将是一个很好的方法
    • 如果有不同的自然分区键(即,您只想查询表的一部分),则可以更改分区键,并将datetime改为范围键。