17
votes

I have 2 LSI in my table with a primary partition Key with primary sort key

Org-ID - primary partition Key

ClientID- primary sort Key

Gender - LSI

Section - LSI

I have no issue with querying a table with one LSI, but how to mention 2 LSI in a table schema.

 var params = {
 TableName:"MyTable",
 IndexNames: ['ClientID-Gender-index','ClientID-Section-index'], 

KeyConditionExpression : '#Key1 = :Value1 and #Key2=:Value2 and #Key3=:Value3', 

ExpressionAttributeNames:{
"#Key1":"Org-ID",
"#Key2":"Gender",
"#Key3":"Section"
},

ExpressionAttributeValues : {
':Value1' :"Microsoft",
':Value2':"Male",
':Value3':"Cloud Computing"
}};

Can anyone fix the issue in IndexName(line 3) or KeyConditionExpression(line 4), I'm not sure about it.

Issue

Condition can be of length 1 or 2 only

1

1 Answers

20
votes

You can only query a single DynamoDB index at a time. You cannot use multiple indexes in the same query.

A simple alternative is to use a single index and apply a query filter, but this will potentially require a lot of records to be scanned and the filter only reduces the amount of data transferred over the network.

A more advanced alternative is to make a compound key. You would most likely want to use a GSI, rather than an LSI for this use case. By making a single new column that is the string concatenation of Key1, Key2, and Key3 you can use this GSI to search all three keys at the same time. This will make each individual record bigger by repeating data but it allows for a more complex query pattern.