当前位置: 首页 > 面试题库 >

使用Swift进行Amazon AWS DynamoDB查询的最佳方法?

谯英彦
2023-03-14
问题内容

我最近为我在iOS中开发的iOS应用程序实现了AWS开发工具包。我已经连接到数据库实例并能够获得查询响应,但是,我正在努力将其转换为可用数据。我对Swift,AWS和编程一般还是比较陌生,因此可能缺少明显的东西!

我的代码如下:

    let atVal = AWSDynamoDBAttributeValue()
    atVal.S = "123456abc"
    let condition = AWSDynamoDBCondition()
    condition.comparisonOperator = AWSDynamoDBComparisonOperator.EQ
    condition.attributeValueList = [atVal]

    let myDic: [String: AWSDynamoDBCondition] = ["userid": condition]
    let query = AWSDynamoDBQueryInput()
    query.indexName = "userid-index"
    query.tableName = "users"
    query.keyConditions = myDic
    query.limit = 1


    dynamoDB.query(query).continueWithBlock {
        (task: BFTask!) -> AnyObject! in
        let results = task.result as AWSDynamoDBQueryOutput

        let myResults = results.items
        println("object: \(myResults.description)")

        return nil
    }

控制台输出为:

对象:[{area =“ {\ n S = \” West Hampstead \“; \ n}”; name =“ {\ n S = \” Olly
Mayes \“; \ n}”; userid =“ {\ n S = \” 123456abc \“; \ n}”; }]

可以理解,使用AWS和Swift似乎没有太多的优先次序,因此,任何帮助将不胜感激!


问题答案:

您的问题的简单答案是:将返回的JSON字符串转换为Dictionary对象。像这样的东西:

let data = jsonDataItem.dataUsingEncoding(NSUTF8StringEncoding)

    if data != nil {
        var error : NSError?
        let dict = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: &error) as? NSDictionary

        if let e = error {
            ...
        } else {
            ...
        }

但是,我强烈建议您看一下更高级别的DynamoDB映射器类。使用DynamoDB映射器类时,您可以定义数据结构,并将其交给DynamoDB
Mapper即可
。这是一个完整的示例,从表创建到表删除。该示例使用DynamoDB
Mapper插入,删除,扫描和查询表。

首先,您需要初始化客户端SDK

    let cp = AWSStaticCredentialsProvider(accessKey: "AK...", secretKey: "xxx")
    let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: cp)
    AWSServiceManager.defaultServiceManager().setDefaultServiceConfiguration(configuration)

这只是一个示例。在代码中嵌入访问密钥和秘密密钥不是一个好习惯。最佳实践是改用AWSCognitoCredentialsProvider(有关Cognito的更多信息)。

定义一个映射表中项目的类

class Item : AWSDynamoDBModel, AWSDynamoDBModeling {

    var email  : String = ""
    var date   : String = ""
    var note   : String = ""
    var number : Double = 0.0

    override init!() { super.init() }

    required init!(coder: NSCoder!) {
        fatalError("init(coder:) has not been implemented")
    }

    class func dynamoDBTableName() -> String! {
        return "Demo"
    }
    class func hashKeyAttribute() -> String! {
        return "email"
    }
    class func rangeKeyAttribute() -> String! {
        return "date"
    }

    //required to let DynamoDB Mapper create instances of this class
    override init(dictionary dictionaryValue: [NSObject : AnyObject]!, error: NSErrorPointer) {
        super.init(dictionary: dictionaryValue, error: error)
    }

    //workaround to possible XCode 6.1 Bug : "Type NotificationAck" does not conform to protocol "NSObjectProtocol"
    override func isEqual(anObject: AnyObject?) -> Bool {
        return super.isEqual(anObject)
    } }

创建表格

self.createTable().continueWithSuccessBlock {(task: BFTask!) -> BFTask! in
    NSLog("Create table - success")
    return nil
}


func createTable() -> BFTask! {
    let pt = AWSDynamoDBProvisionedThroughput()
    pt.readCapacityUnits  = 10
    pt.writeCapacityUnits = 10

    let emailAttr = AWSDynamoDBAttributeDefinition()
    emailAttr.attributeName = "email"
    emailAttr.attributeType = AWSDynamoDBScalarAttributeType.S

    let dateAttr = AWSDynamoDBAttributeDefinition()
    dateAttr.attributeName = "date"
    dateAttr.attributeType = AWSDynamoDBScalarAttributeType.S

    let emailKey = AWSDynamoDBKeySchemaElement()
    emailKey.attributeName = "email"
    emailKey.keyType = AWSDynamoDBKeyType.Hash

    let dateKey = AWSDynamoDBKeySchemaElement()
    dateKey.attributeName = "date"
    dateKey.keyType = AWSDynamoDBKeyType.Range

    let ct = AWSDynamoDBCreateTableInput()
    ct.tableName = "Demo"
    ct.provisionedThroughput = pt
    ct.attributeDefinitions = [emailAttr, dateAttr]
    ct.keySchema = [ emailKey, dateKey ]

    NSLog("Creating table")

    let client = AWSDynamoDB.defaultDynamoDB()
    return client.createTable(ct)
}

删除表格

self.deleteTable().continueWithSuccessBlock({ (task: BFTask!) -> BFTask! in
    NSLog("Delete table - success")
    return nil
})

func deleteTable() -> BFTask! {

    let dt = AWSDynamoDBDeleteTableInput()
    dt.tableName = "Demo"

    NSLog("Deleting table")
    let client = AWSDynamoDB.defaultDynamoDB()
    return client.deleteTable(dt)
}

插入项目

self.insertSomeItems().continueWithBlock({
    (task: BFTask!) -> BFTask! in

    if (task.error != nil) {
        NSLog(task.error.description)
    } else {
        NSLog("DynamoDB save succeeded")
    }

    return nil;
})

func insertSomeItems() -> BFTask! {
    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

    var item = Item()
    item.email  = "stormacq@amazon.com"
    item.date   = "20141101"
    item.note   = "This is item #1"
    item.number = 1.0
    let task1 = mapper.save(item)

    item = Item()
    item.email  = "stormacq@amazon.com"
    item.date   = "20141102"
    item.note   = "This is item #2"
    item.number = 2.0
    let task2 = mapper.save(item)

    item = Item()
    item.email  = "stormacq@amazon.lu"
    item.date   = "20141103"
    item.note   = "This is item #3"
    item.number = 3.0
    let task3 = mapper.save(item)

    return BFTask(forCompletionOfAllTasks: [task1, task2, task3])
}

装载一件物品

self.load("stormacq@amazon.com", range:"20141101").continueWithSuccessBlock({ (task: BFTask!) -> BFTask! in
    NSLog("Load one value - success")
    let item = task.result as Item
    print(item)
    return nil
})


func load(hash: String, range: String) -> BFTask! {
    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
    return mapper.load(Item.self, hashKey: hash, rangeKey: range)

}

查询哈希和范围键

/* 
   keyConditions
   http://docs.aws.amazon.com/AWSiOSSDK/latest/Classes/AWSDynamoDBQueryInput.html#//api/name/keyConditions
*/
let cond = AWSDynamoDBCondition()
let v1    = AWSDynamoDBAttributeValue(); v1.S = "20141101"
cond.comparisonOperator = AWSDynamoDBComparisonOperator.EQ
cond.attributeValueList = [ v1 ]
let c = [ "date" : cond ]
self.query("stormacq@amazon.com", keyConditions:c).continueWithSuccessBlock({ (task: BFTask!) -> BFTask! in
    NSLog("Query multiple values - success")
    let results = task.result as AWSDynamoDBPaginatedOutput
    for r in results.items {
        print(r)
    }
    return nil
})

func query(hash: String, keyConditions:[NSObject:AnyObject]) -> BFTask! {
    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

    let exp = AWSDynamoDBQueryExpression()
    exp.hashKeyValues      = hash
    exp.rangeKeyConditions = keyConditions

    return mapper.query(Item.self, expression: exp)
}

扫描项目(全表扫描)

let cond = AWSDynamoDBCondition()
let v1    = AWSDynamoDBAttributeValue(); v1.S = "20141101"
cond.comparisonOperator = AWSDynamoDBComparisonOperator.GT
cond.attributeValueList = [ v1 ]

let exp = AWSDynamoDBScanExpression()
exp.scanFilter = [ "date" : cond ]

self.scan(exp).continueWithSuccessBlock({ (task: BFTask!) -> BFTask! in
    NSLog("Scan multiple values - success")
    let results = task.result as AWSDynamoDBPaginatedOutput
    for r in results.items {
        print(r)
    }
    return nil
})

func scan(expression : AWSDynamoDBScanExpression) -> BFTask! {

    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
    return mapper.scan(Item.self, expression: expression)
}

如果在美国EAST
1中没有其他DynamoDB用法,那么运行此示例不会带来任何成本,因为它属于DynamoDB的免费层。



 类似资料:
  • 尝试使用CompletionSuggester for autocomplete特性,通过Java的RestHighLevelClient实现CompletionSuggester有不同的方法,想知道以下这些方法之间(在性能/查询执行速度方面)有什么区别吗 1:使用CompletionSuggestionBuilder: 2:使用SimpleQueryString

  • 我现在的问题是在同一个endpoint请求中添加多个新列,如果我的if子句变得疯狂,我相信足够多的代码不会对其他团队成员友好地阅读。 谁能建议如何在spring boot应用程序上实现这个动态查询部分。 我的控制器代码片段如下所示:

  • 示例: 对于文档: video1title=大海是蓝色的 video2title=狂野的大海 video3title=狂野的大海 video4title=海边随便什么 null null 现在,AFAIKS,没有真正的方法告诉Lucene“找到word1和word2等位于位置1和2和3等的文档。” 有一些“变通办法”可以模拟这种行为: > 对字段进行两次索引。在中,您将单词标记化(可能使用),在中

  • 问题内容: 我正在尝试使用express.js创建一个简单的CMS,以动态创建路由。它从数据库中获取一个JSON,如下所示: 并遍历对象以创建路由,如下所示: 现在一切正常。但是问题在于,每次用户修改内容和路径时,都需要重新启动整个节点应用程序。我没有找到任何API调用来删除路由。 有什么方法可以安全地删除通过app.get设置的旧路由吗?我应该这样做吗? 有没有更好的方法来进行这种路由?我喜欢这

  • 我遇到了一个问题。我的网页有一个控件。值更改后(通过选择不同的值),页面将刷新并呈现内容。 下面是我的代码: 第二部分:

  • 在python中,从URL查询字符串(例如,通过表单附加到URL的数据)解析数据的最佳方法是什么?我的目标是接受表单数据并将其显示在同一页面上。我已经研究了几种方法,但并不完全是我想要的。 我正在创建一个简单的Web服务器,目标是学习套接字。此Web服务器仅用于测试目的。