简体   繁体   English

使用二级索引从 dynamoDB 获取数据

[英]Get data from dynamoDB using secondary index

I am using node js to get data from dynamoDB.我正在使用节点 js 从 dynamoDB 获取数据。 However at the moment I am retrieving the data with the UserId.但是目前我正在使用 UserId 检索数据。 I want to retrieve the data using the secondary index that I have created, which is dateId.我想使用我创建的二级索引(dateId)检索数据。 My dynamoDB table consists of userId, Exercises, Sets, Reps and dateId.我的 dynamoDB 表由 userId、Extractions、Sets、Reps 和 dateId 组成。 How can I achieve that?我怎样才能做到这一点?

I already tried to add the Index-name under the table name with the dateId value but it's not working.我已经尝试使用 dateId 值在表名下添加索引名,但它不起作用。

My dbHelper.js looks like this.我的 dbHelper.js 看起来像这样。

dbHelper.prototype.getExercises = (userID) => {   
return new Promise((resolve, reject) => {     
const params = {     
TableName: tableName,
KeyConditionExpression: "#userID = :user_id", 
ExpressionAttributeNames: {"#userID": "userId"},                
ExpressionAttributeValues: {":user_id": userID }        
}            
docClient.query(params, (err, data) => {                
if (err) {                   
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));                  
return reject(JSON.stringify(err, null, 2))             
}            
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));                
resolve(data.Items)               
        })
    });
}

My index.js looks like this我的 index.js 看起来像这样

const GetExercisesIntentHandler = {      
canHandle(handlerInput) {        
return handlerInput.requestEnvelope.request.type === 'IntentRequest'          
&& handlerInput.requestEnvelope.request.intent.name === 'GetExercisesIntent';      
},      
async handle(handlerInput) {        
const {responseBuilder } = handlerInput;        
const userID = handlerInput.requestEnvelope.context.System.user.userId;         
return dbHelper.getExercises(userID)          
.then((data) => {            
var speechText = 'Your exercises of the day are '             
if (data.length == 0) {              
speechText = "You do not have any favourite exercises yet, add exercise by 
saving add moviename "            
} else {
          speechText += data.map(e => e.Exercise).join(", ")
        }            
return responseBuilder
          .speak(speechText)
          .reprompt(GENERAL_REPROMPT)
          .getResponse();
      })         
.catch((err) => {            
const speechText = "we cannot get your exercise right now. Try again!"            
return responseBuilder
          .speak(speechText)
          .getResponse();          
})      
}   
}

I think your function should look more like this example, based on combining AWS's documentation with your original code.我认为您的函数应该更像这个示例,基于将AWS 的文档与您的原始代码相结合。

I think you'll want to supply the partition key for the Index (which I'm assuming is dateId ) rather than the table's partition key.我认为您需要为索引提供分区键(我假设它是dateId )而不是表的分区键。

The ProjectionExpression seems to let us specify a list of attributes to return, and I gather that you want just the Exercises attribute for each item matching the specified dateId . ProjectionExpression 似乎让我们指定要返回的属性列表,我dateId您只需要与指定dateId匹配的每个项目的Exercises属性。

dbHelper.prototype.getExercises = (dateID) => {   
  return new Promise((resolve, reject) => {
    const
      tableName = NameOfDynamoDbTable, // Must be the actual table name
      indexName = NameOfDynamoDbIndex, // Must be the actual index name on that table
      params = {
        "TableName": tableName,
        "IndexName": indexName,
        "KeyConditionExpression": "#dateID = :date_id",
        "ExpressionAttributeNames": {"#dateID": "dateId"},
        "ExpressionAttributeValues": {":date_id": dateID },
        "ProjectionExpression": "Exercises",
        "ScanIndexForward": true
    };
    docClient.query(params, (err, data) => {
      if (err) {
        console.error("Can't read item. Error JSON:", JSON.stringify(err, null, 2));                  
        return reject(JSON.stringify(err, null, 2));
      }
      console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
      resolve(data.Items)               
    });
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用全局二级索引过滤dynamoDB查询 - Filtering a dynamoDB query with a global secondary index 在 GET 请求中使用多个参数从 DynamoDB 获取数据 - Getting data from DynamoDB using multiple parameters in GET Request 具有HashKeyValue和RangeKeyCondition的全局二级索引的dynamoDB查询无法正常运行JavaScript - dynamoDB Query of Global Secondary Index with HashKeyValue and RangeKeyCondition not working JavaScript 使用 AWS Amplify 从 DynamoDB 查询数据 - Querying data from DynamoDB using AWS Amplify 使用 Promises 从 DynamoDB 异步检索数据 - Retrieve Data from DynamoDB asynchronously using Promises 如何使用 Lambda 函数从 DynamoDB 获取所有数据 - How to GET all data from DynamoDB with Lambda Functions 如何使用JSON类型索引从JSON变量获取数据 - how to get data from JSON variable using a JSON type index DynamoDb 更新失败并出现错误“更新表达式尝试将二级索引键更新为不受支持的类型” - DynamoDb update fails with error “The update expression attempted to update the secondary index key to unsupported type” 使用aws-sdk javascript从DynamoDB获取项目 - Using aws-sdk javascript to get items from DynamoDB 仅使用JavaScript从DynamoDB中的一行中检索特定数据 - Only retrieve specific data from a row in DynamoDB using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM