goamazon-dynamodbdynamodb-queriesaws-sdk-go-v2

Passing multiple values to expression.in() of aws-sdk-go-v2 for DynamoDB


I am trying to pass a list of values to the 'IN' expression in aws-sdk-go-v2 and I cannot figure out how to do it dynamically.

This is what it looks like now.

func Find(colors []string) ([]Trip, error) {
    db := database.GetClient()

    filt := expression.In(
        expression.Name("color"),
        expression.Value(colors[0]),
        expression.Value(colors[1]),
    )

    expr, err := expression.NewBuilder().WithFilter(filt).Build()
    if err != nil {
        fmt.Println(err)
    }
    params := &dynamodb.ScanInput{
        ExpressionAttributeNames:  expr.Names(),
        ExpressionAttributeValues: expr.Values(),
        FilterExpression:          expr.Filter(),
        TableName:                 aws.String("Test"),
    }
    resp, err := db.Scan(context.TODO(), params)
}

I'd like to make the list values dynamic without accessing using their index. Like below,

filt := expression.In(expression.Name("color"),expression.Value(colors))

How can I achieve this?


Solution

  • See Passing arguments to ... parameters in the language spec.

    package main
    
    import (
        "fmt"
    
        "github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
    )
    
    func main() {
        colors := []string{"red", "blue", "green"}
    
        if len(colors) == 0 {
            panic("colors should not be empty")
        }
    
        values := make([]expression.OperandBuilder, len(colors))
        for i, c := range colors {
            values[i] = expression.Value(c)
        }
    
        filter := expression.In(
            expression.Name("color"),
            values[0],
            values[1:]...,
        )
    
        fmt.Println(filter)
    }