如何使用array - dynamodb在FilterExpression中使用“IN”语句

时间:2016-10-27 11:36:33

标签: node.js amazon-dynamodb aws-sdk

已检查AWS文档但未找到任何有效示例。

这是我的尝试

var params = {
            TableName: "User",
            IndexName:"a-b-index",
            KeyConditionExpression: "Country = :country and #s = :status",
            FilterExpression: "Id IN (:e)",
            ExpressionAttributeValues: {
              ":country ": "USA",
              ":status": 1,
              ":e": "1"

            },
            ExpressionAttributeNames: {"#s": "Status"}
          };

          //get users
          dynamodb.query(params, function (err, data) {
            if (err)
              //error
            else {
              //success

            }
          });

获得了记录,但它正在获取id为1的记录,但我想使用这样的数组

 var params = {
        TableName: "User",
        IndexName:"a-b-index",
        KeyConditionExpression: "Country = :country and #s = :status",
        FilterExpression: "Id IN (:e)",
        ExpressionAttributeValues: {
          ":country ": "USA",
          ":status": 1,
          ":e": ["1","2","3"]

        },
        ExpressionAttributeNames: {"#s": "Status"}
      };

      //get users
      dynamodb.query(params, function (err, data) {
        if (err)
          //error
        else {
          //success

        }
       });

如何使上面的代码成为work.want来获取记录。语法是正确的,查询运行没有错误,但我没有得到记录

6 个答案:

答案 0 :(得分:17)

请参阅此answer

<强>要点: -

对于“IN”子句中的固定数量的值: -

var params = {
    TableName : "Users",
    FilterExpression : "username IN (:user1, :user2)",
    ExpressionAttributeValues : {
        ":user1" : "john",
        ":user2" : "mike"
    }
};

对于数组中的更多元素并动态形成FilterExpression: -

var titleValues = ["The Big New Movie 2012", "The Big New Movie"];
var titleObject = {};
var index = 0;
titleValues.forEach(function(value) {
    index++;
    var titleKey = ":titlevalue"+index;
    titleObject[titleKey.toString()] = value;
});

var params = {
    TableName : "Movies",
    FilterExpression : "title IN ("+Object.keys(titleObject).toString()+ ")",
    ExpressionAttributeValues : titleObject
};

答案 1 :(得分:6)

notionquest的答案是正确的,但我无法在ExpressionAttributeValues :country:status中使用我的其他值,所以这里修改了答案,让它按照我的工作要求

var AttributeValuesObject = {};

  AttributeValuesObject[':country '] = "USA";
  AttributeValuesObject[':status'] = 1;

  var titleValues = ["1", "2"];
  var titleObject = {}; 

  var index = 0; 

  titleValues.forEach(function(value) {
    index++;
    var titleKey = ":titleValue"+index;
    AttributeValuesObject[titleKey.toString()] = value;
    titleObject[titleKey.toString()] = value;
  });

  var params = {
    TableName: "User",
    IndexName:"a-b-index",
    KeyConditionExpression: "Country = :country and #s = :status",
    FilterExpression: "Id IN ("+Object.keys(titleObject).toString()+ ")",
    ExpressionAttributeValues: AttributeValuesObject,
    ExpressionAttributeNames: {"#s": "Status"}
  };

  //get users
  dynamodb.query(params, function (err, data) {
    if (err)
      //error
    else {
      //success

    }
   });

答案 2 :(得分:1)

您还可以使用notionquest的方法,只需将其他属性值插入titleObject{}内。 例如

var titleObject = { ": country": "USA", ":status": 1, }; 
  

注意:如果不使用,则可能必须添加“ S”之类的架构   DocumentClient

     var titleObject = { 
      ":country": { "S":"USA" }, ...

}

答案 3 :(得分:0)

使用es5和地图:

it()

答案 4 :(得分:0)

我已经做到了,只解析一次参数列表

const users = [{userId:1, name:'joe'}, {userId:2, name:'mike'}]
const expressionAttributeValues = {};
const userIdParams = users.map((u, i) => {
  const userParam = `:user${i}`;
  expressionAttributeValues[userParam] = u.userId;
  return userParam;
}).join(',')
var params = {
    TableName : 'Users',
    FilterExpression : `username IN (${userIdParams})`,
    ExpressionAttributeValues : expressionAttributeValues
};

答案 5 :(得分:0)

Python3版本:

def get_filter_for_in_clause(column_name, in_values, column_type="S"):
    expressions = []
    for i in range(len(in_values)):
        expressions.append(f':temp{i}')
    filter_expression = f'{column_name} IN ({", ".join(expressions)})'

    expression_attribute_values = {}
    for index, expression in enumerate(expressions):
        expression_attribute_values[expression] = {column_type: in_values[index]}

    return filter_expression, expression_attribute_values

用法:

column = 'testcolumn'
inputs = ['testvalue1', 'testvalue2', 'testvalue3']
filter_expression, expression_attribute_values = get_filter_for_in_clause(column, inputs)

结果:

# filter_expression = 'testcolumn IN (:temp0, :temp1, :temp2)'
# expression_attribute_values = {':temp0': {'S': 'testvalue1'}, ':temp1': {'S': 'testvalue2'}, ':temp2': {'S': 'testvalue3'}}