简体   繁体   中英

Complex Queries in DynamoDB

I am working on an application that uses DynamoDB .

Is there a way where I can create a GSI with multiple attributes. My aim is to query the table with a query of following kind:

(attrA.val1 === someVal1 AND attrB.val2 === someVal2 AND attrC.val3 === someVal3) 
OR (attrA.val4 === someVal4 AND attrB.val5 === someVal5 AND attrC.val6 === someVal6)

I am aware we can use Query when we have the Key Attribute and when Key Attribute is unknown we can use Scan operations. I am also aware of GSI if we need to query with non-key attributes. But I need some help in this scenario. Is there a way to model GSI to suit the above query.

I have the below item (ie data) on my Movies tables. The below query params works fine for me.

You can add the third attribute as present in the OP. It should work fine.

DynamoDB does support the complex condition on FilterExpression .

Query table based on some condition:-

var table = "Movies";

var year_val = 1991;
var title = "Movie with map attribute";

var params = {
    TableName : table,
    KeyConditionExpression : 'yearkey = :hkey and title = :rkey',
    FilterExpression : '(records.K1 = :k1Val AND records.K2 = :k2Val) OR (records.K3 = :k3Val AND records.K4 = :k4Val)',    
    ExpressionAttributeValues : {
        ':hkey' : year_val,
        ':rkey' : title,
        ':k3Val' : 'V3',
        ':k4Val' : 'V4',        
        ':k1Val' : 'V1',
        ':k2Val' : 'V2'

    }
};

docClient.query(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err,
                null, 2));      
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));

    }
});

My Data:-

在此处输入图片说明

Result:-

GetItem succeeded: {
  "Items": [
    {
      "title": "Movie with map attribute",
      "yearkey": 1991,
      "records": {
        "K3": "V3",
        "K4": "V4",
        "K1": "V1",
        "K2": "V2"
      }
    }
  ],
  "Count": 1,
  "ScannedCount": 1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM