2016-12-30 73 views
0

我无法找到在swift中编写dynamodb查询以获取具有特定分区键的结果的方法。如何在swift中编写dynamodb查询以获取具有特定分区键的所有值

例如说我的分区键是“bigCompany”,排序键是“email”。现在我想要将所有电子邮件的“bigCompany”名称作为“xyz”。

仅供参考,我的代码结构与下面的加载函数非常相似。但是这个使用.load来获取一个值而不是查询。基本上我需要找到一种方法,在给定我上面提到的约束条件下调用dynamoDBOBjectMapper .query()。任何帮助将非常感谢!

func getTableRow() { 
    let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper() 

    //tableRow?.UserId --> (tableRow?.UserId)! 
    dynamoDBObjectMapper .load(DDBTableRow.self, hashKey: (tableRow?.UserId)!, rangeKey: tableRow?.GameTitle) .continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in 
     if (task.error == nil) { 
      if (task.result != nil) { 
       let tableRow = task.result as! DDBTableRow 
       self.hashKeyTextField.text = tableRow.UserId 
       self.rangeKeyTextField.text = tableRow.GameTitle 
       self.attribute1TextField.text = tableRow.TopScore?.stringValue 
       self.attribute2TextField.text = tableRow.Wins?.stringValue 
       self.attribute3TextField.text = tableRow.Losses?.stringValue 
      } 
     } else { 
      print("Error: \(task.error)") 
      let alertController = UIAlertController(title: "Failed to get item from table.", message: task.error!.description, preferredStyle: UIAlertControllerStyle.Alert) 
      let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) -> Void in 
      }) 
      alertController.addAction(okAction) 
      self.presentViewController(alertController, animated: true, completion: nil) 

     } 
     return nil 
    }) 
} 

回答

1

想通了。他们的关键是正确使用keyConditionExpression。以下是我的答案。

  let queryExpression = AWSDynamoDBQueryExpression() 

      queryExpression.keyConditionExpression = "#bigCompany = :bigCompany" 
      queryExpression.expressionAttributeNames = ["#bigCompany": "bigCompany",] 
      queryExpression.expressionAttributeValues = [":bigCompany" : self.bigCompany,] 

      dynamoDBObjectMapper.query(Requests.self, expression: queryExpression) .continue(with: AWSExecutor.immediate(), with: { (task:AWSTask!) -> AnyObject! in 
       //If added successfully 
       if((task.result) != nil) { 
        let results = task.result! as AWSDynamoDBPaginatedOutput 
        print(results.items) 
       } 
       else { 
        //do error checking here 
       } 
      }) 
相关问题