如何在swift中编写dynamodb查询以获取具有特定分区键的所有值

时间:2016-12-30 12:05:29

标签: ios swift amazon-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 个答案:

答案 0 :(得分:2)

想出来。他们的关键是正确使用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
                }
            })