Alternatives for withFilterExpression for supporting composite key

Viewed 28

I'm trying to query dynamoDB through withFilterExpression. I get an error as the argument is a composite key

Filter Expression can only contain non-primary key attributes: Primary key attribute: question_id 

and also as it uses OR operator in the query and it cannot be passed to withKeyConditionExpression.

The query that was passed to withFilterExpression is similar to this question_id = 1 OR question_id = 2. The entire code is like follows

def getQuestionItems(conceptCode : String) = {
    val qIds = List("1","2","3")
    val hash_map : java.util.Map[String, Object] = new java.util.HashMap[String, Object]()
    var queries = ArrayBuffer[String]()
    hash_map.put(":c_id", conceptCode)

    for ((qId, index) <- qIds.zipWithIndex) {
       val placeholder = ":qId" + index
       hash_map.put(placeholder, qId)
       queries += "question_id = " + placeholder
    }

    val query = queries.mkString(" or ")

    val querySpec = new QuerySpec()
      .withKeyConditionExpression("concept_id = :c_id")
      .withFilterExpression(query)
      .withValueMap(hash_map)
    questionsTable.query(querySpec)
}

Apart from withFilterExpression and withConditionExpression is there any other methods that I can use which is a part of QuerySpec ?

1 Answers

Let's raise things up a level. With a Query (as opposed to a GetItem or Scan) you provide a single PK value and optionally an SK condition. That's what a Query requires. You can't provide multiple PK values. If you want multiple PK values, you can do multiple Query calls. Or possibly you may consider a Scan across all PK values.

You can also consider having a GSI that presents the data in a format more suitable to efficient lookup.

Side note: With PartiQL you can actually specify multiple PK values, up to a limit. So if you really truly want this, that's a possibility. The downside is it raises things up to a new level of abstraction and can make inefficiencies hard to spot.

Related