Dattatray
Dattatray

Reputation: 1871

DynamoDB multiple filter conditions, gives error - buildTree error: unset parameter: ConditionBuilder

I am building REST APIs, using Lambda and DynamoDB in GO.

I need to query the data based on multiple filters.

The number of filters can be varying based on the number of query parameters user has provided, while calling the REST API.

As per the below post, I had developed the code to add multiple conditions.

AWS SDK for Go - DynamoDb - Add multiple conditions to FilterExpression

But when I invoke the function, I get below error, in the logs.-

buildTree error: unset parameter: ConditionBuilder

The Filter expression is not applied and the scan returns all the results.

Here is the code snippet.

for queryParam, queryParamValue := range searchParams {
        fmt.Println("queryParam:", queryParam, "=>", "queryParamValue:", queryParamValue)
        if queryParam == “param1” {
            param1Condition = expression.Name(“param1”).Equal(expression.Value(queryParamValue))
        }

        if queryParam == “param2” {
            param2Condition = expression.Name(“param2”).Equal(expression.Value(queryParamValue))
        }   
    }


sampleExpr, errSample := expression.NewBuilder().
        WithCondition(param1Condition.Or(param2Condition)).
        Build()
    if errSample != nil {
        fmt.Println("Error in building Sample Expr ", errSample)
    } else {
        fmt.Println("sampleExpr ", sampleExpr)
    }

    input := &dynamodb.ScanInput{
        ExpressionAttributeNames:  sampleExpr.Names(),
        ExpressionAttributeValues: sampleExpr.Values(),
        FilterExpression:          sampleExpr.Filter(),
        TableName:                 aws.String(deviceInfotable),
    }

But if I create the expression in different way, it works.

filt := expression.Name("param1").Equal(expression.Value("valu1")).Or(expression.Name("param2").Equal(expression.Value("value2")))

Upvotes: 2

Views: 2727

Answers (1)

Pan Ke
Pan Ke

Reputation: 579

ConditionBuilder has mode field

type ConditionBuilder struct {
    operandList   []OperandBuilder
    conditionList []ConditionBuilder
    mode          conditionMode
}

The zero value of mode is unsetCond. When build condition, unsetCond raises the error.

https://github.com/aws/aws-sdk-go/blob/7798c2e0edc02ba058f7672d32f4ebf6603b5fc6/service/dynamodb/expression/condition.go#L1415

case unsetCond:
        return exprNode{}, newUnsetParameterError("buildTree", "ConditionBuilder")

In your code, if queryParam != “param1” and queryParam != “param2”, the param1Condition and param2Condition is zero value of ConditionBuilder, which fails on build.

Upvotes: 0

Related Questions