简体   繁体   English

在Python中使用boto.dynamodb2在AWS DynamoDb中增加计数器

[英]Increment counter in AWS DynamoDb using boto.dynamodb2 in Python

I'm using DynamoDb v2 interface for boto to make counter increments in my table. 我在Boto上使用DynamoDb v2界面在表中增加计数器。 (I need v2 interface as I'll be dealing with indexes later on) (我需要v2接口,因为稍后我将处理索引)

Somehow I'm not able to find how to do that without fetching item & updating it again. 不知何故,我无法找到方法而又不获取项目并再次更新。

Here is the code I'm using 这是我正在使用的代码

from boto.dynamodb2.table import Table
from boto.dynamodb2.items import Item

my_table = Table('my-table')

# Update counter for existing record.
data = {'key': 'my_key',
        'range_key': 'my_range',
       }

item = Item(my_table, data)
#### Do something here to increment 'counter' by 1
item.save()

What should I do to increment a 'counter' field?? 我应该怎么做才能增加“计数器”字段?

Check out this answer: Update DynamoDB Atomic Counter with Python / Boto 看看这个答案: 使用Python / Boto更新DynamoDB原子计数器

This is dealing with DynamoDB v1, and I have not tested if this still works with v2. 这正在处理DynamoDB v1,并且我尚未测试它是否仍适用于v2。

If you are already fetching the current value, it appears that 如果您已经在获取当前值,则似乎

item.add_attribute('counter', 1)
item.save()

will do an update_item request. 将执行一个update_item请求。

You can also do an update_item request directly: 您也可以直接执行update_item请求:

dynoConnLayer1.update_item("my_table", 
                    {"key":{"S":"my_key"}, 'range_key' : {"S": "my_range"}},
                    {"counter":
                        {"Action":"ADD","Value":{"N":"1"}}
                    }
                )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM