Home > Software design >  How to get all items under certain conditions in DynamoDbAsyncTable
How to get all items under certain conditions in DynamoDbAsyncTable

Time:02-05

I want to get all the items that are bigger than the sortValue(createdTime)

data enter image description here

gameUid = partitionKey

cratedTime = sortKey

val dynamoTable: DynamoDbAsyncTable

val key = Key.builder()
        .partitionValue("02a6c002-d6cc-4327-9398-545a956e01e7").sortValue(1).build()

    val queryConditional =
        QueryConditional.sortGreaterThan(key)

    dynamoTable.query(queryConditional)
        .items()
        .subscribe {
            println("queryTest $it")
        }.join()

result

Game(
gameUid = 02a6c002-d6cc-4327-9398-545a956e01e7, 
numbers = [1, 2, 3, 4, 5, 6], 
createdTime=1644005720324, 
userUid=4w9xNSYn4dQGbLXk0AjP2nzOVJm2
)
//not working
val key = Key.builder()
        .partitionValue("gameUid").sortValue(1).build()

CodePudding user response:

You can just query for one partition at a time, which will work as below

val key = Key.builder()
        .partitionValue("02a6c002-d6cc-4327-9398-545a956e01e7").sortValue(1).build()

But if you want to get all the values greater than createdTime regardless of the partition then you have to scan the table as described FilterExpression

Also look at Key.Builder for more details for your current implementation.

CodePudding user response:

Why can't I use SQL? It's useless. Simple query requires too many codes.

Solution

    val attVal = AttributeValue.builder()
        .n("1644005720324")
        .build()

    val myMap: MutableMap<String, AttributeValue> = HashMap()
    myMap[":val1"] = attVal

    val myExMap: MutableMap<String, String> = HashMap()
    myExMap["#createdTime"] = "createdTime"

    val expression = Expression.builder()
        .expressionValues(myMap)
        .expressionNames(myExMap)
        .expression("#createdTime > :val1")
        .build()

    val enhancedRequest = ScanEnhancedRequest.builder()
        .filterExpression(expression)
        .limit(15)
        .build()

    dynamoTable.scan(enhancedRequest).items().subscribe {
        println("queryTest!! $it")
    }.join()

result

queryTest!! Game(gameUid=79310a7b-d2ac-47b2-907a-c2fa08a2dd6f, numbers=[1, 2, 3, 4, 5, 6], createdTime=1644005720942, userUid=4w9xNSYn4dQGbLXk0AjP2nzOVJm2)

queryTest!! Game(gameUid=42e9579d-d897-4925-8a64-a388c9647133, numbers=[1, 2, 3, 4, 5, 6], createdTime=1644005721555, userUid=4w9xNSYn4dQGbLXk0AjP2nzOVJm2)
  •  Tags:  
  • Related