Gino Mempin
Gino Mempin

Reputation: 29673

Why is AWSDynamoDBScanExpression returning empty when using sort key as filterExpression?

I have the following DynamoDB table:

BoardId   |  DateTime          |  Data  |  Type
-------------------------------------------------
1         |  20180424T123508Z  |  68.1  |  U
1         |  20181026T143233Z  |  38.2  |  T
1         |  20190108T120150Z  |  38.1  |  T
2         |  20180425T092311Z  |  63.4  |  U

"BoardId" is the partition key and "DateTime" is the sort key.

I want to fetch the entry with "BoardId"="1" and "DateTime" containing "2019".
I used AWSDynamoDBObjectMapper#scan to do this with the following code:

    let dbObjMapper = AWSDynamoDBObjectMapper.default()

    let scanExpression = AWSDynamoDBScanExpression()
    scanExpression.limit = 10
    scanExpression.filterExpression = "#id = :id AND contains(#dt, :dt)"
    scanExpression.expressionAttributeNames = [
        "#id" : "BoardId",
        "#dt" : "DateTime"
    ]
    scanExpression.expressionAttributeValues = [
        ":id" : "1",
        ":dt" : "2019"
    ]

    dbObjMapper
        .scan(Event.self, expression: scanExpression)
        .continueWith(block: {
            (task: AWSTask<AWSDynamoDBPaginatedOutput>!) -> Any? in
            if let error = task.error as NSError? {
                print("The request failed. Error: \(error)")
            } else if let paginatedOutput = task.result {
                print("The request was successful.")
                print(paginatedOutput.items.count)
                for event in paginatedOutput.items as! [Event] {
                    print(event)
                }
            }
            return ()
    })

But I am getting an empty result. There is no error ("The request was successful.") but printing paginatedOutput.items.count is 0. I expected to get the same result when doing the same Scan from the DynamoDB web console:

dynamodb console

What is wrong with my usage of AWSDynamoDBScanExpression?

I tried using other Scan configurations:

Is it not allowed to use the sort key as a filter expression?

There is no mention of this in the AWS SDK for iOS docs or in the AWS Working with Scan docs (it is even stated here that "With Scan, you can specify any attributes in a filter expression—including partition key and sort key attributes")

Upvotes: 0

Views: 222

Answers (1)

Brian Winant
Brian Winant

Reputation: 3035

I would try removing scanExpression.limit = 10 from your scan parameters.

From https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html#DDB-Scan-request-Limit: "The maximum number of items to evaluate (not necessarily the number of matching items)."

So what is probably happening is that the scan is looking at 10 items, then applying the filter, the filter matches none of them, and you get no results

Upvotes: 1

Related Questions