1
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
3
# Permission is hereby granted, free of charge, to any person obtaining a
4
# copy of this software and associated documentation files (the
5
# "Software"), to deal in the Software without restriction, including
6
# without limitation the rights to use, copy, modify, merge, publish, dis-
7
# tribute, sublicense, and/or sell copies of the Software, and to permit
8
# persons to whom the Software is furnished to do so, subject to the fol-
11
# The above copyright notice and this permission notice shall be included
12
# in all copies or substantial portions of the Software.
14
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22
from binascii import crc32
26
from boto.connection import AWSQueryConnection
27
from boto.regioninfo import RegionInfo
28
from boto.exception import JSONResponseError
29
from boto.dynamodb2 import exceptions
32
class DynamoDBConnection(AWSQueryConnection):
34
Amazon DynamoDB is a fast, highly scalable, highly available,
35
cost-effective non-relational database service. Amazon DynamoDB
36
removes traditional scalability limitations on data storage while
37
maintaining low latency and predictable performance.
39
APIVersion = "2012-08-10"
40
DefaultRegionName = "us-east-1"
41
DefaultRegionEndpoint = "dynamodb.us-east-1.amazonaws.com"
42
ServiceName = "DynamoDB"
43
TargetPrefix = "DynamoDB_20120810"
44
ResponseError = JSONResponseError
47
"ProvisionedThroughputExceededException": exceptions.ProvisionedThroughputExceededException,
48
"LimitExceededException": exceptions.LimitExceededException,
49
"ConditionalCheckFailedException": exceptions.ConditionalCheckFailedException,
50
"ResourceInUseException": exceptions.ResourceInUseException,
51
"ResourceNotFoundException": exceptions.ResourceNotFoundException,
52
"InternalServerError": exceptions.InternalServerError,
53
"ItemCollectionSizeLimitExceededException": exceptions.ItemCollectionSizeLimitExceededException,
54
"ValidationException": exceptions.ValidationException,
60
def __init__(self, **kwargs):
61
region = kwargs.pop('region', None)
62
validate_checksums = kwargs.pop('validate_checksums', True)
64
region = RegionInfo(self, self.DefaultRegionName,
65
self.DefaultRegionEndpoint)
66
kwargs['host'] = region.endpoint
67
AWSQueryConnection.__init__(self, **kwargs)
69
self._validate_checksums = boto.config.getbool(
70
'DynamoDB', 'validate_checksums', validate_checksums)
72
def _required_auth_capability(self):
75
def batch_get_item(self, request_items, return_consumed_capacity=None):
77
The BatchGetItem operation returns the attributes for multiple
78
items from multiple tables using their primary keys. The
79
maximum number of items that can be retrieved for a single
80
operation is 100. Also, the number of items retrieved is
81
constrained by a 1 MB size limit. If the response size limit
82
is exceeded or a partial result is returned because the
83
tables provisioned throughput is exceeded, or because of an
84
internal processing failure, Amazon DynamoDB returns an
85
UnprocessedKeys value so you can retry the operation starting
86
with the next item to get. Amazon DynamoDB automatically
87
adjusts the number of items returned per page to enforce this
88
limit. For example, even if you ask to retrieve 100 items, but
89
each individual item is 50 KB in size, the system returns 20
90
items and an appropriate UnprocessedKeys value so you can get
91
the next page of results. If desired, your application can
92
include its own logic to assemble the pages of results into
95
If no items could be processed because of insufficient
96
provisioned throughput on each of the tables involved in the
97
request, Amazon DynamoDB returns a
98
ProvisionedThroughputExceededException .
100
By default, BatchGetItem performs eventually consistent reads
101
on every table in the request. You can set ConsistentRead to
102
`True`, on a per-table basis, if you want consistent reads
105
BatchGetItem fetches items in parallel to minimize response
108
When designing your application, keep in mind that Amazon
109
DynamoDB does not guarantee how attributes are ordered in the
110
returned response. Include the primary key values in the
111
AttributesToGet for the items in your request to help parse
112
the response by item.
114
If the requested items do not exist, nothing is returned in
115
the response for those items. Requests for non-existent items
116
consume the minimum read capacity units according to the type
117
of read. For more information, see `Capacity Units
118
Calculations`_ of the Amazon DynamoDB Developer Guide .
120
:type request_items: map
121
:param request_items:
122
A map of one or more table names and, for each table, the corresponding
123
primary keys for the items to retrieve. While requesting items,
124
each table name can be invoked only once per operation.
126
Each KeysAndAttributes element consists of:
129
+ Keys -An array of primary key attribute values that define the items
130
and the attributes associated with the items.
131
+ AttributesToGet -One or more attributes to retrieve from the table or
132
index. If AttributesToGet is not specified, then all attributes
133
will be returned. If any of the specified attributes are not found,
134
they will not appear in the result.
135
+ ConsistentRead -The consistency of a read operation. If set to
136
`True`, then a strongly consistent read is used; otherwise, an
137
eventually consistent read is used.
139
:type return_consumed_capacity: string
140
:param return_consumed_capacity:
143
params = {'RequestItems': request_items, }
144
if return_consumed_capacity is not None:
145
params['ReturnConsumedCapacity'] = return_consumed_capacity
146
return self.make_request(action='BatchGetItem',
147
body=json.dumps(params))
149
def batch_write_item(self, request_items, return_consumed_capacity=None,
150
return_item_collection_metrics=None):
152
This operation enables you to put or delete several items
153
across multiple tables in a single API call.
155
To upload one item, you can use the PutItem API and to delete
156
one item, you can use the DeleteItem API. However, when you
157
want to upload or delete large amounts of data, such as
158
uploading large amounts of data from Amazon Elastic MapReduce
159
(EMR) or migrate data from another database into Amazon
160
DynamoDB, this API offers an efficient alternative.
162
If you use a programming language that supports concurrency,
163
such as Java, you can use threads to upload items in parallel.
164
This adds complexity in your application to handle the
165
threads. With other languages that don't support threading,
166
such as PHP, you must upload or delete items one at a time. In
167
both situations, the BatchWriteItem API provides an
168
alternative where the API performs the specified put and
169
delete operations in parallel, giving you the power of the
170
thread pool approach without having to introduce complexity in
173
Note that each individual put and delete specified in a
174
BatchWriteItem operation costs the same in terms of consumed
175
capacity units, however, the API performs the specified
176
operations in parallel giving you lower latency. Delete
177
operations on non-existent items consume 1 write capacity
180
When using this API, note the following limitations:
183
+ Maximum operations in a single request- You can specify a
184
total of up to 25 put or delete operations; however, the total
185
request size cannot exceed 1 MB (the HTTP payload).
186
+ You can use the BatchWriteItem operation only to put and
187
delete items. You cannot use it to update existing items.
188
+ Not an atomic operation- The individual PutItem and
189
DeleteItem operations specified in BatchWriteItem are atomic;
190
however BatchWriteItem as a whole is a "best-effort" operation
191
and not an atomic operation. That is, in a BatchWriteItem
192
request, some operations might succeed and others might fail.
193
The failed operations are returned in UnprocessedItems in the
194
response. Some of these failures might be because you exceeded
195
the provisioned throughput configured for the table or a
196
transient failure such as a network error. You can investigate
197
and optionally resend the requests. Typically, you call
198
BatchWriteItem in a loop and in each iteration check for
199
unprocessed items, and submit a new BatchWriteItem request
200
with those unprocessed items.
201
+ Does not return any items- The BatchWriteItem is designed
202
for uploading large amounts of data efficiently. It does not
203
provide some of the sophistication offered by APIs such as
204
PutItem and DeleteItem . For example, the DeleteItem API
205
supports ReturnValues in the request body to request the
206
deleted item in the response. The BatchWriteItem operation
207
does not return any items in the response.
208
+ Unlike the PutItem and DeleteItem APIs, BatchWriteItem does
209
not allow you to specify conditions on individual write
210
requests in the operation.
211
+ Attribute values must not be null; string and binary type
212
attributes must have lengths greater than zero; and set type
213
attributes must not be empty. Requests that have empty values
214
will be rejected with a ValidationException .
217
Amazon DynamoDB rejects the entire batch write operation if
218
any one of the following is true:
220
+ If one or more tables specified in the BatchWriteItem
221
request does not exist.
222
+ If primary key attributes specified on an item in the
223
request does not match the corresponding table's primary key
225
+ If you try to perform multiple operations on the same item
226
in the same BatchWriteItem request. For example, you cannot
227
put and delete the same item in the same BatchWriteItem
229
+ If the total request size exceeds the 1 MB request size (the
231
+ If any individual item in a batch exceeds the 64 KB item
234
:type request_items: map
235
:param request_items:
236
A map of one or more table names and, for each table, a list of
237
operations to perform ( DeleteRequest or PutRequest ).
240
+ DeleteRequest -Perform a DeleteItem operation on the specified item.
241
The item to be deleted is identified by:
243
+ Key -A map of primary key attribute values that uniquely identify the
244
item. Each entry in this map consists of an attribute name and an
247
+ PutRequest -Perform a PutItem operation on the specified item. The
248
item to be updated is identified by:
250
+ Item -A map of attributes and their values. Each entry in this map
251
consists of an attribute name and an attribute value. If you
252
specify any attributes that are part of an index key, then the data
253
types for those attributes must match those of the schema in the
254
table's attribute definition.
256
:type return_consumed_capacity: string
257
:param return_consumed_capacity:
259
:type return_item_collection_metrics: string
260
:param return_item_collection_metrics: Indicates whether to return
261
statistics about item collections, if any, that were modified
262
during the operation. The default for ReturnItemCollectionMetrics
263
is `NONE`, meaning that no statistics will be returned. To obtain
264
the statistics, set ReturnItemCollectionMetrics to `SIZE`.
267
params = {'RequestItems': request_items, }
268
if return_consumed_capacity is not None:
269
params['ReturnConsumedCapacity'] = return_consumed_capacity
270
if return_item_collection_metrics is not None:
271
params['ReturnItemCollectionMetrics'] = return_item_collection_metrics
272
return self.make_request(action='BatchWriteItem',
273
body=json.dumps(params))
275
def create_table(self, attribute_definitions, table_name, key_schema,
276
provisioned_throughput, local_secondary_indexes=None):
278
The CreateTable operation adds a new table to your account. In
279
an AWS account, table names must be unique within each region.
280
That is, you can have two tables with same name if you create
281
the tables in different regions.
283
CreateTable is an asynchronous operation. Upon receiving a
284
CreateTable request, Amazon DynamoDB immediately returns a
285
response with a TableStatus of `CREATING`. After the table is
286
created, Amazon DynamoDB sets the TableStatus to `ACTIVE`. You
287
can perform read and write operations only on an `ACTIVE`
290
You can use the DescribeTable API to check the table status.
292
:type attribute_definitions: list
293
:param attribute_definitions: An array of attributes that describe the
294
key schema for the table and indexes.
296
:type table_name: string
297
:param table_name: The name of the table to create.
299
:type key_schema: list
300
:param key_schema: Specifies the attributes that make up the primary
301
key for the table. The attributes in KeySchema must also be defined
302
in the AttributeDefinitions array. For more information, see `Data
303
Model`_ of the Amazon DynamoDB Developer Guide .
304
Each KeySchemaElement in the array is composed of:
307
+ AttributeName -The name of this key attribute.
308
+ KeyType -Determines whether the key attribute is `HASH` or `RANGE`.
311
For more information, see `Specifying the Primary Key`_ of the Amazon
312
DynamoDB Developer Guide .
314
:type local_secondary_indexes: list
315
:param local_secondary_indexes:
316
One or more secondary indexes to be created on the table. Each index is
317
scoped to a given hash key value. There is a 10 gigabyte size limit
318
per hash key; otherwise, the size of a local secondary index is
321
Each secondary index in the array includes the following:
324
+ IndexName -The name of the secondary index. Must be unique only for
326
+ KeySchema -Specifies the key schema for the index. The key schema
327
must begin with the same hash key attribute as the table.
328
+ Projection -Specifies attributes that are copied (projected) from the
329
table into the index. These are in addition to the primary key
330
attributes and index key attributes, which are automatically
331
projected. Each attribute specification is composed of:
333
+ ProjectionType -One of the following:
335
+ `ALL`-All of the table attributes are projected into the index.
336
+ `KEYS_ONLY`-Only the index and primary keys are projected into the
338
+ `INCLUDE`-Only the specified table attributes are projected into the
339
index. The list of projected attributes are in NonKeyAttributes .
341
+ NonKeyAttributes -A list of one or more non-key attribute names that
342
are projected into the index.
344
:type provisioned_throughput: dict
345
:param provisioned_throughput:
349
'AttributeDefinitions': attribute_definitions,
350
'TableName': table_name,
351
'KeySchema': key_schema,
352
'ProvisionedThroughput': provisioned_throughput,
354
if local_secondary_indexes is not None:
355
params['LocalSecondaryIndexes'] = local_secondary_indexes
356
return self.make_request(action='CreateTable',
357
body=json.dumps(params))
359
def delete_item(self, table_name, key, expected=None, return_values=None,
360
return_consumed_capacity=None,
361
return_item_collection_metrics=None):
363
Deletes a single item in a table by primary key. You can
364
perform a conditional delete operation that deletes the item
365
if it exists, or if it has an expected attribute value.
367
In addition to deleting an item, you can also return the
368
item's attribute values in the same operation, using the
369
ReturnValues parameter.
371
Unless you specify conditions, the DeleteItem is an idempotent
372
operation; running it multiple times on the same item or
373
attribute does not result in an error response.
375
Conditional deletes are useful for only deleting items if
376
specific conditions are met. If those conditions are met,
377
Amazon DynamoDB performs the delete. Otherwise, the item is
380
:type table_name: string
381
:param table_name: The name of the table from which to delete the item.
384
:param key: A map of attribute names to AttributeValue objects,
385
representing the primary key of the item to delete.
388
:param expected: A map of attribute/condition pairs. This is the
389
conditional block for the DeleteItem operation. All the conditions
390
must be met for the operation to succeed.
391
Expected allows you to provide an attribute name, and whether or not
392
Amazon DynamoDB should check to see if the attribute value already
393
exists; or if the attribute value exists and has a particular value
396
Each item in Expected represents an attribute name for Amazon DynamoDB
397
to check, along with the following:
400
+ Value -the attribute value for Amazon DynamoDB to check.
401
+ Exists -causes Amazon DynamoDB to evaluate the value before
402
attempting a conditional operation:
404
+ If Exists is `True`, Amazon DynamoDB will check to see if that
405
attribute value already exists in the table. If it is found, then
406
the operation succeeds. If it is not found, the operation fails
407
with a ConditionalCheckFailedException .
408
+ If Exists is `False`, Amazon DynamoDB assumes that the attribute
409
value does not exist in the table. If in fact the value does not
410
exist, then the assumption is valid and the operation succeeds. If
411
the value is found, despite the assumption that it does not exist,
412
the operation fails with a ConditionalCheckFailedException .
413
The default setting for Exists is `True`. If you supply a Value all by
414
itself, Amazon DynamoDB assumes the attribute exists: You don't
415
have to set Exists to `True`, because it is implied. Amazon
416
DynamoDB returns a ValidationException if:
418
+ Exists is `True` but there is no Value to check. (You expect a value
419
to exist, but don't specify what that value is.)
420
+ Exists is `False` but you also specify a Value . (You cannot expect
421
an attribute to have a value, while also expecting it not to
426
If you specify more than one condition for Exists , then all of the
427
conditions must evaluate to true. (In other words, the conditions
428
are ANDed together.) Otherwise, the conditional operation will
431
:type return_values: string
432
:param return_values:
433
Use ReturnValues if you want to get the item attributes as they
434
appeared before they were deleted. For DeleteItem , the valid
438
+ `NONE`-(default) If ReturnValues is not specified, or if its value is
439
`NONE`, then nothing is returned.
440
+ `ALL_OLD`-The content of the old item is returned.
442
:type return_consumed_capacity: string
443
:param return_consumed_capacity:
445
:type return_item_collection_metrics: string
446
:param return_item_collection_metrics: Indicates whether to return
447
statistics about item collections, if any, that were modified
448
during the operation. The default for ReturnItemCollectionMetrics
449
is `NONE`, meaning that no statistics will be returned. To obtain
450
the statistics, set ReturnItemCollectionMetrics to `SIZE`.
453
params = {'TableName': table_name, 'Key': key, }
454
if expected is not None:
455
params['Expected'] = expected
456
if return_values is not None:
457
params['ReturnValues'] = return_values
458
if return_consumed_capacity is not None:
459
params['ReturnConsumedCapacity'] = return_consumed_capacity
460
if return_item_collection_metrics is not None:
461
params['ReturnItemCollectionMetrics'] = return_item_collection_metrics
462
return self.make_request(action='DeleteItem',
463
body=json.dumps(params))
465
def delete_table(self, table_name):
467
The DeleteTable operation deletes a table and all of its
468
items. After a DeleteTable request, the specified table is in
469
the `DELETING` state until Amazon DynamoDB completes the
470
deletion. If the table is in the `ACTIVE` state, you can
471
delete it. If a table is in `CREATING` or `UPDATING` states,
472
then Amazon DynamoDB returns a ResourceInUseException . If the
473
specified table does not exist, Amazon DynamoDB returns a
474
ResourceNotFoundException . If table is already in the
475
`DELETING` state, no error is returned.
477
Amazon DynamoDB might continue to accept data read and write
478
operations, such as GetItem and PutItem , on a table in the
479
`DELETING` state until the table deletion is complete.
481
Tables are unique among those associated with the AWS Account
482
issuing the request, and the AWS region that receives the
483
request (such as dynamodb.us-east-1.amazonaws.com). Each
484
Amazon DynamoDB endpoint is entirely independent. For example,
485
if you have two tables called "MyTable," one in dynamodb.us-
486
east-1.amazonaws.com and one in dynamodb.us-
487
west-1.amazonaws.com, they are completely independent and do
488
not share any data; deleting one does not delete the other.
490
Use the DescribeTable API to check the status of the table.
492
:type table_name: string
493
:param table_name: The name of the table to delete.
496
params = {'TableName': table_name, }
497
return self.make_request(action='DeleteTable',
498
body=json.dumps(params))
500
def describe_table(self, table_name):
502
Returns information about the table, including the current
503
status of the table, when it was created, the primary key
504
schema,and any indexes on the table.
506
:type table_name: string
507
:param table_name: The name of the table to describe.
510
params = {'TableName': table_name, }
511
return self.make_request(action='DescribeTable',
512
body=json.dumps(params))
514
def get_item(self, table_name, key, attributes_to_get=None,
515
consistent_read=None, return_consumed_capacity=None):
517
The GetItem operation returns a set of attributes for the item
518
with the given primary key. If there is no matching item,
519
GetItem does not return any data.
521
GetItem provides an eventually consistent read by default. If
522
your application requires a strongly consistent read, set
523
ConsistentRead to `True`. Although a strongly consistent read
524
might take more time than an eventually consistent read, it
525
always returns the last updated value.
527
:type table_name: string
528
:param table_name: The name of the table containing the requested item.
531
:param key: A map of attribute names to AttributeValue objects,
532
representing the primary key of the item to retrieve.
534
:type attributes_to_get: list
535
:param attributes_to_get: The names of one or more attributes to
536
retrieve. If no attribute names are specified, then all attributes
537
will be returned. If any of the requested attributes are not found,
538
they will not appear in the result.
540
:type consistent_read: boolean
541
:param consistent_read: If set to `True`, then the operation uses
542
strongly consistent reads; otherwise, eventually consistent reads
545
:type return_consumed_capacity: string
546
:param return_consumed_capacity:
549
params = {'TableName': table_name, 'Key': key, }
550
if attributes_to_get is not None:
551
params['AttributesToGet'] = attributes_to_get
552
if consistent_read is not None:
553
params['ConsistentRead'] = consistent_read
554
if return_consumed_capacity is not None:
555
params['ReturnConsumedCapacity'] = return_consumed_capacity
556
return self.make_request(action='GetItem',
557
body=json.dumps(params))
559
def list_tables(self, exclusive_start_table_name=None, limit=None):
561
Returns an array of all the tables associated with the current
562
account and endpoint.
564
Each Amazon DynamoDB endpoint is entirely independent. For
565
example, if you have two tables called "MyTable," one in
566
dynamodb.us-east-1.amazonaws.com and one in dynamodb.us-
567
west-1.amazonaws.com , they are completely independent and do
568
not share any data. The ListTables operation returns all of
569
the table names associated with the account making the
570
request, for the endpoint that receives the request.
572
:type exclusive_start_table_name: string
573
:param exclusive_start_table_name: The name of the table that starts
574
the list. If you already ran a ListTables operation and received a
575
LastEvaluatedTableName value in the response, use that value here
576
to continue the list.
579
:param limit: A maximum number of table names to return.
583
if exclusive_start_table_name is not None:
584
params['ExclusiveStartTableName'] = exclusive_start_table_name
585
if limit is not None:
586
params['Limit'] = limit
587
return self.make_request(action='ListTables',
588
body=json.dumps(params))
590
def put_item(self, table_name, item, expected=None, return_values=None,
591
return_consumed_capacity=None,
592
return_item_collection_metrics=None):
594
Creates a new item, or replaces an old item with a new item.
595
If an item already exists in the specified table with the same
596
primary key, the new item completely replaces the existing
597
item. You can perform a conditional put (insert a new item if
598
one with the specified primary key doesn't exist), or replace
599
an existing item if it has certain attribute values.
601
In addition to putting an item, you can also return the item's
602
attribute values in the same operation, using the ReturnValues
605
When you add an item, the primary key attribute(s) are the
606
only required attributes. Attribute values cannot be null;
607
string and binary type attributes must have lengths greater
608
than zero; and set type attributes cannot be empty. Requests
609
with empty values will be rejected with a ValidationException
612
You can request that PutItem return either a copy of the old
613
item (before the update) or a copy of the new item (after the
614
update). For more information, see the ReturnValues
617
To prevent a new item from replacing an existing item, use a
618
conditional put operation with Exists set to `False` for the
619
primary key attribute, or attributes.
621
For more information about using this API, see `Working with
622
Items`_ of the Amazon DynamoDB Developer Guide .
624
:type table_name: string
625
:param table_name: The name of the table to contain the item.
628
:param item: A map of attribute name/value pairs, one for each
629
attribute. Only the primary key attributes are required; you can
630
optionally provide other attribute name-value pairs for the item.
631
If you specify any attributes that are part of an index key, then the
632
data types for those attributes must match those of the schema in
633
the table's attribute definition.
635
For more information about primary keys, see `Primary Key`_ of the
636
Amazon DynamoDB Developer Guide .
638
Each element in the Item map is an AttributeValue object.
641
:param expected: A map of attribute/condition pairs. This is the
642
conditional block for the PutItem operation. All the conditions
643
must be met for the operation to succeed.
644
Expected allows you to provide an attribute name, and whether or not
645
Amazon DynamoDB should check to see if the attribute value already
646
exists; or if the attribute value exists and has a particular value
649
Each item in Expected represents an attribute name for Amazon DynamoDB
650
to check, along with the following:
653
+ Value -the attribute value for Amazon DynamoDB to check.
654
+ Exists -causes Amazon DynamoDB to evaluate the value before
655
attempting a conditional operation:
657
+ If Exists is `True`, Amazon DynamoDB will check to see if that
658
attribute value already exists in the table. If it is found, then
659
the operation succeeds. If it is not found, the operation fails
660
with a ConditionalCheckFailedException .
661
+ If Exists is `False`, Amazon DynamoDB assumes that the attribute
662
value does not exist in the table. If in fact the value does not
663
exist, then the assumption is valid and the operation succeeds. If
664
the value is found, despite the assumption that it does not exist,
665
the operation fails with a ConditionalCheckFailedException .
666
The default setting for Exists is `True`. If you supply a Value all by
667
itself, Amazon DynamoDB assumes the attribute exists: You don't
668
have to set Exists to `True`, because it is implied. Amazon
669
DynamoDB returns a ValidationException if:
671
+ Exists is `True` but there is no Value to check. (You expect a value
672
to exist, but don't specify what that value is.)
673
+ Exists is `False` but you also specify a Value . (You cannot expect
674
an attribute to have a value, while also expecting it not to
679
If you specify more than one condition for Exists , then all of the
680
conditions must evaluate to true. (In other words, the conditions
681
are ANDed together.) Otherwise, the conditional operation will
684
:type return_values: string
685
:param return_values:
686
Use ReturnValues if you want to get the item attributes as they
687
appeared before they were updated with the PutItem request. For
688
PutItem , the valid values are:
691
+ `NONE`-(default) If ReturnValues is not specified, or if its value is
692
`NONE`, then nothing is returned.
693
+ `ALL_OLD`-If PutItem overwrote an attribute name-value pair, then the
694
content of the old item is returned.
696
:type return_consumed_capacity: string
697
:param return_consumed_capacity:
699
:type return_item_collection_metrics: string
700
:param return_item_collection_metrics: Indicates whether to return
701
statistics about item collections, if any, that were modified
702
during the operation. The default for ReturnItemCollectionMetrics
703
is `NONE`, meaning that no statistics will be returned. To obtain
704
the statistics, set ReturnItemCollectionMetrics to `SIZE`.
707
params = {'TableName': table_name, 'Item': item, }
708
if expected is not None:
709
params['Expected'] = expected
710
if return_values is not None:
711
params['ReturnValues'] = return_values
712
if return_consumed_capacity is not None:
713
params['ReturnConsumedCapacity'] = return_consumed_capacity
714
if return_item_collection_metrics is not None:
715
params['ReturnItemCollectionMetrics'] = return_item_collection_metrics
716
return self.make_request(action='PutItem',
717
body=json.dumps(params))
719
def query(self, table_name, index_name=None, select=None,
720
attributes_to_get=None, limit=None, consistent_read=None,
721
key_conditions=None, scan_index_forward=None,
722
exclusive_start_key=None, return_consumed_capacity=None):
724
A Query operation directly accesses items from a table using
725
the table primary key, or from an index using the index key.
726
You must provide a specific hash key value. You can narrow the
727
scope of the query by using comparison operators on the range
728
key value, or on the index key. You can use the
729
ScanIndexForward parameter to get results in forward or
730
reverse order, by range key or by index key.
732
Queries that do not return results consume the minimum read
733
capacity units according to the type of read.
735
If the total number of items meeting the query criteria
736
exceeds the result set size limit of 1 MB, the query stops and
737
results are returned to the user with a LastEvaluatedKey to
738
continue the query in a subsequent operation. Unlike a Scan
739
operation, a Query operation never returns an empty result set
740
and a LastEvaluatedKey . The LastEvaluatedKey is only provided
741
if the results exceed 1 MB, or if you have used Limit .
743
To request a strongly consistent result, set ConsistentRead to
746
:type table_name: string
747
:param table_name: The name of the table containing the requested
750
:type index_name: string
751
:param index_name: The name of an index on the table to query.
754
:param select: The attributes to be returned in the result. You can
755
retrieve all item attributes, specific item attributes, the count
756
of matching items, or in the case of an index, some or all of the
757
attributes projected into the index.
759
+ `ALL_ATTRIBUTES`: Returns all of the item attributes. For a table,
760
this is the default. For an index, this mode causes Amazon DynamoDB
761
to fetch the full item from the table for each matching item in the
762
index. If the index is configured to project all item attributes,
763
the matching items will not be fetched from the table. Fetching
764
items from the table incurs additional throughput cost and latency.
765
+ `ALL_PROJECTED_ATTRIBUTES`: Allowed only when querying an index.
766
Retrieves all attributes which have been projected into the index.
767
If the index is configured to project all attributes, this is
768
equivalent to specifying ALL_ATTRIBUTES .
769
+ `COUNT`: Returns the number of matching items, rather than the
770
matching items themselves.
771
+ `SPECIFIC_ATTRIBUTES` : Returns only the attributes listed in
772
AttributesToGet . This is equivalent to specifying AttributesToGet
773
without specifying any value for Select . If you are querying an
774
index and only request attributes that are projected into that
775
index, the operation will consult the index and bypass the table.
776
If any of the requested attributes are not projected in to the
777
index, Amazon DynamoDB will need to fetch each matching item from
778
the table. This extra fetching incurs additional throughput cost
782
When neither Select nor AttributesToGet are specified, Amazon DynamoDB
783
defaults to `ALL_ATTRIBUTES` when accessing a table, and
784
`ALL_PROJECTED_ATTRIBUTES` when accessing an index. You cannot use
785
both Select and AttributesToGet together in a single request,
786
unless the value for Select is `SPECIFIC_ATTRIBUTES`. (This usage
787
is equivalent to specifying AttributesToGet without any value for
790
:type attributes_to_get: list
791
:param attributes_to_get: The names of one or more attributes to
792
retrieve. If no attribute names are specified, then all attributes
793
will be returned. If any of the requested attributes are not found,
794
they will not appear in the result.
795
If you are querying an index and only request attributes that are
796
projected into that index, the operation will consult the index and
797
bypass the table. If any of the requested attributes are not
798
projected in to the index, Amazon DynamoDB will need to fetch each
799
matching item from the table. This extra fetching incurs additional
800
throughput cost and latency.
802
You cannot use both AttributesToGet and Select together in a Query
803
request, unless the value for Select is `SPECIFIC_ATTRIBUTES`.
804
(This usage is equivalent to specifying AttributesToGet without any
808
:param limit: The maximum number of items to evaluate (not necessarily
809
the number of matching items). If Amazon DynamoDB processes the
810
number of items up to the limit while processing the results, it
811
stops the operation and returns the matching values up to that
812
point, and a LastEvaluatedKey to apply in a subsequent operation,
813
so that you can pick up where you left off. Also, if the processed
814
data set size exceeds 1 MB before Amazon DynamoDB reaches this
815
limit, it stops the operation and returns the matching values up to
816
the limit, and a LastEvaluatedKey to apply in a subsequent
817
operation to continue the operation. For more information see
818
`Query and Scan`_ of the Amazon DynamoDB Developer Guide .
820
:type consistent_read: boolean
821
:param consistent_read: If set to `True`, then the operation uses
822
strongly consistent reads; otherwise, eventually consistent reads
825
:type key_conditions: map
826
:param key_conditions:
827
The selection criteria for the query.
829
For a query on a table, you can only have conditions on the table
830
primary key attributes. you must specify the hash key attribute
831
name and value as an `EQ` condition. You can optionally specify a
832
second condition, referring to the range key attribute.
834
For a query on a secondary index, you can only have conditions on the
835
index key attributes. You must specify the index hash attribute
836
name and value as an EQ condition. You can optionally specify a
837
second condition, referring to the index key range attribute.
839
Multiple conditions are evaluated using "AND"; in other words, all of
840
the conditions must be met in order for an item to appear in the
843
Each KeyConditions element consists of an attribute name to compare,
844
along with the following:
847
+ AttributeValueList -One or more values to evaluate against the
848
supplied attribute. This list contains exactly one value, except
849
for a `BETWEEN` or `IN` comparison, in which case the list contains
850
two values. String value comparisons for greater than, equals, or
851
less than are based on ASCII character code values. For example,
852
`a` is greater than `A`, and `aa` is greater than `B`. For a list
854
`http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters`_.
855
For Binary, Amazon DynamoDB treats each byte of the binary data as
856
unsigned when it compares binary values, for example when
857
evaluating query expressions.
858
+ ComparisonOperator -A comparator for evaluating attributes. For
859
example, equals, greater than, less than, etc. Valid comparison
860
operators for Query: `EQ | LE | LT | GE | GT | BEGINS_WITH |
861
BETWEEN` For information on specifying data types in JSON, see
862
`JSON Data Format`_ of the Amazon DynamoDB Developer Guide . The
863
following are descriptions of each comparison operator.
865
+ `EQ` : Equal. AttributeValueList can contain only one AttributeValue
866
of type String, Number, or Binary (not a set). If an item contains
867
an AttributeValue of a different type than the one specified in the
868
request, the value does not match. For example, `{"S":"6"}` does
869
not equal `{"N":"6"}`. Also, `{"N":"6"}` does not equal
870
`{"NS":["6", "2", "1"]}`.
871
+ `LE` : Less than or equal. AttributeValueList can contain only one
872
AttributeValue of type String, Number, or Binary (not a set). If an
873
item contains an AttributeValue of a different type than the one
874
specified in the request, the value does not match. For example,
875
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
876
compare to `{"NS":["6", "2", "1"]}`.
877
+ `LT` : Less than. AttributeValueList can contain only one
878
AttributeValue of type String, Number, or Binary (not a set). If an
879
item contains an AttributeValue of a different type than the one
880
specified in the request, the value does not match. For example,
881
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
882
compare to `{"NS":["6", "2", "1"]}`.
883
+ `GE` : Greater than or equal. AttributeValueList can contain only one
884
AttributeValue of type String, Number, or Binary (not a set). If an
885
item contains an AttributeValue of a different type than the one
886
specified in the request, the value does not match. For example,
887
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
888
compare to `{"NS":["6", "2", "1"]}`.
889
+ `GT` : Greater than. AttributeValueList can contain only one
890
AttributeValue of type String, Number, or Binary (not a set). If an
891
item contains an AttributeValue of a different type than the one
892
specified in the request, the value does not match. For example,
893
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
894
compare to `{"NS":["6", "2", "1"]}`. `BEGINS_WITH` : checks for a prefix. AttributeValueList can contain
895
only one AttributeValue of type String or Binary (not a Number or a
896
set). The target attribute of the comparison must be a String or
897
Binary (not a Number or a set).
898
+ `BETWEEN` : Greater than or equal to the first value, and less than
899
or equal to the second value. AttributeValueList must contain two
900
AttributeValue elements of the same type, either String, Number, or
901
Binary (not a set). A target attribute matches if the target value
902
is greater than, or equal to, the first element and less than, or
903
equal to, the second element. If an item contains an AttributeValue
904
of a different type than the one specified in the request, the
905
value does not match. For example, `{"S":"6"}` does not compare to
906
`{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6",
909
:type scan_index_forward: boolean
910
:param scan_index_forward: Specifies ascending (true) or descending
911
(false) traversal of the index. Amazon DynamoDB returns results
912
reflecting the requested order determined by the range key: If the
913
data type is Number, the results are returned in numeric order;
914
otherwise, the results are returned in order of ASCII character
916
If ScanIndexForward is not specified, the results are returned in
919
:type exclusive_start_key: map
920
:param exclusive_start_key: The primary key of the item from which to
921
continue an earlier operation. An earlier operation might provide
922
this value as the LastEvaluatedKey if that operation was
923
interrupted before completion; either because of the result set
924
size or because of the setting for Limit . The LastEvaluatedKey can
925
be passed back in a new request to continue the operation from that
927
The data type for ExclusiveStartKey must be String, Number or Binary.
928
No set data types are allowed.
930
:type return_consumed_capacity: string
931
:param return_consumed_capacity:
934
params = {'TableName': table_name, }
935
if index_name is not None:
936
params['IndexName'] = index_name
937
if select is not None:
938
params['Select'] = select
939
if attributes_to_get is not None:
940
params['AttributesToGet'] = attributes_to_get
941
if limit is not None:
942
params['Limit'] = limit
943
if consistent_read is not None:
944
params['ConsistentRead'] = consistent_read
945
if key_conditions is not None:
946
params['KeyConditions'] = key_conditions
947
if scan_index_forward is not None:
948
params['ScanIndexForward'] = scan_index_forward
949
if exclusive_start_key is not None:
950
params['ExclusiveStartKey'] = exclusive_start_key
951
if return_consumed_capacity is not None:
952
params['ReturnConsumedCapacity'] = return_consumed_capacity
953
return self.make_request(action='Query',
954
body=json.dumps(params))
956
def scan(self, table_name, attributes_to_get=None, limit=None,
957
select=None, scan_filter=None, exclusive_start_key=None,
958
return_consumed_capacity=None):
960
The Scan operation returns one or more items and item
961
attributes by accessing every item in the table. To have
962
Amazon DynamoDB return fewer items, you can provide a
965
If the total number of scanned items exceeds the maximum data
966
set size limit of 1 MB, the scan stops and results are
967
returned to the user with a LastEvaluatedKey to continue the
968
scan in a subsequent operation. The results also include the
969
number of items exceeding the limit. A scan can result in no
970
table data meeting the filter criteria.
972
The result set is eventually consistent.
974
:type table_name: string
975
:param table_name: The name of the table containing the requested
978
:type attributes_to_get: list
979
:param attributes_to_get: The names of one or more attributes to
980
retrieve. If no attribute names are specified, then all attributes
981
will be returned. If any of the requested attributes are not found,
982
they will not appear in the result.
985
:param limit: The maximum number of items to evaluate (not necessarily
986
the number of matching items). If Amazon DynamoDB processes the
987
number of items up to the limit while processing the results, it
988
stops the operation and returns the matching values up to that
989
point, and a LastEvaluatedKey to apply in a subsequent operation,
990
so that you can pick up where you left off. Also, if the processed
991
data set size exceeds 1 MB before Amazon DynamoDB reaches this
992
limit, it stops the operation and returns the matching values up to
993
the limit, and a LastEvaluatedKey to apply in a subsequent
994
operation to continue the operation. For more information see
995
`Query and Scan`_ of the Amazon DynamoDB Developer Guide .
998
:param select: The attributes to be returned in the result. You can
999
retrieve all item attributes, specific item attributes, the count
1000
of matching items, or in the case of an index, some or all of the
1001
attributes projected into the index.
1003
+ `ALL_ATTRIBUTES`: Returns all of the item attributes. For a table,
1004
this is the default. For an index, this mode causes Amazon DynamoDB
1005
to fetch the full item from the table for each matching item in the
1006
index. If the index is configured to project all item attributes,
1007
the matching items will not be fetched from the table. Fetching
1008
items from the table incurs additional throughput cost and latency.
1009
+ `ALL_PROJECTED_ATTRIBUTES`: Retrieves all attributes which have been
1010
projected into the index. If the index is configured to project all
1011
attributes, this is equivalent to specifying ALL_ATTRIBUTES .
1012
+ `COUNT`: Returns the number of matching items, rather than the
1013
matching items themselves.
1014
+ `SPECIFIC_ATTRIBUTES` : Returns only the attributes listed in
1015
AttributesToGet . This is equivalent to specifying AttributesToGet
1016
without specifying any value for Select . If you are querying an
1017
index and only request attributes that are projected into that
1018
index, the operation will consult the index and bypass the table.
1019
If any of the requested attributes are not projected in to the
1020
index, Amazon DynamoDB will need to fetch each matching item from
1021
the table. This extra fetching incurs additional throughput cost
1025
When neither Select nor AttributesToGet are specified, Amazon DynamoDB
1026
defaults to `ALL_ATTRIBUTES` when accessing a table, and
1027
`ALL_PROJECTED_ATTRIBUTES` when accessing an index. You cannot use
1028
both Select and AttributesToGet together in a single request,
1029
unless the value for Select is `SPECIFIC_ATTRIBUTES`. (This usage
1030
is equivalent to specifying AttributesToGet without any value for
1033
:type scan_filter: map
1035
Evaluates the scan results and returns only the desired values.
1036
Multiple conditions are treated as "AND" operations: all conditions
1037
must be met to be included in the results.
1039
Each ScanConditions element consists of an attribute name to compare,
1040
along with the following:
1043
+ AttributeValueList -One or more values to evaluate against the
1044
supplied attribute. This list contains exactly one value, except
1045
for a `BETWEEN` or `IN` comparison, in which case the list contains
1046
two values. String value comparisons for greater than, equals, or
1047
less than are based on ASCII character code values. For example,
1048
`a` is greater than `A`, and `aa` is greater than `B`. For a list
1050
`http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters`_.
1051
For Binary, Amazon DynamoDB treats each byte of the binary data as
1052
unsigned when it compares binary values, for example when
1053
evaluating query expressions.
1054
+ ComparisonOperator -A comparator for evaluating attributes. For
1055
example, equals, greater than, less than, etc. Valid comparison
1056
operators for Scan: `EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL
1057
| CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN` For
1058
information on specifying data types in JSON, see `JSON Data
1059
Format`_ of the Amazon DynamoDB Developer Guide . The following are
1060
descriptions of each comparison operator.
1062
+ `EQ` : Equal. AttributeValueList can contain only one AttributeValue
1063
of type String, Number, or Binary (not a set). If an item contains
1064
an AttributeValue of a different type than the one specified in the
1065
request, the value does not match. For example, `{"S":"6"}` does
1066
not equal `{"N":"6"}`. Also, `{"N":"6"}` does not equal
1067
`{"NS":["6", "2", "1"]}`.
1068
+ `NE` : Not equal. AttributeValueList can contain only one
1069
AttributeValue of type String, Number, or Binary (not a set). If an
1070
item contains an AttributeValue of a different type than the one
1071
specified in the request, the value does not match. For example,
1072
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
1073
equal `{"NS":["6", "2", "1"]}`.
1074
+ `LE` : Less than or equal. AttributeValueList can contain only one
1075
AttributeValue of type String, Number, or Binary (not a set). If an
1076
item contains an AttributeValue of a different type than the one
1077
specified in the request, the value does not match. For example,
1078
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
1079
compare to `{"NS":["6", "2", "1"]}`.
1080
+ `LT` : Less than. AttributeValueList can contain only one
1081
AttributeValue of type String, Number, or Binary (not a set). If an
1082
item contains an AttributeValue of a different type than the one
1083
specified in the request, the value does not match. For example,
1084
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
1085
compare to `{"NS":["6", "2", "1"]}`.
1086
+ `GE` : Greater than or equal. AttributeValueList can contain only one
1087
AttributeValue of type String, Number, or Binary (not a set). If an
1088
item contains an AttributeValue of a different type than the one
1089
specified in the request, the value does not match. For example,
1090
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
1091
compare to `{"NS":["6", "2", "1"]}`.
1092
+ `GT` : Greater than. AttributeValueList can contain only one
1093
AttributeValue of type String, Number, or Binary (not a set). If an
1094
item contains an AttributeValue of a different type than the one
1095
specified in the request, the value does not match. For example,
1096
`{"S":"6"}` does not equal `{"N":"6"}`. Also, `{"N":"6"}` does not
1097
compare to `{"NS":["6", "2", "1"]}`.
1098
+ `NOT_NULL` : The attribute exists.
1099
+ `NULL` : The attribute does not exist.
1100
+ `CONTAINS` : checks for a subsequence, or value in a set.
1101
AttributeValueList can contain only one AttributeValue of type
1102
String, Number, or Binary (not a set). If the target attribute of
1103
the comparison is a String, then the operation checks for a
1104
substring match. If the target attribute of the comparison is
1105
Binary, then the operation looks for a subsequence of the target
1106
that matches the input. If the target attribute of the comparison
1107
is a set ("SS", "NS", or "BS"), then the operation checks for a
1108
member of the set (not as a substring).
1109
+ `NOT_CONTAINS` : checks for absence of a subsequence, or absence of a
1110
value in a set. AttributeValueList can contain only one
1111
AttributeValue of type String, Number, or Binary (not a set). If
1112
the target attribute of the comparison is a String, then the
1113
operation checks for the absence of a substring match. If the
1114
target attribute of the comparison is Binary, then the operation
1115
checks for the absence of a subsequence of the target that matches
1116
the input. If the target attribute of the comparison is a set
1117
("SS", "NS", or "BS"), then the operation checks for the absence of
1118
a member of the set (not as a substring).
1119
+ `BEGINS_WITH` : checks for a prefix. AttributeValueList can contain
1120
only one AttributeValue of type String or Binary (not a Number or a
1121
set). The target attribute of the comparison must be a String or
1122
Binary (not a Number or a set).
1123
+ `IN` : checks for exact matches. AttributeValueList can contain more
1124
than one AttributeValue of type String, Number, or Binary (not a
1125
set). The target attribute of the comparison must be of the same
1126
type and exact value to match. A String never matches a String set.
1127
+ `BETWEEN` : Greater than or equal to the first value, and less than
1128
or equal to the second value. AttributeValueList must contain two
1129
AttributeValue elements of the same type, either String, Number, or
1130
Binary (not a set). A target attribute matches if the target value
1131
is greater than, or equal to, the first element and less than, or
1132
equal to, the second element. If an item contains an AttributeValue
1133
of a different type than the one specified in the request, the
1134
value does not match. For example, `{"S":"6"}` does not compare to
1135
`{"N":"6"}`. Also, `{"N":"6"}` does not compare to `{"NS":["6",
1138
:type exclusive_start_key: map
1139
:param exclusive_start_key: The primary key of the item from which to
1140
continue an earlier operation. An earlier operation might provide
1141
this value as the LastEvaluatedKey if that operation was
1142
interrupted before completion; either because of the result set
1143
size or because of the setting for Limit . The LastEvaluatedKey can
1144
be passed back in a new request to continue the operation from that
1146
The data type for ExclusiveStartKey must be String, Number or Binary.
1147
No set data types are allowed.
1149
:type return_consumed_capacity: string
1150
:param return_consumed_capacity:
1153
params = {'TableName': table_name, }
1154
if attributes_to_get is not None:
1155
params['AttributesToGet'] = attributes_to_get
1156
if limit is not None:
1157
params['Limit'] = limit
1158
if select is not None:
1159
params['Select'] = select
1160
if scan_filter is not None:
1161
params['ScanFilter'] = scan_filter
1162
if exclusive_start_key is not None:
1163
params['ExclusiveStartKey'] = exclusive_start_key
1164
if return_consumed_capacity is not None:
1165
params['ReturnConsumedCapacity'] = return_consumed_capacity
1166
return self.make_request(action='Scan',
1167
body=json.dumps(params))
1169
def update_item(self, table_name, key, attribute_updates=None,
1170
expected=None, return_values=None,
1171
return_consumed_capacity=None,
1172
return_item_collection_metrics=None):
1174
Edits an existing item's attributes, or inserts a new item if
1175
it does not already exist. You can put, delete, or add
1176
attribute values. You can also perform a conditional update
1177
(insert a new attribute name-value pair if it doesn't exist,
1178
or replace an existing name-value pair if it has certain
1179
expected attribute values).
1181
In addition to updating an item, you can also return the
1182
item's attribute values in the same operation, using the
1183
ReturnValues parameter.
1185
:type table_name: string
1186
:param table_name: The name of the table containing the item to update.
1189
:param key: The primary key that defines the item. Each element
1190
consists of an attribute name and a value for that attribute.
1192
:type attribute_updates: map
1193
:param attribute_updates: The names of attributes to be modified, the
1194
action to perform on each, and the new value for each. If you are
1195
updating an attribute that is an index key attribute for any
1196
indexes on that table, the attribute type must match the index key
1197
type defined in the AttributesDefinition of the table description.
1198
You can use UpdateItem to update any non-key attributes.
1199
Attribute values cannot be null; string and binary type attributes must
1200
have lengths greater than zero; and set type attributes must not be
1201
empty. Requests with empty values will be rejected with a
1202
ValidationException .
1204
Each AttributeUpdates element consists of an attribute name to modify,
1205
along with the following:
1208
+ Value -the new value, if applicable, for this attribute.
1209
+ Action -specifies how to perform the update. Valid values for Action
1210
are `PUT`, `DELETE`, and `ADD`. The behavior depends on whether the
1211
specified primary key already exists in the table. **If an item
1212
with the specified Key is found in the table:**
1214
+ `PUT`-Adds the specified attribute to the item. If the attribute
1215
already exists, it is replaced by the new value.
1216
+ `DELETE`-If no value is specified, the attribute and its value are
1217
removed from the item. The data type of the specified value must
1218
match the existing value's data type. If a set of values is
1219
specified, then those values are subtracted from the old set. For
1220
example, if the attribute value was the set `[a,b,c]` and the
1221
DELETE action specified `[a,c]`, then the final attribute value
1222
would be `[b]`. Specifying an empty set is an error.
1223
+ `ADD`-If the attribute does not already exist, then the attribute and
1224
its values are added to the item. If the attribute does exist, then
1225
the behavior of `ADD` depends on the data type of the attribute:
1227
+ If the existing attribute is a number, and if Value is also a number,
1228
then the Value is mathematically added to the existing attribute.
1229
If Value is a negative number, then it is subtracted from the
1230
existing attribute. If you use `ADD` to increment or decrement a
1231
number value for an item that doesn't exist before the update,
1232
Amazon DynamoDB uses 0 as the initial value. In addition, if you
1233
use `ADD` to update an existing item, and intend to increment or
1234
decrement an attribute value which does not yet exist, Amazon
1235
DynamoDB uses `0` as the initial value. For example, suppose that
1236
the item you want to update does not yet have an attribute named
1237
itemcount , but you decide to `ADD` the number `3` to this
1238
attribute anyway, even though it currently does not exist. Amazon
1239
DynamoDB will create the itemcount attribute, set its initial value
1240
to `0`, and finally add `3` to it. The result will be a new
1241
itemcount attribute in the item, with a value of `3`.
1242
+ If the existing data type is a set, and if the Value is also a set,
1243
then the Value is added to the existing set. (This is a set
1244
operation, not mathematical addition.) For example, if the
1245
attribute value was the set `[1,2]`, and the `ADD` action specified
1246
`[3]`, then the final attribute value would be `[1,2,3]`. An error
1247
occurs if an Add action is specified for a set attribute and the
1248
attribute type specified does not match the existing set type. Both
1249
sets must have the same primitive data type. For example, if the
1250
existing data type is a set of strings, the Value must also be a
1251
set of strings. The same holds true for number sets and binary
1253
This action is only valid for an existing attribute whose data type is
1254
number or is a set. Do not use `ADD` for any other data types.
1255
**If no item with the specified Key is found:**
1257
+ `PUT`-Amazon DynamoDB creates a new item with the specified primary
1258
key, and then adds the attribute.
1259
+ `DELETE`-Nothing happens; there is no attribute to delete.
1260
+ `ADD`-Amazon DynamoDB creates an item with the supplied primary key
1261
and number (or set of numbers) for the attribute value. The only
1262
data types allowed are number and number set; no other data types
1267
If you specify any attributes that are part of an index key, then the
1268
data types for those attributes must match those of the schema in
1269
the table's attribute definition.
1272
:param expected: A map of attribute/condition pairs. This is the
1273
conditional block for the UpdateItem operation. All the conditions
1274
must be met for the operation to succeed.
1275
Expected allows you to provide an attribute name, and whether or not
1276
Amazon DynamoDB should check to see if the attribute value already
1277
exists; or if the attribute value exists and has a particular value
1280
Each item in Expected represents an attribute name for Amazon DynamoDB
1281
to check, along with the following:
1284
+ Value -the attribute value for Amazon DynamoDB to check.
1285
+ Exists -causes Amazon DynamoDB to evaluate the value before
1286
attempting a conditional operation:
1288
+ If Exists is `True`, Amazon DynamoDB will check to see if that
1289
attribute value already exists in the table. If it is found, then
1290
the operation succeeds. If it is not found, the operation fails
1291
with a ConditionalCheckFailedException .
1292
+ If Exists is `False`, Amazon DynamoDB assumes that the attribute
1293
value does not exist in the table. If in fact the value does not
1294
exist, then the assumption is valid and the operation succeeds. If
1295
the value is found, despite the assumption that it does not exist,
1296
the operation fails with a ConditionalCheckFailedException .
1297
The default setting for Exists is `True`. If you supply a Value all by
1298
itself, Amazon DynamoDB assumes the attribute exists: You don't
1299
have to set Exists to `True`, because it is implied. Amazon
1300
DynamoDB returns a ValidationException if:
1302
+ Exists is `True` but there is no Value to check. (You expect a value
1303
to exist, but don't specify what that value is.)
1304
+ Exists is `False` but you also specify a Value . (You cannot expect
1305
an attribute to have a value, while also expecting it not to
1310
If you specify more than one condition for Exists , then all of the
1311
conditions must evaluate to true. (In other words, the conditions
1312
are ANDed together.) Otherwise, the conditional operation will
1315
:type return_values: string
1316
:param return_values:
1317
Use ReturnValues if you want to get the item attributes as they
1318
appeared either before or after they were updated. For UpdateItem ,
1319
the valid values are:
1322
+ `NONE`-(default) If ReturnValues is not specified, or if its value is
1323
`NONE`, then nothing is returned.
1324
+ `ALL_OLD`-If UpdateItem overwrote an attribute name-value pair, then
1325
the content of the old item is returned.
1326
+ `UPDATED_OLD`-The old versions of only the updated attributes are
1328
+ `ALL_NEW`-All of the attributes of the new version of the item are
1330
+ `UPDATED_NEW`-The new versions of only the updated attributes are
1333
:type return_consumed_capacity: string
1334
:param return_consumed_capacity:
1336
:type return_item_collection_metrics: string
1337
:param return_item_collection_metrics: Indicates whether to return
1338
statistics about item collections, if any, that were modified
1339
during the operation. The default for ReturnItemCollectionMetrics
1340
is `NONE`, meaning that no statistics will be returned. To obtain
1341
the statistics, set ReturnItemCollectionMetrics to `SIZE`.
1344
params = {'TableName': table_name, 'Key': key, }
1345
if attribute_updates is not None:
1346
params['AttributeUpdates'] = attribute_updates
1347
if expected is not None:
1348
params['Expected'] = expected
1349
if return_values is not None:
1350
params['ReturnValues'] = return_values
1351
if return_consumed_capacity is not None:
1352
params['ReturnConsumedCapacity'] = return_consumed_capacity
1353
if return_item_collection_metrics is not None:
1354
params['ReturnItemCollectionMetrics'] = return_item_collection_metrics
1355
return self.make_request(action='UpdateItem',
1356
body=json.dumps(params))
1358
def update_table(self, table_name, provisioned_throughput):
1360
Updates the provisioned throughput for the given table.
1361
Setting the throughput for a table helps you manage
1362
performance and is part of the provisioned throughput feature
1365
The provisioned throughput values can be upgraded or
1366
downgraded based on the maximums and minimums listed in the
1367
`Limits`_ section of the Amazon DynamoDB Developer Guide .
1369
The table must be in the `ACTIVE` state for this operation to
1370
succeed. UpdateTable is an asynchronous operation; while
1371
executing the operation, the table is in the `UPDATING` state.
1372
While the table is in the `UPDATING` state, the table still
1373
has the provisioned throughput from before the call. The new
1374
provisioned throughput setting is in effect only when the
1375
table returns to the `ACTIVE` state after the UpdateTable
1378
:type table_name: string
1379
:param table_name: The name of the table to be updated.
1381
:type provisioned_throughput: dict
1382
:param provisioned_throughput:
1386
'TableName': table_name,
1387
'ProvisionedThroughput': provisioned_throughput,
1389
return self.make_request(action='UpdateTable',
1390
body=json.dumps(params))
1392
def make_request(self, action, body):
1394
'X-Amz-Target': '%s.%s' % (self.TargetPrefix, action),
1395
'Host': self.region.endpoint,
1396
'Content-Type': 'application/x-amz-json-1.0',
1397
'Content-Length': str(len(body)),
1399
http_request = self.build_base_http_request(
1400
method='POST', path='/', auth_path='/', params={},
1401
headers=headers, data=body)
1402
response = self._mexe(http_request, sender=None,
1403
override_num_retries=self.NumberRetries,
1404
retry_handler=self._retry_handler)
1405
response_body = response.read()
1406
boto.log.debug(response_body)
1407
if response.status == 200:
1409
return json.loads(response_body)
1411
json_body = json.loads(response_body)
1412
fault_name = json_body.get('__type', None)
1413
exception_class = self._faults.get(fault_name, self.ResponseError)
1414
raise exception_class(response.status, response.reason,
1417
def _retry_handler(self, response, i, next_sleep):
1419
if response.status == 400:
1420
response_body = response.read()
1421
boto.log.debug(response_body)
1422
data = json.loads(response_body)
1423
if 'ProvisionedThroughputExceededException' in data.get('__type'):
1424
self.throughput_exceeded_events += 1
1425
msg = "%s, retry attempt %s" % (
1426
'ProvisionedThroughputExceededException',
1429
next_sleep = self._exponential_time(i)
1431
status = (msg, i, next_sleep)
1432
if i == self.NumberRetries:
1433
# If this was our last retry attempt, raise
1434
# a specific error saying that the throughput
1436
raise exceptions.ProvisionedThroughputExceededException(
1437
response.status, response.reason, data)
1438
elif 'ConditionalCheckFailedException' in data.get('__type'):
1439
raise exceptions.ConditionalCheckFailedException(
1440
response.status, response.reason, data)
1441
elif 'ValidationException' in data.get('__type'):
1442
raise exceptions.ValidationException(
1443
response.status, response.reason, data)
1445
raise self.ResponseError(response.status, response.reason,
1447
expected_crc32 = response.getheader('x-amz-crc32')
1448
if self._validate_checksums and expected_crc32 is not None:
1449
boto.log.debug('Validating crc32 checksum for body: %s',
1451
actual_crc32 = crc32(response.read()) & 0xffffffff
1452
expected_crc32 = int(expected_crc32)
1453
if actual_crc32 != expected_crc32:
1454
msg = ("The calculated checksum %s did not match the expected "
1455
"checksum %s" % (actual_crc32, expected_crc32))
1456
status = (msg, i + 1, self._exponential_time(i))
1459
def _exponential_time(self, i):
1463
next_sleep = 0.05 * (2 ** i)