AWS-如何设置Lambda函数对dynamodb进行动态查询 [英] aws - how to set lambda function to make dynamic query to dynamodb

查看:113
本文介绍了AWS-如何设置Lambda函数对dynamodb进行动态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我当前的lambda函数,该函数返回表横幅"中的所有数据.

This is my current lambda function, which return all data from Table "Banner".

getBanner.js

getBanner.js

'use strict'
const AWS = require('aws-sdk');

exports.handler = async function (event, context, callback) {
    const documentClient = new AWS.DynamoDB.DocumentClient();

    let responseBody = "";
    let statusCode = 0;

    const params = {
        TableName : "Banner",
    };

    try{
        const data = await documentClient.scan(params).promise();
        responseBody = JSON.stringify(data.Items);
        statusCode = 200
    }catch(err){
        responseBody = `Unable to get products: ${err}`;
        statusCode = 403
    }

    const response = {
        statusCode: statusCode,
        headers:{
            "Content-Type": "application/json",
            'Access-Control-Allow-Origin': '*', // Required for CORS support to work
        },
        body: responseBody
    }

    return response
}

这是示例返回的数据

[
   {
       Order: 123,
       Year: 2000
       ...
   },
   {
       Order: 77,
       Year: 2007
       ...
   }
]

我了解如果我想对属性顺序进行一些查询,则需要更改为以下内容.

I understand If I want to do some query for attribute order, I need to change to following.

...
var params = {
    TableName : "Banner",
    KeyConditionExpression: "#od = :yyyy",
    ExpressionAttributeNames:{
        "#od": "order"
    },
    ExpressionAttributeValues: {
        ":yyyy": 1
    }
};
...

如果我想执行以下操作怎么办?
可能有一些用例使我需要查询另一个或多个属性.

What if I want to do the following?
There may be some use cases which make me need to do query for another attribute, or multiple attributes.

我应该如何拥有一个可以动态处理queryStringParameters的函数?

How should I do have a function which can handle the queryStringParameters dynamically?

已根据评论进行了更新,但发生了另一个错误

'use strict'
const AWS = require('aws-sdk');

exports.handler = async function (event, context, callback) {
    const documentClient = new AWS.DynamoDB.DocumentClient();

    let responseBody = "";
    let statusCode = 0;

    console.log(event)
    const queryStringParams = event.queryStringParameters;

    console.log(queryStringParams)

    let KeyConditionExpression = ''
    let ExpressionAttributeNames={};
    let ExpressionAttributeValues = {};
    for (const property in queryStringParams) {
      KeyConditionExpression += ` #${property} = :${property} ,`;
      ExpressionAttributeNames['#'+property] = property ;
      ExpressionAttributeValues[':'+property]=queryStringParams[property];
    }

    KeyConditionExpression= KeyConditionExpression.slice(0, -1);

    const params = {
        TableName : "Banner",
        KeyConditionExpression: KeyConditionExpression,
        ExpressionAttributeNames: ExpressionAttributeNames,
        ExpressionAttributeValues: ExpressionAttributeValues
    };

    console.log(params)   //Response A

    try{
        const data = await documentClient.scan(params).promise();
        responseBody = JSON.stringify(data.Items);
        statusCode = 200
    }catch(err){
        responseBody = `Unabel to get products: ${err}`;
        statusCode = 403
    }

    const response = {
        statusCode: statusCode,
        headers:{
            "Content-Type": "application/json",
            'Access-Control-Allow-Origin': '*', // Required for CORS support to work
        },
        body: responseBody
    }

    return response
}

Unabel to get products: ValidationException: ExpressionAttributeNames can only be specified when using expressions

这是从cloudwatch获得的"params"的值响应A

This is the value of the ‘params’ obtained from cloudwatch Response A

{
  TableName: 'Banner',
  KeyConditionExpression: ' #order = :order , #year = :year ',
  ExpressionAttributeNames: { '#order': 'order', '#year': 'year' },
  ExpressionAttributeValues: { ':order': '1', ':year': '2007' }
}

推荐答案

您可以从Lambda函数处理程序中的事件对象中查询此参数.事件对象的内容取决于哪个服务调用了Lambda函数.如果从Elastic Load Balancing或API网关调用了Lambda函数,则可以从事件对象获取查询参数.事件对象将具有名为 queryStringParameters 的属性,该属性在请求中具有所有查询字符串参数.

You can this query parameters from the event object in your Lambda function handler. The event object content depends on what service invoked the Lambda function. If Lambda function invoked from Elastic Load Balancing or from API gateway you can get the query parameters from the event object. The event object will have an attribute called queryStringParameters which have all the query string parameters in the request.

这是文档中事件对象的示例:

This is a sample for an event object from the documentation:

{
    "requestContext": {
        "elb": {
            "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
        }
    },
    "httpMethod": "GET",
    "path": "/lambda",
    "queryStringParameters": {
        "query": "1234ABCD"
    },
    "headers": {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "accept-encoding": "gzip",
        "accept-language": "en-US,en;q=0.9",
        "connection": "keep-alive",
        "host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com",
        "upgrade-insecure-requests": "1",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
        "x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
        "x-forwarded-for": "72.12.164.125",
        "x-forwarded-port": "80",
        "x-forwarded-proto": "http",
        "x-imforwards": "20"
    },
    "body": "",
    "isBase64Encoded": false
}

https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html https://docs.aws.amazon.com/lambda/Latest/dg/lambda-services.html

这种情况的示例:(注意:查询字符串的名称必须与表达式属性相同)

Example for your case: (NOTE: name of the query strings must be the same as expression attributes)

const queryStringParams = event.queryStringParams;
const updatedQueryStringParams = {};

Object.keys(queryStringParams).forEach(key => updatedQueryStringParams[`:${key}`] = queryStringParams[key]);

    var params = {
        TableName : "Banner",
        KeyConditionExpression: "#od = :year",
        ExpressionAttributeNames:{
            "#od": "order"
        },
        ExpressionAttributeValues: {
            ...updatedQueryStringParams
        }
    };

这篇关于AWS-如何设置Lambda函数对dynamodb进行动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆