DynamoDB-条件表达式ConditionExpression

主题:

  1. 防止覆盖项目现有的项目
  2. 检查项目中的属性
  3. 有条件删除
  4. 有条件更新
  5. 比较运算符和函数引用

条件表达式的语法:

condition-expression ::=
      operand comparator operand
    | operand BETWEEN operand AND operand
    | operand IN ( operand (',' operand (, ...) ))
    | function
    | condition AND condition
    | condition OR condition
    | NOT condition
    | ( condition )

comparator ::=
    =
    | <>
    | <
    | <=
    | >
    | >=

function ::=
    attribute_exists (path)
    | attribute_not_exists (path)
    | attribute_type (path, type)
    | begins_with (path, substr)
    | contains (path, operand)
    | size (path)

  • 防止覆盖项目现有的项目( attribute_not_existsattribute_exists  )

          PutItem 操作将覆盖具有相同键的项目 (如果存在)。如果要避免这种情况,请使用条件表达式。这仅允许写入在有问题的项目没有相同的键时继续进行:

  

 case 'PUT': {
            var table = 'book_table', hash = 'book', id = "05d101be-d5e8-43ec-8eb6-5530e21af83e";
            var params = {
                TableName: table,
                Key: {
                    "hash": hash,
                    "id": id
                },

                UpdateExpression: "SET price = :p",
                ConditionExpression: "attribute_not_exists(#c)",
                ExpressionAttributeNames: {
                    "#c": "count"
                },
                ExpressionAttributeValues: {
                    ":p": 99.99
                }, 
               ReturnValues: "ALL_NEW"
            };

           await docClient.update( params ).promise().then(
                ( success ) => {
                    response.body = JSON.stringify({ "success:": success })
                }
               
            ).catch(
                ( err ) => {
                    console.log(err);
                    response.statusCode = err.statusCode;
                    response.body = JSON.stringify({
                        code: err.code,
                        message: err.message
                    })
                }
            );
            callback( null, response );
            break;
       };

  程序运行后返回:

 

{
    "success:": {
        "Attributes": {
            "booktype": [
                "青春文学",
                "历史典故"
            ],
            "id": "9f3f9c74-8e23-4e46-b440-4b3532048ad6",
            "price": 99.99,
            "hash": "book"
        }
    }
}

  

  • 检查项目中的属性(attribute_not_existsattribute_exists )

您可以检查任何属性是否存在。如果条件表达式的计算结果为 true,操作将成功;否则操作将失败。

 case 'PUT': {
            var table = 'book_table', hash = 'book', id = "05d101be-d5e8-43ec-8eb6-5530e21af83e";
            var params = {
                TableName: table,
                Key: {
                    "hash": hash,
                    "id": id
                },

                UpdateExpression: "SET price = :p",
                ConditionExpression: "attribute_exists(#c)",
                ExpressionAttributeNames: {
                    "#c": "count"
                },
                ExpressionAttributeValues: {
                    ":p": 55.55
                },
               ReturnValues: "ALL_NEW"
            };

           await docClient.update( params ).promise().then(
                ( success ) => {
                    response.body = JSON.stringify({ "success:": success })
                }
               
            ).catch(
                ( err ) => {
                    console.log(err);
                    response.statusCode = err.statusCode;
                    response.body = JSON.stringify({
                        code: err.code,
                        message: err.message
                    })
                }
            );
            callback( null, response );
            break;
       };

  程序运行成功后返回:

{
    "success:": {
        "Attributes": {
            "date": "2010-01-01",
            "author": "韩寒",
            "price": 55.55,
            "zan": 2048,
            "count": 10,
            "name": "三重门",
            "description": "本书通过少年林雨翔的视角,向读者揭示了真实的高中生的生活,体现了学生式的思考、困惑和梦想。",
            "id": "05d101be-d5e8-43ec-8eb6-5530e21af83e",
            "sn": "100-100-010",
            "type": "情感其他",
            "hash": "book"
        }
    }
}

  

  • 有条件删除

要执行有条件删除,请将 DeleteItem 操作与条件表达式一起使用。要继续执行操作,条件表达式的求值结果必须为 true;否则操作将失败。

使用 BETWEEN 和 IN 关键字来将操作数与值范围或值的枚举值列表进行比较:

  • a BETWEEN b AND c - 如果 a 大于或等于 b 并且小于或等于 c,则为 true。

  • a IN (bcd- 如果 a 等于列表中的任何值(例如,bc 或 d 任意之一),则为 true。列表最多可以包含 100 个值,以逗号分隔。

例如:

{
    
    "booktype": [
                "青春文学",
                "历史典故"
            ],
    "id": "9f3f9c74-8e23-4e46-b440-4b3532048ad6",
   "price": 99.99,
    "hash": "book"
}

  

case 'DELETE': {
            var table ='book_table', hash = 'book', 
            id = '9f3f9c74-8e23-4e46-b440-4b3532048ad6';
            var params = {
                TableName: table,
                Key: {
                    "hash": hash,
                    "id": id
                },
                ConditionExpression: "(booktype[0] IN (:c1, :c2)) and (price between :p1 and :p2)",
                ExpressionAttributeValues: {
                    ":c1": "青春文学",
                    ":c2":  "愿风裁尘",
                    ":p1": 90,
                    ":p2": 110
                },
                await docClient.delete( params ).promise().then(
                ( data ) => {
                    response.body = JSON.stringify({"success": data});
                    console.log("success", data );
                    
                }
            ).catch(
                ( err ) =>{
                    console.log("error", err );
                    response.statusCode = err.statusCode;
                    response.body = JSON.stringify({"error": err});
                }
            );
            callback( null, response );
            break;
        }

  程序运行成功后返回:

{
    "success": {}
}

  

  •  有条件更新

要执行有条件更新,请将 UpdateItem 操作与条件表达式一起使用。要继续执行操作,条件表达式的求值结果必须为 true;否则操作将失败。

注意:UpdateItem 还支持更新表达式,您在其中指定要对项目进行的修改和更改

        case 'PUT': {
            var table = 'book_table', hash = 'book', id = "05d101be-d5e8-43ec-8eb6-5530e21af83e";
            var params = {
                TableName: table,
                Key: {
                    "hash": hash,
                    "id": id
                },

        UpdateExpression: "SET price = price - :discount",
                ConditionExpression: "price > :limit",
                ExpressionAttributeValues: {
                    ":discount": 50,
                    ":limit": 1000
                },
                ReturnValues: "ALL_NEW"
            };

           await docClient.update( params ).promise().then(
                ( success ) => {
                    response.body = JSON.stringify({ "success:": success })
                }
               
            ).catch(
                ( err ) => {
                    console.log(err);
                    response.statusCode = err.statusCode;
                    response.body = JSON.stringify({
                        code: err.code,
                        message: err.message
                    })
                }
            );
            callback( null, response );
            break;
       };

  程序运行成功后返回:

{
    "success:": {
        "Attributes": {
            "date": "2010-01-01",
            "author": "韩寒",
            "price": 974,
            "zan": 2048,
            "count": 10,
            "name": "三重门",
            "description": "本书通过少年林雨翔的视角,向读者揭示了真实的高中生的生活,体现了学生式的思考、困惑和梦想。",
            "id": "05d101be-d5e8-43ec-8eb6-5530e21af83e",
            "sn": "100-100-010",
            "type": "情感其他",
            "hash": "book"
        }
    }
}
  •  比较运算符和函数引用
    •   begins_with(path, substr): 如果 path 指定的属性以特定子字符串开头,则为 true。
                     UpdateExpression: "SET zan = :z",
                      ConditionExpression: "begins_with(#u, :v)",
                      ExpressionAttributeNames: {
                          "#u": "uri"
                      },
                      ExpressionAttributeValues: {
                          ":z": 1024,
                          ":v": "https://www.cnblogs.com"
                      },
                      ReturnValues: "ALL_NEW"
      

        程序运行成功后返回:

{
    "success:": {
        "Attributes": {
            "date": "2010-01-01",
            "author": "韩寒",
            "zan": 1024,
            "price": 55.55,
            "count": 10,
            "name": "三重门",
            "description": "本书通过少年林雨翔的视角,向读者揭示了真实的高中生的生活,体现了学生式的思考、困惑和梦想。",
            "id": "05d101be-d5e8-43ec-8eb6-5530e21af83e",
            "sn": "100-100-010",
            "type": "情感其他",
            "uri": "https://www.cnblogs.com/landen/p/9790704.html ",
            "hash": "book"
        }
    }
}
    • attribute_type (pathtype): 如果指定路径中的属性为特定数据类型,则为 true。
 1                 UpdateExpression: "SET zan = :z",
 2                 ConditionExpression: "attribute_type(#p,:v_sub)",
 3                 ExpressionAttributeNames: {
 4                     "#p": "price"
 5                 },
 6                 ExpressionAttributeValues: {
 7                     ":z": 520,
 8                     ":v_sub": "N"
 9                 },
10                 ReturnValues: "ALL_NEW"

  程序运行成功后返回:

{
    "success:": {
        "Attributes": {
            "date": "2010-01-01",
            "author": "韩寒",
            "zan": 520,
            "price": 55.55,
            "count": 10,
            "name": "三重门",
            "description": "本书通过少年林雨翔的视角,向读者揭示了真实的高中生的生活,体现了学生式的思考、困惑和梦想。",
            "id": "05d101be-d5e8-43ec-8eb6-5530e21af83e",
            "sn": "100-100-010",
            "type": "情感其他",
            "uri": "https://www.cnblogs.com/landen/p/9790704.html ",
            "hash": "book"
        }
    }
}

 

ps: 本文为本人原创文章,若有疑问,欢迎下方留言,也可自读aws的相关api文档: https://docs.aws.amazon.com/zh_cn/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html

posted @ 2018-10-15 14:12  曦言鸢默  阅读(505)  评论(0编辑  收藏  举报