Search code examples
typescriptamazon-dynamodb

How to get only the key and value from a Filter expression DynamoDb Query in Typescript


I have a filter expression and Key Condition The filter expression is {"Age":{"eq":3},"Sex":{"eq":"MALE"}}

const params: QueryCommandInput = {
            TableName: my_table_name,
            KeyConditionExpression: 'userId = :userId and begins_with(lastName, :lastName)',
            ExpressionAttributeValues: expressionAttributeValues,
            FilterExpression: filterExpression, // Assuming fullFilter is a valid FilterExpression
            ExpressionAttributeNames: expressionNames
        }

I want to pass the above filter expression as a string which I am doing using

    getFilterExpression(filter) {
    const expressions = [];
    Object.entries(filter).forEach(([key, value]) => {
        const expressionKey = `#${key}`;
        const expressionValue = `:${key}`;
        expressions.push(`${expressionKey} = ${expressionValue}`);
    });
    return expressions.length > 0 ? expressions.join(' AND ') : undefined;
}

ExpressionAttributeNames = {"#Age":"Age","#Sex":"Sex"}

But now I want to pass in the Age and Sex values in ExpressionAttributeValues

How can I extract the Key 'Age', 'Sex' and only the values

I have this piece of code which is not working as expected

filter = #Age = :Age AND #Sex = :Sex

        for (const [k, v] of Object.entries(filter)) {
        expressionNames[`#${k}`] = k;
        sets.push(`#${k} = :${k}`);
        expValues[`:${k}`] = typeof v === 'number' ? { N: v } : { S: v };
    }

which gives me

{":Age":{"S":{"eq":3}},":Sex":{"S":{"eq":"MALE"}}}

and when I pass this to the DyanmoDb query I get an error


Solution

  • The problem lies in the formation of the ExpressionAttributeValues.

    Try this:

    const filter = {
        Age: {eq: 3},
        Sex: {eq: "MALE"}
    }
    
    const expressionAttributeValues = {}
    
    for (const [k, v] of Object.entries(filter)) {
        expressionAttributeValues[`:${k}`] = v.eq;
    }
    
    console.log(expressionAttributeValues)