AWS DynamoDB query top 5 scores for country

Let’s take a look at how to query top 5 scores from AWS DynamoDB, let say we have some top scores table and want to get top 5 performers for the specific country. What we also need is not to waste the network resources, that’s why we will specify what exact fields we need to fetch from server – with help of projectionExpression.
Moreover let’s take a look at how to deal with the following error:
com.amazon.coral.validate#ValidationException”,”message”:”Invalid ProjectionExpression: Attribute name is a reserved keyword; reserved keyword: name”

it could be solved by adding reserved words to the expressionAttributeNames, e.g. instead of

queryExpression.projectionExpression = "userId,challenge,country,name,total"

where name and total are reserved words let’s do the following

queryExpression.expressionAttributeNames = [
            "#n": "name",
            "#t": "total",
        ]
queryExpression.projectionExpression = "userId,challenge,country,#n,#t"

That approach will eliminate the ValidationException – reserved keyword; reserved keyword error.

Here’s the whole method
Continue reading “AWS DynamoDB query top 5 scores for country”

Social Share Toolbar

AWS Mobile hub, swift and dynamoDB

If you will google “backend for ios application” or “backend for swift application” you can notice that Amazone Mobile Hub will be in the top results, articles whatever, the easiest way to start your backend right now is for sure https://aws.amazon.com/mobile especially if you already familiar with aws. The wizard is quite well and detailed, it will guide you through the process and will even generate sample project YourApp-aws-my-sample-app-ios-swift which will use the backend which you have just configured in the web.
I believe you can play with wizard by yourself and reach even the point when you will copy-paste all AWS stuff to you project – wizard greatly describe even this part. I just want to highlight several steps/moments which were not very obviously for me, and show the example how to use mobile hub even easier w/o copying all the code from AWS – I mean tables, helpers, and all that swift stuff, you will need only One file – aws data model, and that’s it, you are all set to make backend requests.

Please start with completing this wizard https://aws.amazon.com/mobile
Several things they forgot to mention in the step “Use MySampleApp as an Example”:
1. While copying settings from Sample’s Info.plist to yours one, additionally copy “App Transport Security Settings”.
001
It is easy to forget and it’s really required to allow your app to make http requests to aws instances
2. On the step “Add a Run Script phase to your project” you need to add “bash “${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/AWSCore.framework/strip-frameworks.sh” line to the “Build Phases”.
It’s vital to have “Run script” section under the “Embed frameworks” and basically all other, just drag it to the bottom, so you can avoid “…Frameworks/AWSCore.framework/strip-frameworks.sh: No such file or directory” error during the Build of your app.
So drag it down like that
002
and try to clean and build your project once again – should be fine in case if you had such an error.

Read further if you have successfully finished all wizards steps and if you have your app up and running and connected with aws backend.

Lets say we want to create a new table for collecting Feedback, we just need to post the “Feedback” and that’s it, let go ahead and create a new table in mobilehub, so I clicked to “Configure” section, than to NoSql Databases and choose “Add new table” option on the bottom, here is my scheme:
003
Ensure that in the “Queries this table can perform.” you have “Find all items with deviceId = ABC” option, otherwise you will have only one Feedback from one device, it will be the latest one.

You can try to download the latest version of Sample App, but eventually the only thing you nee is the table ID which looks like this “AppName-mobilehub-xxxxxxxxxx-Feedback”. You don’t really need those humongous Tables and Helper classes, the only one thing you might want to copy-paste from the latest Sample is the Feedback.swift which is data model for AWS DynamoDB, it looks like this (Feedback.swift):

//...
 
import Foundation
import UIKit
import AWSDynamoDB
class Feedback: AWSDynamoDBObjectModel, AWSDynamoDBModeling {
 
    var _deviceId: String?
    var _appName: String?
    var _text: String?
    var _userContact: String?
    var _date: String?
 
    class func dynamoDBTableName() -> String {
        return "AppName-mobilehub-xxxxxxxxxxx-Feedback"
    }
 
    class func hashKeyAttribute() -> String {
        return "_deviceId"
    }
 
    class func rangeKeyAttribute() -> String {
        return "_date"
    }
 
    override class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject] {
        return [
            "_deviceId" : "deviceId",
            "_appName" : "appName",
            "_text" : "text",
            "_userContact" : "userContact",
            "_date" : "date",
        ]
    }
}

Ok, we are ready to post the feedback, here is all we need:

    func postFeedback(contact: String, text: String, completionHandler: (error: NSError?) -> Void) {
        let feedback = Feedback()
        feedback._deviceId = Identity.getUserUniqueId() // AWS Identity
        feedback._date = String(NSDate())
        feedback._appName = "AppName" // Just in case if you'll want to use this table from several apps.
        feedback._userContact = contact
        feedback._text = text
 
        insertFeedbackWithCompletionHandler(feedback, completionHandler: completionHandler)
    }
 
    // MARK: AWS Methods
    internal func insertFeedbackWithCompletionHandler(item: Feedback, completionHandler: (error: NSError?) -> Void) {
        let objectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
 
        objectMapper.save(item, completionHandler: {(error: NSError?) -> Void in
            dispatch_async(dispatch_get_main_queue(), {
                completionHandler(error: error)
            })
        })
    }

So this is basically it, go ahead and run you app and it should work (obviously you had to create a UI and call this method on your own). You might noticed this line “Identity.getUserUniqueId()” just in case here is what’s under the hood:

    func getUserUniqueId() -> String {
        let identityManager = AWSIdentityManager.defaultIdentityManager()
        return identityManager.identityId ?? TEST_ID
    }

This is it, AWS mobilehub is very easy and way to create a backend for you iso app, I still had no chance to push it’s limits and I’m sure that there is a price for such a high-level abstraction but it’s very easy for simple use cases. May be I’ll post some results on my researches on it’s performance or dealing with edge cases. It was kind of overview of this new technology.

P.S. To check out the content of your DynamoDB go here https://console.aws.amazon.com/dynamodb/home?region=us-east-1#tables: choose the right region, click to “…-Feedback” table and click “Items” tab, here you can see all the items from your database and even scan or query them.

Social Share Toolbar