o ckF[@sddlZddlmZddlmZmZmZmZmZm Z m Z m Z ddl m Z ddlmZddlmZmZddlmZmZmZmZmZddlmZGd d d eZGd d d eZdS) N) exceptions)HashKeyRangeKeyAllIndex KeysOnlyIndex IncludeIndexGlobalAllIndexGlobalKeysOnlyIndexGlobalIncludeIndex)Item)DynamoDBConnection) ResultSetBatchGetResultSet)NonBooleanDynamizer DynamizerFILTER_OPERATORSQUERY_OPERATORSSTRING)JSONResponseErrorc@seZdZdZdZeeeeedee e e ddZ  dLddZ dd Ze  dMd d ZdNd d ZddZddZddZddZdOddZddZddZddZddZd d!ZdPd#d$Zd%d&Zd'd(Zd)d*ZdQd+d,Z dNd-d.Z!dNd/d0Z"dOd1d2Z#d3d4Z$d5d6Z%e&fd7d8Z' " dRd9d:Z( "  dSd;d<Z)   dTd>d?Z* "  dUd@dAZ+  dVdBdCZ,  dVdDdEZ-dPdFdGZ.dPdHdIZ/dJdKZ0dS)WTablea Interacts & models the behavior of a DynamoDB table. The ``Table`` object represents a set (or rough categorization) of records within DynamoDB. The important part is that all records within the table, while largely-schema-free, share the same schema & are essentially namespaced for use in your application. For example, you might have a ``users`` table or a ``forums`` table. d)ALL KEYS_ONLYINCLUDE)global_indexes local_indexesNcCsV||_||_ddd|_||_||_||_|jdurt|_|dur%||_t|_dS)a Sets up a new in-memory ``Table``. This is useful if the table already exists within DynamoDB & you simply want to use it for additional interactions. The only required parameter is the ``table_name``. However, under the hood, the object will call ``describe_table`` to determine the schema/indexes/throughput. You can avoid this extra call by passing in ``schema`` & ``indexes``. **IMPORTANT** - If you're creating a new ``Table`` for the first time, you should use the ``Table.create`` method instead, as it will persist the table structure to DynamoDB. Requires a ``table_name`` parameter, which should be a simple string of the name of the table. Optionally accepts a ``schema`` parameter, which should be a list of ``BaseSchemaField`` subclasses representing the desired schema. Optionally accepts a ``throughput`` parameter, which should be a dictionary. If provided, it should specify a ``read`` & ``write`` key, both of which should have an integer value associated with them. Optionally accepts a ``indexes`` parameter, which should be a list of ``BaseIndexField`` subclasses representing the desired indexes. Optionally accepts a ``global_indexes`` parameter, which should be a list of ``GlobalBaseIndexField`` subclasses representing the desired indexes. Optionally accepts a ``connection`` parameter, which should be a ``DynamoDBConnection`` instance (or subclass). This is primarily useful for specifying alternate connection parameters. Example:: # The simple, it-already-exists case. >>> conn = Table('users') # The full, minimum-extra-calls case. >>> from boto import dynamodb2 >>> users = Table('users', schema=[ ... HashKey('username'), ... RangeKey('date_joined', data_type=NUMBER) ... ], throughput={ ... 'read':20, ... 'write': 10, ... }, indexes=[ ... KeysOnlyIndex('MostRecentlyJoined', parts=[ ... HashKey('username') ... RangeKey('date_joined') ... ]), ... ], global_indexes=[ ... GlobalAllIndex('UsersByZipcode', parts=[ ... HashKey('zipcode'), ... RangeKey('username'), ... ], ... throughput={ ... 'read':10, ... 'write':10, ... }), ... ], connection=dynamodb2.connect_to_region('us-west-2', ... aws_access_key_id='key', ... aws_secret_access_key='key', ... )) )readwriteN) table_name connection throughputschemaindexesrr r _dynamizer)selfrr"r!r#rr r&6/usr/lib/python3/dist-packages/boto/dynamodb2/table.py__init__'sE  zTable.__init__cCs t|_dSN)rr$r%r&r&r' use_boolean~s zTable.use_booleancCs<|||d}||_|dur||_|dur||_|dur||_g}g} t} |jD]} || | | j| | q(t |jdt |jdd} i} ddd}dD]5}t ||}|rg}|D]!}|||j D]} | j| vr| | j| | qpqd|| ||<qW|j j d |j| || d | |S) a Creates a new table in DynamoDB & returns an in-memory ``Table`` object. This will setup a brand new table within DynamoDB. The ``table_name`` must be unique for your AWS account. The ``schema`` is also required to define the key structure of the table. **IMPORTANT** - You should consider the usage pattern of your table up-front, as the schema can **NOT** be modified once the table is created, requiring the creation of a new table & migrating the data should you wish to revise it. **IMPORTANT** - If the table already exists in DynamoDB, additional calls to this method will result in an error. If you just need a ``Table`` object to interact with the existing table, you should just initialize a new ``Table`` object, which requires only the ``table_name``. Requires a ``table_name`` parameter, which should be a simple string of the name of the table. Requires a ``schema`` parameter, which should be a list of ``BaseSchemaField`` subclasses representing the desired schema. Optionally accepts a ``throughput`` parameter, which should be a dictionary. If provided, it should specify a ``read`` & ``write`` key, both of which should have an integer value associated with them. Optionally accepts a ``indexes`` parameter, which should be a list of ``BaseIndexField`` subclasses representing the desired indexes. Optionally accepts a ``global_indexes`` parameter, which should be a list of ``GlobalBaseIndexField`` subclasses representing the desired indexes. Optionally accepts a ``connection`` parameter, which should be a ``DynamoDBConnection`` instance (or subclass). This is primarily useful for specifying alternate connection parameters. Example:: >>> users = Table.create('users', schema=[ ... HashKey('username'), ... RangeKey('date_joined', data_type=NUMBER) ... ], throughput={ ... 'read':20, ... 'write': 10, ... }, indexes=[ ... KeysOnlyIndex('MostRecentlyJoined', parts=[ ... HashKey('username'), ... RangeKey('date_joined'), ... ]), global_indexes=[ ... GlobalAllIndex('UsersByZipcode', parts=[ ... HashKey('zipcode'), ... RangeKey('username'), ... ], ... throughput={ ... 'read':10, ... 'write':10, ... }), ... ]) )rr NrrReadCapacityUnitsWriteCapacityUnitslocal_secondary_indexesglobal_secondary_indexes)r#r)rattribute_definitions key_schemaprovisioned_throughputr&)r"r!r#rsetappendaddname definitionintgetattrpartsr create_tabler)clsrr"r!r#rr table raw_schema attr_defs seen_attrsfieldraw_throughputkwargs kwarg_map index_attr table_indexes raw_indexes index_fieldr&r&r'createsZ B         z Table.createcCsg}i}|r|D] }|d||d<q|D]6}||dt}|ddkr1|t|d|dq|ddkrC|t|d|dqtd|d|S)z Given a raw schema structure back from a DynamoDB response, parse out & build the high-level Python objects that represent them. AttributeType AttributeNameKeyTypeHASH) data_typeRANGEW%s was seen, but is unknown. Please report this at https://github.com/boto/boto/issues.)getrr5rrrUnknownSchemaFieldError)r%r?raw_attributesr"sane_attributesrBrOr&r&r'_introspect_schemas*  zTable._introspect_schemacCsg}|D]a}|d}dgi}|dddkr|d}n/|dddkr+|d}n!|dddkrA|d}|dd|d<n td |dd|d }||d d |d<|||fi|q|S) z Given a raw index/global index structure back from a DynamoDB response, parse out & build the high-level Python objects that represent them. rr; ProjectionProjectionTyperrNonKeyAttributesincludesrQ IndexName KeySchemaN)rRrUnknownIndexFieldErrorrVr5)r%rHmap_indexes_projectionr#rB index_klassrDr7r&r&r'_introspect_all_indexess*     zTable._introspect_all_indexescC|||jdS)z Given a raw index structure back from a DynamoDB response, parse out & build the high-level Python objects that represent them. rr`_PROJECTION_TYPE_TO_INDEXrR)r%rHr&r&r'_introspect_indexes<s zTable._introspect_indexescCra)z Given a raw global index structure back from a DynamoDB response, parse out & build the high-level Python objects that represent them. rrb)r%raw_global_indexesr&r&r'_introspect_global_indexesDs z Table._introspect_global_indexescCs|j|j}|dd}t|d|jd<t|d|jd<|js9|ddg}|ddg}||||_|jsJ|dd g}| ||_|dd g}| ||_ |S) a Describes the current structure of the table in DynamoDB. This information will be used to update the ``schema``, ``indexes``, ``global_indexes`` and ``throughput`` information on the ``Table``. Some calls, such as those involving creating keys or querying, will require this information to be populated. It also returns the full raw data structure from DynamoDB, in the event you'd like to parse out additional information (such as the ``ItemCount`` or usage information). Example:: >>> users.describe() { # Lots of keys here... } >>> len(users.schema) 2 rProvisionedThroughputr-rr.rr\AttributeDefinitionsLocalSecondaryIndexesGlobalSecondaryIndexes) r describe_tablerr9r!r"rRrVr#rdrfr)r%resultrCr?rTrHrer&r&r'describeMs   zTable.describec Csd}|r||_t|jdt|jdd}d}|r:g}|D]\}}|d|t|dt|dddiq |s>|rJ|jj|j||ddSd }tj |d S) a0 Updates table attributes and global indexes in DynamoDB. Optionally accepts a ``throughput`` parameter, which should be a dictionary. If provided, it should specify a ``read`` & ``write`` key, both of which should have an integer value associated with them. Optionally accepts a ``global_indexes`` parameter, which should be a dictionary. If provided, it should specify the index name, which is also a dict containing a ``read`` & ``write`` key, both of which should have an integer value associated with them. If you are writing new code, please use ``Table.update_global_secondary_index``. Returns ``True`` on success. Example:: # For a read-heavier application... >>> users.update(throughput={ ... 'read': 20, ... 'write': 10, ... }) True # To also update the global index(es) throughput. >>> users.update(throughput={ ... 'read': 20, ... 'write': 10, ... }, ... global_secondary_indexes={ ... 'TheIndexNameHere': { ... 'read': 15, ... 'write': 5, ... } ... }) True Nrrr,Updater[rg)r3global_secondary_index_updatesTzPYou need to provide either the throughput or the global_indexes to update methodF) r!r9itemsr5r update_tablerbotologerror)r%r!rdatagsi_datagsi_namegsi_throughputmsgr&r&r'update~s8'      z Table.updatecCsd|r(g}g}|d|i|jD] }||q|jj|j||ddSd}tj |dS)a Creates a global index in DynamoDB after the table has been created. Requires a ``global_indexes`` parameter, which should be a ``GlobalBaseIndexField`` subclass representing the desired index. To update ``global_indexes`` information on the ``Table``, you'll need to call ``Table.describe``. Returns ``True`` on success. Example:: # To create a global index >>> users.create_global_secondary_index( ... global_index=GlobalAllIndex( ... 'TheIndexNameHere', parts=[ ... HashKey('requiredHashkey', data_type=STRING), ... RangeKey('optionalRangeKey', data_type=STRING) ... ], ... throughput={ ... 'read': 2, ... 'write': 1, ... }) ... ) True Create)rpr1TzLYou need to provide the global_index to create_global_secondary_index methodF) r5r"r;r8r rrrrsrtru)r% global_indexrwgsi_data_attr_defattr_defrzr&r&r'create_global_secondary_indexs"  z#Table.create_global_secondary_indexcCs<|rdd|iig}|jj|j|ddSd}tj|dS)a  Deletes a global index in DynamoDB after the table has been created. Requires a ``global_index_name`` parameter, which should be a simple string of the name of the global secondary index. To update ``global_indexes`` information on the ``Table``, you'll need to call ``Table.describe``. Returns ``True`` on success. Example:: # To delete a global index >>> users.delete_global_secondary_index('TheIndexNameHere') True Deleter[rpTzQYou need to provide the global index name to delete_global_secondary_index methodF)r rrrrsrtru)r%global_index_namerwrzr&r&r'delete_global_secondary_indexs z#Table.delete_global_secondary_indexc Csn|r-g}|D]\}}|d|t|dt|dddiq|jj|j|ddSd}tj|d S) a5 Updates a global index(es) in DynamoDB after the table has been created. Requires a ``global_indexes`` parameter, which should be a dictionary. If provided, it should specify the index name, which is also a dict containing a ``read`` & ``write`` key, both of which should have an integer value associated with them. To update ``global_indexes`` information on the ``Table``, you'll need to call ``Table.describe``. Returns ``True`` on success. Example:: # To update a global index >>> users.update_global_secondary_index(global_indexes={ ... 'TheIndexNameHere': { ... 'read': 15, ... 'write': 5, ... } ... }) True rnrrr,rorTzNYou need to provide the global indexes to update_global_secondary_index methodF) rqr5r9r rrrrsrtru)r%rrwrxryrzr&r&r'update_global_secondary_index.s&    z#Table.update_global_secondary_indexcCs|j|jdS)z Deletes a table in DynamoDB. **IMPORTANT** - Be careful when using this method, there is no undo. Returns ``True`` on success. Example:: >>> users.delete() True T)r delete_tablerr*r&r&r'deletecsz Table.deletecCs*i}|D] \}}|j|||<q|S)a Given a flat Python dictionary of keys/values, converts it into the nested dictionary DynamoDB expects. Converts:: { 'username': 'john', 'tags': [1, 2, 5], } ...to...:: { 'username': {'S': 'john'}, 'tags': {'NS': ['1', '2', '5']}, } )rqr$encode)r%keysraw_keykeyvaluer&r&r' _encode_keystszTable._encode_keysFcKsL||}|jj|j|||d}d|vrtd|t|}|||S)a/ Fetches an item (record) from a table in DynamoDB. To specify the key of the item you'd like to get, you can specify the key attributes as kwargs. Optionally accepts a ``consistent`` parameter, which should be a boolean. If you provide ``True``, it will perform a consistent (but more expensive) read from DynamoDB. (Default: ``False``) Optionally accepts an ``attributes`` parameter, which should be a list of fieldname to fetch. (Default: ``None``, which means all fields should be fetched) Returns an ``Item`` instance containing all the data for that record. Raises an ``ItemNotFound`` exception if the item is not found. Example:: # A simple hash key. >>> john = users.get_item(username='johndoe') >>> john['first_name'] 'John' # A complex hash+range key. >>> john = users.get_item(username='johndoe', last_name='Doe') >>> john['first_name'] 'John' # A consistent read (assuming the data might have just changed). >>> john = users.get_item(username='johndoe', consistent=True) >>> john['first_name'] 'Johann' # With a key that is an invalid variable name in Python. # Also, assumes a different schema than previous examples. >>> john = users.get_item(**{ ... 'date-joined': 127549192, ... }) >>> john['first_name'] 'John' )attributes_to_getconsistent_readr zItem %s couldn't be found.)rr get_itemrr ItemNotFoundr load)r% consistent attributesrDr item_dataitemr&r&r'rs . zTable.get_itemc Ks2z |jdi|WdSttjfyYdSw)a Return whether an item (record) exists within a table in DynamoDB. To specify the key of the item you'd like to get, you can specify the key attributes as kwargs. Optionally accepts a ``consistent`` parameter, which should be a boolean. If you provide ``True``, it will perform a consistent (but more expensive) read from DynamoDB. (Default: ``False``) Optionally accepts an ``attributes`` parameter, which should be a list of fieldnames to fetch. (Default: ``None``, which means all fields should be fetched) Returns ``True`` if an ``Item`` is present, ``False`` if not. Example:: # Simple, just hash-key schema. >>> users.has_item(username='johndoe') True # Complex schema, item not present. >>> users.has_item( ... username='johndoe', ... date_joined='2014-01-07' ... ) False FTNr&)rrrrr%rDr&r&r'has_items  zTable.has_itemcOsP|js|t|D] \}}|||j|j<q |jdi|}|s&dS|S)ai Look up an entry in DynamoDB. This is mostly backwards compatible with boto.dynamodb. Unlike get_item, it takes hash_key and range_key first, although you may still specify keyword arguments instead. Also unlike the get_item command, if the returned item has no keys (i.e., it does not exist in DynamoDB), a None result is returned, instead of an empty key object. Example:: >>> user = users.lookup(username) >>> user = users.lookup(username, consistent=True) >>> app = apps.lookup('my_customer_id', 'my_app_id') Nr&)r"rm enumerater7rr)r%argsrDxargretr&r&r'lookupsz Table.lookupcGs@|js|i}t|D] \}}|||j|j<q t||dS)zf Returns a new, blank item This is mostly for consistency with boto.dynamodb rv)r"rmrr7r )r%rrvrrr&r&r'new_item s  zTable.new_itemcCst||d}|j|dS)a  Saves an entire item to DynamoDB. By default, if any part of the ``Item``'s original data doesn't match what's currently in DynamoDB, this request will fail. This prevents other processes from updating the data in between when you read the item & when your request to update the item's data is processed, which would typically result in some data loss. Requires a ``data`` parameter, which should be a dictionary of the data you'd like to store in DynamoDB. Optionally accepts an ``overwrite`` parameter, which should be a boolean. If you provide ``True``, this will tell DynamoDB to blindly overwrite whatever data is present, if any. Returns ``True`` on success. Example:: >>> users.put_item(data={ ... 'username': 'jane', ... 'first_name': 'Jane', ... 'last_name': 'Doe', ... 'date_joined': 126478915, ... }) True r) overwrite)r save)r%rvrrr&r&r'put_items  zTable.put_itemcCs0i}|dur ||d<|jj|j|fi|dS)a The internal variant of ``put_item`` (full data). This is used by the ``Item`` objects, since that operation is represented at the table-level by the API, but conceptually maps better to telling an individual ``Item`` to save itself. NexpectedT)r rr)r%rexpectsrDr&r&r' _put_item8s zTable._put_itemcCs<||}i}|dur||d<|jj|j||fi|dS)a The internal variant of ``put_item`` (partial data). This is used by the ``Item`` objects, since that operation is represented at the table-level by the API, but conceptually maps better to telling an individual ``Item`` to save itself. NrT)rr update_itemr)r%rrrrrDr&r&r' _update_itemGs zTable._update_itemcKsL|j|td}||}z|jj|j|||dWdStjy%YdSw)a Deletes a single item. You can perform a conditional delete operation that deletes the item if it exists, or if it has an expected attribute value. Conditional deletes are useful for only deleting items if specific conditions are met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item is not deleted. To specify the expected attribute values of the item, you can pass a dictionary of conditions to ``expected``. Each condition should follow the pattern ``__=``. **IMPORTANT** - Be careful when using this method, there is no undo. To specify the key of the item you'd like to get, you can specify the key attributes as kwargs. Optionally accepts an ``expected`` parameter which is a dictionary of expected attribute value conditions. Optionally accepts a ``conditional_operator`` which applies to the expected attribute value conditions: + `AND` - If all of the conditions evaluate to true (default) + `OR` - True if at least one condition evaluates to true Returns ``True`` on success, ``False`` on failed conditional delete. Example:: # A simple hash key. >>> users.delete_item(username='johndoe') True # A complex hash+range key. >>> users.delete_item(username='jane', last_name='Doe') True # With a key that is an invalid variable name in Python. # Also, assumes a different schema than previous examples. >>> users.delete_item(**{ ... 'date-joined': 127549192, ... }) True # Conditional delete >>> users.delete_item(username='johndoe', ... expected={'balance__eq': 0}) True using)rconditional_operatorFT)_build_filtersrrr delete_itemrrConditionalCheckFailedException)r%rrrDrr&r&r'rWs4  zTable.delete_itemcCs|js|dd|jDS)a Returns the fields necessary to make a key for a table. If the ``Table`` does not already have a populated ``schema``, this will request it via a ``Table.describe`` call. Returns a list of fieldnames (strings). Example:: # A simple hash key. >>> users.get_key_fields() ['username'] # A complex hash+range key. >>> users.get_key_fields() ['username', 'last_name'] cSsg|]}|jqSr&)r7).0rBr&r&r' sz(Table.get_key_fields..)r"rmr*r&r&r'get_key_fieldsszTable.get_key_fieldscCst|S)a Allows the batching of writes to DynamoDB. Since each write/delete call to DynamoDB has a cost associated with it, when loading lots of data, it makes sense to batch them, creating as few calls as possible. This returns a context manager that will transparently handle creating these batches. The object you get back lightly-resembles a ``Table`` object, sharing just the ``put_item`` & ``delete_item`` methods (which are all that DynamoDB can batch in terms of writing data). DynamoDB's maximum batch size is 25 items per request. If you attempt to put/delete more than that, the context manager will batch as many as it can up to that number, then flush them to DynamoDB & continue batching as more calls come in. Example:: # Assuming a table with one record... >>> with users.batch_write() as batch: ... batch.put_item(data={ ... 'username': 'johndoe', ... 'first_name': 'John', ... 'last_name': 'Doe', ... 'owner': 1, ... }) ... # Nothing across the wire yet. ... batch.delete_item(username='bob') ... # Still no requests sent. ... batch.put_item(data={ ... 'username': 'jane', ... 'first_name': 'Jane', ... 'last_name': 'Doe', ... 'date_joined': 127436192, ... }) ... # Nothing yet, but once we leave the context, the ... # put/deletes will be sent. ) BatchTabler*r&r&r' batch_writes*zTable.batch_writec Csn|durdSi}|D]\}}|d}d|dd}z||d}Wnty8td|d|fwg|d} |ddkrU| d=|durPd | d <n`d | d <n[|dd krt|d krt|tt fr| d |j |d| d |j |dn-|ddkr|D] } | d |j | qnt|tt frt |}| d |j || ||<q |S)z An internal method for taking query/scan-style ``**kwargs`` & turning them into the raw structure DynamoDB expects for filtering. N__z*Operator '%s' from '%s' is not recognized.)AttributeValueListComparisonOperatornullrFNOT_NULLrNULLbetweenrin)rqsplitjoinKeyErrorrUnknownFilterTypeErrorlen isinstancelisttupler5r$rr4) r% filter_kwargsrfilters field_and_opr field_bits fieldnameoprvalr&r&r'rsX          zTable._build_filtersc Ks$| }|jd||||||d|S)z **WARNING:** This method is provided **strictly** for backward-compatibility. It returns results in an incorrect order. If you are writing new code, please use ``Table.query_2``. )limitindexreverserr max_page_sizeNr&)query_2)r%rrrrrrrr&r&r'querys z Table.queryc Ks|jrt|jdkrt| dkr|jrt|jstd|dur$d} nd} t|d} | } | ||||| |||d| j|j fi| | S)a Queries for a set of matching items in a DynamoDB table. Queries can be performed against a hash key, a hash+range key or against any data stored in your local secondary indexes. Query filters can be used to filter on arbitrary fields. **Note** - You can not query against arbitrary fields within the data stored in DynamoDB unless you specify ``query_filter`` values. To specify the filters of the items you'd like to get, you can specify the filters as kwargs. Each filter kwarg should follow the pattern ``__=``. Query filters are specified in the same way. Optionally accepts a ``limit`` parameter, which should be an integer count of the total number of items to return. (Default: ``None`` - all results) Optionally accepts an ``index`` parameter, which should be a string of name of the local secondary index you want to query against. (Default: ``None``) Optionally accepts a ``reverse`` parameter, which will present the results in reverse order. (Default: ``False`` - normal order) Optionally accepts a ``consistent`` parameter, which should be a boolean. If you provide ``True``, it will force a consistent read of the data (more expensive). (Default: ``False`` - use eventually consistent reads) Optionally accepts a ``attributes`` parameter, which should be a tuple. If you provide any attributes only these will be fetched from DynamoDB. This uses the ``AttributesToGet`` and set's ``Select`` to ``SPECIFIC_ATTRIBUTES`` API. Optionally accepts a ``max_page_size`` parameter, which should be an integer count of the maximum number of items to retrieve **per-request**. This is useful in making faster requests & prevent the scan from drowning out other queries. (Default: ``None`` - fetch as many as DynamoDB will return) Optionally accepts a ``query_filter`` which is a dictionary of filter conditions against any arbitrary field in the returned data. Optionally accepts a ``conditional_operator`` which applies to the query filter conditions: + `AND` - True if all filter conditions evaluate to true (default) + `OR` - True if at least one filter condition evaluates to true Returns a ``ResultSet`` containing ``Item``s, which transparently handles the pagination of results you get back. Example:: # Look for last names equal to "Doe". >>> results = users.query(last_name__eq='Doe') >>> for res in results: ... print res['first_name'] 'John' 'Jane' # Look for last names beginning with "D", in reverse order, limit 3. >>> results = users.query( ... last_name__beginswith='D', ... reverse=True, ... limit=3 ... ) >>> for res in results: ... print res['first_name'] 'Alice' 'Jane' 'John' # Use an LSI & a consistent read. >>> results = users.query( ... date_joined__gte=1236451000, ... owner__eq=1, ... index='DateJoinedIndex', ... consistent=True ... ) >>> for res in results: ... print res['first_name'] 'Alice' 'Bob' 'John' 'Fred' # Filter by non-indexed field(s) >>> results = users.query( ... last_name__eq='Doe', ... reverse=True, ... query_filter={ ... 'first_name__beginswith': 'A' ... } ... ) >>> for res in results: ... print res['first_name'] + ' ' + res['last_name'] 'Alice Doe' rz0You must specify more than one key to filter on.NSPECIFIC_ATTRIBUTESr)rrrrselectr query_filterr) r"rrr QueryErrorr copyr{to_call_query) r%rrrrrrrrrrresultsrDr&r&r'r+s4j  z Table.query_2Tc Ksz|j|td} |j|td} d} |} |jj|j||d| | |||| d } | t| dd7} | d} | r9| dkr< | Sq) a) Queries the exact count of matching items in a DynamoDB table. Queries can be performed against a hash key, a hash+range key or against any data stored in your local secondary indexes. Query filters can be used to filter on arbitrary fields. To specify the filters of the items you'd like to get, you can specify the filters as kwargs. Each filter kwarg should follow the pattern ``__=``. Query filters are specified in the same way. Optionally accepts an ``index`` parameter, which should be a string of name of the local secondary index you want to query against. (Default: ``None``) Optionally accepts a ``consistent`` parameter, which should be a boolean. If you provide ``True``, it will force a consistent read of the data (more expensive). (Default: ``False`` - use eventually consistent reads) Optionally accepts a ``query_filter`` which is a dictionary of filter conditions against any arbitrary field in the returned data. Optionally accepts a ``conditional_operator`` which applies to the query filter conditions: + `AND` - True if all filter conditions evaluate to true (default) + `OR` - True if at least one filter condition evaluates to true Optionally accept a ``exclusive_start_key`` which is used to get the remaining items when a query cannot return the complete count. Returns an integer which represents the exact amount of matched items. :type scan_index_forward: boolean :param scan_index_forward: Specifies ascending (true) or descending (false) traversal of the index. DynamoDB returns results reflecting the requested order determined by the range key. If the data type is Number, the results are returned in numeric order. For String, the results are returned in order of ASCII character code values. For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values. If ScanIndexForward is not specified, the results are returned in ascending order. :type limit: integer :param limit: The maximum number of items to evaluate (not necessarily the number of matching items). Example:: # Look for last names equal to "Doe". >>> users.query_count(last_name__eq='Doe') 5 # Use an LSI & a consistent read. >>> users.query_count( ... date_joined__gte=1236451000, ... owner__eq=1, ... index='DateJoinedIndex', ... consistent=True ... ) 2 rrTCOUNT) index_namerrkey_conditionsrrrscan_index_forwardexclusive_start_keyCountLastEvaluatedKeyr)rrrr rrr9rR)r%rrrrrrrrrbuilt_query_filter count_bufferlast_evaluated_key raw_resultsr&r&r' query_counts:G  zTable.query_countc Ks|||||| d} |rd| d<|r(i| d<|D]\} } |j| | d| <q|j| td| d<|j|td| d<|jj|jfi| }g}d}| d gD]}t |}| d |i| |qO| d dr}i}|d D] \} } |j | || <qp||d S) z The internal method that performs the actual queries. Used extensively by ``ResultSet`` to perform each (paginated) request. )rrrrrrFrrrrrNItemsr rrlast_key)rqr$rrrrr rrrRr rr5decode)r%rrrrrrrrrrrDrrrrrraw_itemrr&r&r'rsT       z Table._queryc Ks@t|d}|} | |||||d|j|jfi| |S)a Scans across all items within a DynamoDB table. Scans can be performed against a hash key or a hash+range key. You can additionally filter the results after the table has been read but before the response is returned by using query filters. To specify the filters of the items you'd like to get, you can specify the filters as kwargs. Each filter kwarg should follow the pattern ``__=``. Optionally accepts a ``limit`` parameter, which should be an integer count of the total number of items to return. (Default: ``None`` - all results) Optionally accepts a ``segment`` parameter, which should be an integer of the segment to retrieve on. Please see the documentation about Parallel Scans (Default: ``None`` - no segments) Optionally accepts a ``total_segments`` parameter, which should be an integer count of number of segments to divide the table into. Please see the documentation about Parallel Scans (Default: ``None`` - no segments) Optionally accepts a ``max_page_size`` parameter, which should be an integer count of the maximum number of items to retrieve **per-request**. This is useful in making faster requests & prevent the scan from drowning out other queries. (Default: ``None`` - fetch as many as DynamoDB will return) Optionally accepts an ``attributes`` parameter, which should be a tuple. If you provide any attributes only these will be fetched from DynamoDB. This uses the ``AttributesToGet`` and set's ``Select`` to ``SPECIFIC_ATTRIBUTES`` API. Returns a ``ResultSet``, which transparently handles the pagination of results you get back. Example:: # All results. >>> everything = users.scan() # Look for last names beginning with "D". >>> results = users.scan(last_name__beginswith='D') >>> for res in results: ... print res['first_name'] 'Alice' 'John' 'Jane' # Use an ``IN`` filter & limit. >>> results = users.scan( ... age__in=[25, 26, 27, 28, 29], ... limit=1 ... ) >>> for res in results: ... print res['first_name'] 'Alice' r)rsegmenttotal_segmentsrr)r rr{r_scan) r%rrrrrrrrrDr&r&r'scan]s@z Table.scancKs|||||d}|r!i|d<|D]\} } |j| |d| <q|j|td|d<|jj|jfi|} g} d} | dgD]}t |}| d|i| |q?| ddrmi} | dD] \} } |j | | | <q`| | d S) z The internal method that performs the actual scan. Used extensively by ``ResultSet`` to perform each (paginated) request. )rrrrrrr scan_filterNrr rr) rqr$rrrr rrrRr rr5r)r%rrrrrrrrDrrrrrrrr&r&r'rsF     z Table._scancCs$t||jd}|j|j||d|S)a Fetches many specific items in batch from a table. Requires a ``keys`` parameter, which should be a list of dictionaries. Each dictionary should consist of the keys values to specify. Optionally accepts a ``consistent`` parameter, which should be a boolean. If you provide ``True``, a strongly consistent read will be used. (Default: False) Optionally accepts an ``attributes`` parameter, which should be a tuple. If you provide any attributes only these will be fetched from DynamoDB. Returns a ``ResultSet``, which transparently handles the pagination of results you get back. Example:: >>> results = users.batch_get(keys=[ ... { ... 'username': 'johndoe', ... }, ... { ... 'username': 'jane', ... }, ... { ... 'username': 'fred', ... }, ... ]) >>> for res in results: ... print res['first_name'] 'John' 'Jane' 'Fred' )r max_batch_get)rr)rrr _batch_get)r%rrrrr&r&r' batch_gets(zTable.batch_getcCs,|jdgii}|rd||jd<|dur|||jd<|D]}i}|D] \}}|j|||<q%||jd|q|jj|d} g} g} | d|jgD]} t|} | d| i| | qQ| d i|ji}|dgD]}i}|D] \}}|j |||<q}| |qu| d| d S) z The internal method that performs the actual batch get. Used extensively by ``BatchGetResultSet`` to perform each (paginated) request. KeysTConsistentReadNAttributesToGet) request_items Responsesr UnprocessedKeys)rrunprocessed_keys) rrqr$rr5r batch_get_itemrRr rr)r%rrrrqkey_datarrrrrrrrraw_unprocessedpy_keyr&r&r'r s@  zTable._batch_getcCs|}|dddS)z Returns a (very) eventually consistent count of the number of items in a table. Lag time is about 6 hours, so don't expect a high degree of accuracy. Example:: >>> users.count() 6 r ItemCountr)rmrR)r%infor&r&r'countCs z Table.count)NNNNN)NNNNr))NN)FNF)NNFFNN)NNFFNNNN)NFNNTNN) NNFFNNNNN)NNNNNN)1__name__ __module__ __qualname____doc__rdictrr r rrrrcr(r+ classmethodrJrVr`rdrfrmr{rrrrrrrrrrrrrrrrrrrrrrrrrrr&r&r&r'rs   W z! 1O7*5 ;' !  @ ,@     i > N 5 , 7rc@sZeZdZdZddZddZddZdd d Zd d Zd dZ ddZ ddZ ddZ dS)rz Used by ``Table`` as the context manager for batch writes. You likely don't want to try to use this object directly. cCs||_g|_g|_g|_dSr))r>_to_put _to_delete _unprocessed)r%r>r&r&r'r(Zs zBatchTable.__init__cCs|Sr)r&r*r&r&r' __enter__`szBatchTable.__enter__cCs*|js|jr ||jr|dSdSr))r r flushr resend_unprocessed)r%typer tracebackr&r&r'__exit__cs  zBatchTable.__exit__FcC$|j||r|dSdSr))r r5 should_flushr)r%rvrr&r&r'rl  zBatchTable.put_itemcKrr))r r5rrrr&r&r'rrrzBatchTable.delete_itemcCs t|jt|jdkrdSdS)NTF)rr r r*r&r&r'rxszBatchTable.should_flushcCs|jjgi}|jD]}t|j|d}||jjdd|iiq |jD]}||jjdd|j|iiq%|jj |}| |g|_g|_dS)Nr PutRequestr DeleteRequestKeyT) r>rr r r5 prepare_fullr rr batch_write_itemhandle_unprocessed)r% batch_dataputrrrespr&r&r'r~s(      zBatchTable.flushcCsTt|dgr(|jj}|d|g}d}tj|t||j|dSdS)NUnprocessedItemsz-%s items were unprocessed. Storing for later.) rrRr>rrsrtrr extend)r%r r unprocessedrzr&r&r'rszBatchTable.handle_unprocessedcCstjdt|jt|jrM|jdd}|jdd|_|jj|i}tjdt||jj|}| |tjdt|jt|jsdSdS)Nz Re-sending %s unprocessed items.rzSending %s itemsz%s unprocessed items left) rsrtrrr r>rr rr)r% to_resendrr r&r&r'rs    zBatchTable.resend_unprocessedNr) rrrrr(rrrrrrrrr&r&r&r'rTs  r)rsboto.dynamodb2rboto.dynamodb2.fieldsrrrrrrr r boto.dynamodb2.itemsr boto.dynamodb2.layer1r boto.dynamodb2.resultsr rboto.dynamodb2.typesrrrrrboto.exceptionrobjectrrr&r&r&r's, (   Q