Node.js aws-如何设置lambda函数对dynamodb进行动态查询
这是我当前的lambda函数,它返回表“Banner”中的所有数据。Node.js aws-如何设置lambda函数对dynamodb进行动态查询,node.js,amazon-web-services,aws-lambda,amazon-dynamodb,Node.js,Amazon Web Services,Aws Lambda,Amazon Dynamodb,这是我当前的lambda函数,它返回表“Banner”中的所有数据。 getBanner.js 'use strict' const AWS = require('aws-sdk'); exports.handler = async function (event, context, callback) { const documentClient = new AWS.DynamoDB.DocumentClient(); let responseBody = "&q
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
...
}
]
我知道如果我想查询属性顺序,我需要改为以下内容。...
var params = {
TableName : "Banner",
KeyConditionExpression: "#od = :yyyy",
ExpressionAttributeNames:{
"#od": "order"
},
ExpressionAttributeValues: {
":yyyy": 1
}
};
...
如果我要执行以下操作怎么办?可能有一些用例使我需要查询另一个属性或多个属性。
我应该如何拥有一个可以动态处理queryStringParameters的函数 根据评论更新,但出现另一个错误
'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
}
这是从cloudwatch获得的“参数”的值
答复A
{
TableName: 'Banner',
KeyConditionExpression: ' #order = :order , #year = :year ',
ExpressionAttributeNames: { '#order': 'order', '#year': 'year' },
ExpressionAttributeValues: { ':order': '1', ':year': '2007' }
}
您可以从Lambda函数处理程序中的事件对象查询此参数。事件对象内容取决于调用Lambda函数的服务。如果从弹性负载平衡或API网关调用Lambda函数,则可以从事件对象获取查询参数。事件对象将有一个名为
queryStringParameters
的属性,该属性包含请求中的所有查询字符串参数
这是文档中事件对象的示例:
{
"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
}
案例示例:(注意:查询字符串的名称必须与表达式属性相同)
您可以从Lambda函数处理程序中的事件对象查询此参数。事件对象内容取决于调用Lambda函数的服务。如果从弹性负载平衡或API网关调用Lambda函数,则可以从事件对象获取查询参数。事件对象将有一个名为
queryStringParameters
的属性,该属性包含请求中的所有查询字符串参数
这是文档中事件对象的示例:
{
"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
}
案例示例:(注意:查询字符串的名称必须与表达式属性相同)
简单例子
const getParams = (key, value) => ({
TableName: "Banner",
KeyConditionExpression: "#key = :value",
ExpressionAttributeNames: {
"#key": key
},
ExpressionAttributeValues: {
":value": value
}
});
并根据查询参数调用此函数。
可以从事件中获取的查询参数
const queryParams = event.queryStringParameters;
简单例子
const getParams = (key, value) => ({
TableName: "Banner",
KeyConditionExpression: "#key = :value",
ExpressionAttributeNames: {
"#key": key
},
ExpressionAttributeValues: {
":value": value
}
});
并根据查询参数调用此函数。
可以从事件中获取的查询参数
const queryParams = event.queryStringParameters;
使用扫描而不是KeyConditionExpression时使用FilterExpression。 样品
使用扫描而不是KeyConditionExpression时使用FilterExpression。 样品
能否给出一些示例代码来演示如何动态使用queryStringParameters?const{order,year}=event.queryStringParameters;var参数={TableName:“Banner”,KeyConditionExpression:“#od=:yyyy”,ExpressionAttributeNames:{“#od::“order”},expressionAttributeValue:{”:yyyy::year};有没有动态的方法?因为我可能会或多或少地使用属性来查询Yes,所以您可以在event.queryStringParameters中为循环键添加属性,并在每个键的名称前添加冒号,然后使用spread运算符将键和值分配给ExpressionAttributeValue。但这是有安全代价的。我将在上面的答案中为您提供示例。谢谢。但是为什么会有一个安全价格呢?你能给出一些示例代码来说明如何动态使用queryStringParameters吗?const{order,year}=event.queryStringParameters;var参数={TableName:“Banner”,KeyConditionExpression:“#od=:yyyy”,ExpressionAttributeNames:{“#od::“order”},expressionAttributeValue:{”:yyyy::year};有没有动态的方法?因为我可能会或多或少地使用属性来查询Yes,所以您可以在event.queryStringParameters中为循环键添加属性,并在每个键的名称前添加冒号,然后使用spread运算符将键和值分配给ExpressionAttributeValue。但这是有安全代价的。我将在上面的答案中为您提供示例。谢谢。但是为什么会有一个安全价格呢?如果我有多个查询参数呢?比如(年份、订单、名称),你应该在dynamoDB中有一个索引,并使用KeyConditionExpression。对于多个参数,应该使用FilterExpression。KeyConditionExpression只能与索引主键和排序键中的键一起使用。如果我有多个QueryParam呢?例如(年份、顺序、名称),您应该在dynamoDB中有一个索引并使用KeyConditionExpression。对于多个参数,应该使用FilterExpression。KeyConditionExpression仅适用于索引主键和排序键中的键。