Getting started with Amazon dynamodb 8: deleting projects

Time:2020-10-24

The last article introduced the dynamodb update, this one will introduce the project deletion operation and dynamoab py

Delete data from table

In SQL, the delete statement removes one or more rows from the table.Dynamodb uses the delete item operation to delete items one at a time.

SQL

In SQL, you can use the delete statement to delete one or more rows. The where clause determines the row to modify. Examples are as follows:

DELETE FROM Music
WHERE Artist = ‘The Acme Band’ AND SongTitle = ‘Look Out, World’;
We can modify the where clause to delete multiple rows. For example, delete all songs from a particular artist, as follows:

DELETE FROM Music WHERE Artist = ‘The Acme Band’

Note

If the where clause is omitted, the database attempts to remove all rows from the table.

DynamoDB

In dynamodb, you can use the delete item operation to modify a single item.

( http://docs.aws.amazon.com/zh… The syntax is as follows]:

{
   "ConditionExpression": "string",
   "ExpressionAttributeNames": {
      "string" : "string"
   },
   "ExpressionAttributeValues": {
      "string" : {
         "B": blob,
         "BOOL": boolean,
         "BS": [ blob ],
         "L": [
            "AttributeValue"
         ],
         "M": {
            "string" : "AttributeValue"
         },
         "N": "string",
         "NS": [ "string" ],
         "NULL": boolean,
         "S": "string",
         "SS": [ "string" ]
      }
   },
   "Key": {
      "string" : {
         "B": blob,
         "BOOL": boolean,
         "BS": [ blob ],
         "L": [
            "AttributeValue"
         ],
         "M": {
            "string" : "AttributeValue"
         },
         "N": "string",
         "NS": [ "string" ],
         "NULL": boolean,
         "S": "string",
         "SS": [ "string" ]
      }
   },
   "ReturnConsumedCapacity": "string",
   "ReturnItemCollectionMetrics": "string",
   "ReturnValues": "string",
   "TableName": "string"
}

Parameter Description:

  • Key: primary key, used to locate items

  • Tablename: table name (minimum 3. Maximum 255)

  • Conditionexpression: conditional expression (successfully completed only if the specific conditionexpression evaluates to true)

  • Expressionattributenames: alias of the name of the conditional expression. For example, date is a reserved word, and the alias can be defined as ා D

  • Expressionattributevalues: values of conditional expressions

  • Return combined capacity: displays the number of units of write capacity used

    • Total will return the write capacity occupied by the table and all its global secondary indexes;

    • Indexes only returns the write capacity occupied by global secondary index;

    • None means you don’t need to return any statistics.

  • Returnvalues: the data returned after the update

    • None – if not specified, return none (this is the default)

    • ALL_ Old – returns the entire project as it was before the update.

  • ReturnItemCollectionMetrics: Determines whether item collection metrics are returned. If set to SIZE , the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to NONE (the default), no statistics are returned.

( http://boto3.readthedocs.io/e… The grammar is as follows]

response = table.delete_item(
    Key={
        'string': 'string'|123|Binary(b'bytes')|True|None|set(['string'])|set([123])|set([Binary(b'bytes')])|[]|{}
    },
    ConditionalOperator='AND'|'OR',
    ReturnValues='NONE'|'ALL_OLD'|'UPDATED_OLD'|'ALL_NEW'|'UPDATED_NEW',
    ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE',
    ReturnItemCollectionMetrics='SIZE'|'NONE',
    ConditionExpression=Attr('myattribute').eq('myvalue'),
    ExpressionAttributeNames={
        'string': 'string'
    },
    ExpressionAttributeValues={
        'string': 'string'|123|Binary(b'bytes')|True|None|set(['string'])|set([123])|set([Binary(b'bytes')])|[]|{}
    }
)

In dynamodb, you can use the delete item operation to delete data from a table (one item at a time). You must specify a primary key value for the item. Examples are as follows:

{
    TableName: "Music",
    Key: {
        Artist: "The Acme Band",
        SongTitle: "Look Out, World"
    }
}

Note

In addition to the delete item, Amazon dynamodb also supports the batchwriteitem operation to delete multiple items at the same time.

Deleteitem supports conditional writing, in which case the operation completes successfully only if the evaluation of a specific conditionexpression is true. For example, the following deleteitem action deletes an item only if it has a recordlabel property:

{
    TableName: "Music",
    Key: {
        Artist: "The Acme Band",
        SongTitle: "Look Out, World"
    },
   ConditionExpression: "attribute_exists(RecordLabel)"
}

The deletion operation is so simple. The following is the benefit time.

Is it possible that every time we use boto3 to operate dynamodb, we will introduce a new tool.

dynamodb-py

Dynamodb py is a dynamodb ORM written in imitation of Sqlalchemy. Its usage is particularly simple. Here are some examples:

Table operations
from dynamodb.model import Model
from dynamodb.fields import CharField, IntegerField, FloatField, DictField
from dynamodb.table import Table

class Movies(Model):

    __table_name__ = 'Movies'

    ReadCapacityUnits = 10
    WriteCapacityUnits = 10

    year = IntegerField(name='year', hash_key=True)
    title = CharField(name='title', range_key=True)
    rating = FloatField(name='rating', indexed=True)
    rank = IntegerField(name='rank', indexed=True)
    release_date = CharField(name='release_date')
    info = DictField(name='info', default={})

# create_table
Table(Movies()).create()

# update_table
Table(Movies()).update()

# delete_table
Table(Movies()).delete()
Query items
# query without index
items = Movies.query().where(Movies.year.eq(year)).all()
items = Movies.query().where(Movies.year.eq(1985)).limit(10).all()
items = (Movies.query()
        .where(Movies.year.eq(1992),
               Movies.title.between('A', 'L'))
        .all())

# query with index
items = (Movies.query()
        .where(Movies.year.eq(1992),
               Movies.title.between('A', 'L'))
        .order_by(Movies.rating, asc=False)
        .all())
Update project
item = Movies.get(year=year, title=title)

item.update(rank=2467, rating=7.1)
delete item
item = Movies.get(year=year, title=title)

item.delete()

It’s so convenient.

However, dynamodb py is still under development. You are welcome to try it out and contribute your own strength.

Finally, the next section covers index queries

Recommended Today

Blog based on beego, go blog

Go Blog A beego based development, can quickly create personal blog, CMS system Include functions see Official website of go bloggo-blog.cn Demo siteleechan.online Update log time function January 23, 2020 New top post function February 2, 2020 New custom navigation function February 4, 2020 New site announcement function February 6, 2020 New link module February […]