21
votes

I have Table with 2 attribute id(string,primary key), value(string). When I try follwoing KeyConditionExpression it throws Query key condition not supported.

KeyConditionExpression: "begins_with(ID, :tagIDValue)" 
                        or
KeyConditionExpression: "contains(ID, :tagIDValue)"

From this link I came to know we can use only EQ operations on main key. How can I achieve this

Solution:======================================================

I need to use begins_with or contains to filter So I went with following approach.

Table attributes: PK(partion_key, string), ID(sort key, string), value(string).

Now my primary key is framed based on PK,ID

PK will have constant value for all rows. so KeyConditionExpression will be like.

KeyConditionExpression: "PL = :pk  and begins_with(ID, :tagIDValue)"

NOTE: But still contains not working with KeyConditionExpression. I think it was removed from KeyConditionExpression

3
Your own "Solution" showed me the correct syntax for "PL = :pk and begins_with(ID, :tagIDValue)." Thank you. This is not very clear in the AWS documentation.Steve W.

3 Answers

31
votes

You can use begins_with and contains only with a range key after specifying an EQ condition for the primary key.

To use EQ with the primary key you can do

KeyConditionExpression: "ID = :tagIDValue"
9
votes

I disagree with Tolbahady statement regarding begins_with and contains only workable in range key. You can use any comparison operator in any keys using method scan. Scan is a flexible but expensive and inefficient way of conducting dynamodb queries.

Anyways, there is a tool named, AWS NoSQL Workbench. It is little bit like MySQL Workbench. What is the good thing about it, is you can construct your table while checking against your access patterns(possible and most used queries of your application against your table).

5
votes

I would stay away from scans at all costs, in this scenario I would create a global secondary index. The primary key on a GSI doesn't require uniqueness and you can query off of that. Storage is cheap, you can probably live with the extra keys.