0
votes

I am trying to query a dynamo table with latitude and longitude for various locations. I want to get the values between certain coordinates as a user pans on the map.

The primary key for the table is city and the sort key is id. I created a global secondary index with lat as the partition key and lon as the sort key (to query for locations between two points in latitude and longitude).

I am trying to use this query:

let doc = require('dynamodb-doc');
let dynamo = new doc.DynamoDB();

...

        var params = {
            TableName : "locations-dev",
            IndexName: "lat-lon-index",
            KeyConditionExpression: "lon between :lon2 and :lon1 AND lat between :lat1 and :lat2",
            ExpressionAttributeValues: {
                ":lat1": JSON.stringify(event.bodyJSON.east),
                ":lat2": JSON.stringify(event.bodyJSON.west),
                ":lon1": JSON.stringify(event.bodyJSON.north),
                ":lon2": JSON.stringify(event.bodyJSON.south)
            }
        };

        dynamo.query(params, function (err, data) {
            if (err) {
                console.error('Error with ', err);
                context.fail(err);
            } else {
                context.succeed(data);
            }
        });

But I am getting this error:

{
   "errorMessage": "Query key condition not supported",
   "errorType": "ValidationException",
   "stackTrace": [
    ...
  ]
 }

Here is an example item in Dynamo:

{
  "id": "18",
  "lat": "39.923070",
  "lon": "-86.036178",
  "name": "Home Depot",
  "phone": "(317)915-8534",
  "website": "https://corporate.homedepot.com/newsroom/battery-recycling-one-million-pounds"
}
1

1 Answers

3
votes

Primary keys (even in secondary indices) in DynamoDB can only be queried with equals criteria. This constraint is derived from its internal representation since it is stored as hashed value to identify its item partition. Those hashed values cannot be queried by range.

Choosing the Right DynamoDB Partition Key

Except for scan, DynamoDB API operations require an equal operator (EQ) on the partition key for tables and GSIs. As a result, the partition key must be something that is easily queried by your application with a simple lookup (for example, using key=value, which returns either a unique item or fewer items).