PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/boto/dynamodb2/table.py

https://gitlab.com/smoke.torez/python-mysql-dump-to-amazon-s3
Python | 1361 lines | 1300 code | 24 blank | 37 comment | 6 complexity | 777de59b4d3d596528946df05bfe6e76 MD5 | raw file
  1. import boto
  2. from boto.dynamodb2 import exceptions
  3. from boto.dynamodb2.fields import (HashKey, RangeKey,
  4. AllIndex, KeysOnlyIndex, IncludeIndex,
  5. GlobalAllIndex, GlobalKeysOnlyIndex,
  6. GlobalIncludeIndex)
  7. from boto.dynamodb2.items import Item
  8. from boto.dynamodb2.layer1 import DynamoDBConnection
  9. from boto.dynamodb2.results import ResultSet, BatchGetResultSet
  10. from boto.dynamodb2.types import Dynamizer, FILTER_OPERATORS, QUERY_OPERATORS
  11. from boto.exception import JSONResponseError
  12. class Table(object):
  13. """
  14. Interacts & models the behavior of a DynamoDB table.
  15. The ``Table`` object represents a set (or rough categorization) of
  16. records within DynamoDB. The important part is that all records within the
  17. table, while largely-schema-free, share the same schema & are essentially
  18. namespaced for use in your application. For example, you might have a
  19. ``users`` table or a ``forums`` table.
  20. """
  21. max_batch_get = 100
  22. def __init__(self, table_name, schema=None, throughput=None, indexes=None,
  23. global_indexes=None, connection=None):
  24. """
  25. Sets up a new in-memory ``Table``.
  26. This is useful if the table already exists within DynamoDB & you simply
  27. want to use it for additional interactions. The only required parameter
  28. is the ``table_name``. However, under the hood, the object will call
  29. ``describe_table`` to determine the schema/indexes/throughput. You
  30. can avoid this extra call by passing in ``schema`` & ``indexes``.
  31. **IMPORTANT** - If you're creating a new ``Table`` for the first time,
  32. you should use the ``Table.create`` method instead, as it will
  33. persist the table structure to DynamoDB.
  34. Requires a ``table_name`` parameter, which should be a simple string
  35. of the name of the table.
  36. Optionally accepts a ``schema`` parameter, which should be a list of
  37. ``BaseSchemaField`` subclasses representing the desired schema.
  38. Optionally accepts a ``throughput`` parameter, which should be a
  39. dictionary. If provided, it should specify a ``read`` & ``write`` key,
  40. both of which should have an integer value associated with them.
  41. Optionally accepts a ``indexes`` parameter, which should be a list of
  42. ``BaseIndexField`` subclasses representing the desired indexes.
  43. Optionally accepts a ``global_indexes`` parameter, which should be a
  44. list of ``GlobalBaseIndexField`` subclasses representing the desired
  45. indexes.
  46. Optionally accepts a ``connection`` parameter, which should be a
  47. ``DynamoDBConnection`` instance (or subclass). This is primarily useful
  48. for specifying alternate connection parameters.
  49. Example::
  50. # The simple, it-already-exists case.
  51. >>> conn = Table('users')
  52. # The full, minimum-extra-calls case.
  53. >>> from boto import dynamodb2
  54. >>> users = Table('users', schema=[
  55. ... HashKey('username'),
  56. ... RangeKey('date_joined', data_type=NUMBER)
  57. ... ], throughput={
  58. ... 'read':20,
  59. ... 'write': 10,
  60. ... }, indexes=[
  61. ... KeysOnlyIndex('MostRecentlyJoined', parts=[
  62. ... HashKey('username')
  63. ... RangeKey('date_joined')
  64. ... ]),
  65. ... ], global_indexes=[
  66. ... GlobalAllIndex('UsersByZipcode', parts=[
  67. ... HashKey('zipcode'),
  68. ... RangeKey('username'),
  69. ... ],
  70. ... throughput={
  71. ... 'read':10,
  72. ... 'write":10,
  73. ... }),
  74. ... ], connection=dynamodb2.connect_to_region('us-west-2',
  75. ... aws_access_key_id='key',
  76. ... aws_secret_access_key='key',
  77. ... ))
  78. """
  79. self.table_name = table_name
  80. self.connection = connection
  81. self.throughput = {
  82. 'read': 5,
  83. 'write': 5,
  84. }
  85. self.schema = schema
  86. self.indexes = indexes
  87. self.global_indexes = global_indexes
  88. if self.connection is None:
  89. self.connection = DynamoDBConnection()
  90. if throughput is not None:
  91. self.throughput = throughput
  92. self._dynamizer = Dynamizer()
  93. @classmethod
  94. def create(cls, table_name, schema, throughput=None, indexes=None,
  95. global_indexes=None, connection=None):
  96. """
  97. Creates a new table in DynamoDB & returns an in-memory ``Table`` object.
  98. This will setup a brand new table within DynamoDB. The ``table_name``
  99. must be unique for your AWS account. The ``schema`` is also required
  100. to define the key structure of the table.
  101. **IMPORTANT** - You should consider the usage pattern of your table
  102. up-front, as the schema & indexes can **NOT** be modified once the
  103. table is created, requiring the creation of a new table & migrating
  104. the data should you wish to revise it.
  105. **IMPORTANT** - If the table already exists in DynamoDB, additional
  106. calls to this method will result in an error. If you just need
  107. a ``Table`` object to interact with the existing table, you should
  108. just initialize a new ``Table`` object, which requires only the
  109. ``table_name``.
  110. Requires a ``table_name`` parameter, which should be a simple string
  111. of the name of the table.
  112. Requires a ``schema`` parameter, which should be a list of
  113. ``BaseSchemaField`` subclasses representing the desired schema.
  114. Optionally accepts a ``throughput`` parameter, which should be a
  115. dictionary. If provided, it should specify a ``read`` & ``write`` key,
  116. both of which should have an integer value associated with them.
  117. Optionally accepts a ``indexes`` parameter, which should be a list of
  118. ``BaseIndexField`` subclasses representing the desired indexes.
  119. Optionally accepts a ``global_indexes`` parameter, which should be a
  120. list of ``GlobalBaseIndexField`` subclasses representing the desired
  121. indexes.
  122. Optionally accepts a ``connection`` parameter, which should be a
  123. ``DynamoDBConnection`` instance (or subclass). This is primarily useful
  124. for specifying alternate connection parameters.
  125. Example::
  126. >>> users = Table.create('users', schema=[
  127. ... HashKey('username'),
  128. ... RangeKey('date_joined', data_type=NUMBER)
  129. ... ], throughput={
  130. ... 'read':20,
  131. ... 'write': 10,
  132. ... }, indexes=[
  133. ... KeysOnlyIndex('MostRecentlyJoined', parts=[
  134. ... RangeKey('date_joined')
  135. ... ]), global_indexes=[
  136. ... GlobalAllIndex('UsersByZipcode', parts=[
  137. ... HashKey('zipcode'),
  138. ... RangeKey('username'),
  139. ... ],
  140. ... throughput={
  141. ... 'read':10,
  142. ... 'write':10,
  143. ... }),
  144. ... ])
  145. """
  146. table = cls(table_name=table_name, connection=connection)
  147. table.schema = schema
  148. if throughput is not None:
  149. table.throughput = throughput
  150. if indexes is not None:
  151. table.indexes = indexes
  152. if global_indexes is not None:
  153. table.global_indexes = global_indexes
  154. # Prep the schema.
  155. raw_schema = []
  156. attr_defs = []
  157. seen_attrs = set()
  158. for field in table.schema:
  159. raw_schema.append(field.schema())
  160. # Build the attributes off what we know.
  161. seen_attrs.add(field.name)
  162. attr_defs.append(field.definition())
  163. raw_throughput = {
  164. 'ReadCapacityUnits': int(table.throughput['read']),
  165. 'WriteCapacityUnits': int(table.throughput['write']),
  166. }
  167. kwargs = {}
  168. kwarg_map = {
  169. 'indexes': 'local_secondary_indexes',
  170. 'global_indexes': 'global_secondary_indexes',
  171. }
  172. for index_attr in ('indexes', 'global_indexes'):
  173. table_indexes = getattr(table, index_attr)
  174. if table_indexes:
  175. raw_indexes = []
  176. for index_field in table_indexes:
  177. raw_indexes.append(index_field.schema())
  178. # Make sure all attributes specified in the indexes are
  179. # added to the definition
  180. for field in index_field.parts:
  181. if field.name not in seen_attrs:
  182. seen_attrs.add(field.name)
  183. attr_defs.append(field.definition())
  184. kwargs[kwarg_map[index_attr]] = raw_indexes
  185. table.connection.create_table(
  186. table_name=table.table_name,
  187. attribute_definitions=attr_defs,
  188. key_schema=raw_schema,
  189. provisioned_throughput=raw_throughput,
  190. **kwargs
  191. )
  192. return table
  193. def _introspect_schema(self, raw_schema):
  194. """
  195. Given a raw schema structure back from a DynamoDB response, parse
  196. out & build the high-level Python objects that represent them.
  197. """
  198. schema = []
  199. for field in raw_schema:
  200. if field['KeyType'] == 'HASH':
  201. schema.append(HashKey(field['AttributeName']))
  202. elif field['KeyType'] == 'RANGE':
  203. schema.append(RangeKey(field['AttributeName']))
  204. else:
  205. raise exceptions.UnknownSchemaFieldError(
  206. "%s was seen, but is unknown. Please report this at "
  207. "https://github.com/boto/boto/issues." % field['KeyType']
  208. )
  209. return schema
  210. def _introspect_indexes(self, raw_indexes):
  211. """
  212. Given a raw index structure back from a DynamoDB response, parse
  213. out & build the high-level Python objects that represent them.
  214. """
  215. indexes = []
  216. for field in raw_indexes:
  217. index_klass = AllIndex
  218. kwargs = {
  219. 'parts': []
  220. }
  221. if field['Projection']['ProjectionType'] == 'ALL':
  222. index_klass = AllIndex
  223. elif field['Projection']['ProjectionType'] == 'KEYS_ONLY':
  224. index_klass = KeysOnlyIndex
  225. elif field['Projection']['ProjectionType'] == 'INCLUDE':
  226. index_klass = IncludeIndex
  227. kwargs['includes'] = field['Projection']['NonKeyAttributes']
  228. else:
  229. raise exceptions.UnknownIndexFieldError(
  230. "%s was seen, but is unknown. Please report this at "
  231. "https://github.com/boto/boto/issues." % \
  232. field['Projection']['ProjectionType']
  233. )
  234. name = field['IndexName']
  235. kwargs['parts'] = self._introspect_schema(field['KeySchema'])
  236. indexes.append(index_klass(name, **kwargs))
  237. return indexes
  238. def describe(self):
  239. """
  240. Describes the current structure of the table in DynamoDB.
  241. This information will be used to update the ``schema``, ``indexes``
  242. and ``throughput`` information on the ``Table``. Some calls, such as
  243. those involving creating keys or querying, will require this
  244. information to be populated.
  245. It also returns the full raw datastructure from DynamoDB, in the
  246. event you'd like to parse out additional information (such as the
  247. ``ItemCount`` or usage information).
  248. Example::
  249. >>> users.describe()
  250. {
  251. # Lots of keys here...
  252. }
  253. >>> len(users.schema)
  254. 2
  255. """
  256. result = self.connection.describe_table(self.table_name)
  257. # Blindly update throughput, since what's on DynamoDB's end is likely
  258. # more correct.
  259. raw_throughput = result['Table']['ProvisionedThroughput']
  260. self.throughput['read'] = int(raw_throughput['ReadCapacityUnits'])
  261. self.throughput['write'] = int(raw_throughput['WriteCapacityUnits'])
  262. if not self.schema:
  263. # Since we have the data, build the schema.
  264. raw_schema = result['Table'].get('KeySchema', [])
  265. self.schema = self._introspect_schema(raw_schema)
  266. if not self.indexes:
  267. # Build the index information as well.
  268. raw_indexes = result['Table'].get('LocalSecondaryIndexes', [])
  269. self.indexes = self._introspect_indexes(raw_indexes)
  270. # This is leaky.
  271. return result
  272. def update(self, throughput, global_indexes=None):
  273. """
  274. Updates table attributes in DynamoDB.
  275. Currently, the only thing you can modify about a table after it has
  276. been created is the throughput.
  277. Requires a ``throughput`` parameter, which should be a
  278. dictionary. If provided, it should specify a ``read`` & ``write`` key,
  279. both of which should have an integer value associated with them.
  280. Returns ``True`` on success.
  281. Example::
  282. # For a read-heavier application...
  283. >>> users.update(throughput={
  284. ... 'read': 20,
  285. ... 'write': 10,
  286. ... })
  287. True
  288. # To also update the global index(es) throughput.
  289. >>> users.update(throughput={
  290. ... 'read': 20,
  291. ... 'write': 10,
  292. ... },
  293. ... global_secondary_indexes={
  294. ... 'TheIndexNameHere': {
  295. ... 'read': 15,
  296. ... 'write': 5,
  297. ... }
  298. ... })
  299. True
  300. """
  301. self.throughput = throughput
  302. data = {
  303. 'ReadCapacityUnits': int(self.throughput['read']),
  304. 'WriteCapacityUnits': int(self.throughput['write']),
  305. }
  306. gsi_data = None
  307. if global_indexes:
  308. gsi_data = []
  309. for gsi_name, gsi_throughput in global_indexes.items():
  310. gsi_data.append({
  311. "Update": {
  312. "IndexName": gsi_name,
  313. "ProvisionedThroughput": {
  314. "ReadCapacityUnits": int(gsi_throughput['read']),
  315. "WriteCapacityUnits": int(gsi_throughput['write']),
  316. },
  317. },
  318. })
  319. self.connection.update_table(
  320. self.table_name,
  321. provisioned_throughput=data,
  322. global_secondary_index_updates=gsi_data
  323. )
  324. return True
  325. def delete(self):
  326. """
  327. Deletes a table in DynamoDB.
  328. **IMPORTANT** - Be careful when using this method, there is no undo.
  329. Returns ``True`` on success.
  330. Example::
  331. >>> users.delete()
  332. True
  333. """
  334. self.connection.delete_table(self.table_name)
  335. return True
  336. def _encode_keys(self, keys):
  337. """
  338. Given a flat Python dictionary of keys/values, converts it into the
  339. nested dictionary DynamoDB expects.
  340. Converts::
  341. {
  342. 'username': 'john',
  343. 'tags': [1, 2, 5],
  344. }
  345. ...to...::
  346. {
  347. 'username': {'S': 'john'},
  348. 'tags': {'NS': ['1', '2', '5']},
  349. }
  350. """
  351. raw_key = {}
  352. for key, value in keys.items():
  353. raw_key[key] = self._dynamizer.encode(value)
  354. return raw_key
  355. def get_item(self, consistent=False, attributes=None, **kwargs):
  356. """
  357. Fetches an item (record) from a table in DynamoDB.
  358. To specify the key of the item you'd like to get, you can specify the
  359. key attributes as kwargs.
  360. Optionally accepts a ``consistent`` parameter, which should be a
  361. boolean. If you provide ``True``, it will perform
  362. a consistent (but more expensive) read from DynamoDB.
  363. (Default: ``False``)
  364. Optionally accepts an ``attributes`` parameter, which should be a
  365. list of fieldname to fetch. (Default: ``None``, which means all fields
  366. should be fetched)
  367. Returns an ``Item`` instance containing all the data for that record.
  368. Example::
  369. # A simple hash key.
  370. >>> john = users.get_item(username='johndoe')
  371. >>> john['first_name']
  372. 'John'
  373. # A complex hash+range key.
  374. >>> john = users.get_item(username='johndoe', last_name='Doe')
  375. >>> john['first_name']
  376. 'John'
  377. # A consistent read (assuming the data might have just changed).
  378. >>> john = users.get_item(username='johndoe', consistent=True)
  379. >>> john['first_name']
  380. 'Johann'
  381. # With a key that is an invalid variable name in Python.
  382. # Also, assumes a different schema than previous examples.
  383. >>> john = users.get_item(**{
  384. ... 'date-joined': 127549192,
  385. ... })
  386. >>> john['first_name']
  387. 'John'
  388. """
  389. raw_key = self._encode_keys(kwargs)
  390. item_data = self.connection.get_item(
  391. self.table_name,
  392. raw_key,
  393. attributes_to_get=attributes,
  394. consistent_read=consistent
  395. )
  396. if 'Item' not in item_data:
  397. raise exceptions.ItemNotFound("Item %s couldn't be found." % kwargs)
  398. item = Item(self)
  399. item.load(item_data)
  400. return item
  401. def has_item(self, **kwargs):
  402. """
  403. Return whether an item (record) exists within a table in DynamoDB.
  404. To specify the key of the item you'd like to get, you can specify the
  405. key attributes as kwargs.
  406. Optionally accepts a ``consistent`` parameter, which should be a
  407. boolean. If you provide ``True``, it will perform
  408. a consistent (but more expensive) read from DynamoDB.
  409. (Default: ``False``)
  410. Optionally accepts an ``attributes`` parameter, which should be a
  411. list of fieldnames to fetch. (Default: ``None``, which means all fields
  412. should be fetched)
  413. Returns ``True`` if an ``Item`` is present, ``False`` if not.
  414. Example::
  415. # Simple, just hash-key schema.
  416. >>> users.has_item(username='johndoe')
  417. True
  418. # Complex schema, item not present.
  419. >>> users.has_item(
  420. ... username='johndoe',
  421. ... date_joined='2014-01-07'
  422. ... )
  423. False
  424. """
  425. try:
  426. self.get_item(**kwargs)
  427. except (JSONResponseError, exceptions.ItemNotFound):
  428. return False
  429. return True
  430. def lookup(self, *args, **kwargs):
  431. """
  432. Look up an entry in DynamoDB. This is mostly backwards compatible
  433. with boto.dynamodb. Unlike get_item, it takes hash_key and range_key first,
  434. although you may still specify keyword arguments instead.
  435. Also unlike the get_item command, if the returned item has no keys
  436. (i.e., it does not exist in DynamoDB), a None result is returned, instead
  437. of an empty key object.
  438. Example::
  439. >>> user = users.lookup(username)
  440. >>> user = users.lookup(username, consistent=True)
  441. >>> app = apps.lookup('my_customer_id', 'my_app_id')
  442. """
  443. if not self.schema:
  444. self.describe()
  445. for x, arg in enumerate(args):
  446. kwargs[self.schema[x].name] = arg
  447. ret = self.get_item(**kwargs)
  448. if not ret.keys():
  449. return None
  450. return ret
  451. def new_item(self, *args):
  452. """
  453. Returns a new, blank item
  454. This is mostly for consistency with boto.dynamodb
  455. """
  456. if not self.schema:
  457. self.describe()
  458. data = {}
  459. for x, arg in enumerate(args):
  460. data[self.schema[x].name] = arg
  461. return Item(self, data=data)
  462. def put_item(self, data, overwrite=False):
  463. """
  464. Saves an entire item to DynamoDB.
  465. By default, if any part of the ``Item``'s original data doesn't match
  466. what's currently in DynamoDB, this request will fail. This prevents
  467. other processes from updating the data in between when you read the
  468. item & when your request to update the item's data is processed, which
  469. would typically result in some data loss.
  470. Requires a ``data`` parameter, which should be a dictionary of the data
  471. you'd like to store in DynamoDB.
  472. Optionally accepts an ``overwrite`` parameter, which should be a
  473. boolean. If you provide ``True``, this will tell DynamoDB to blindly
  474. overwrite whatever data is present, if any.
  475. Returns ``True`` on success.
  476. Example::
  477. >>> users.put_item(data={
  478. ... 'username': 'jane',
  479. ... 'first_name': 'Jane',
  480. ... 'last_name': 'Doe',
  481. ... 'date_joined': 126478915,
  482. ... })
  483. True
  484. """
  485. item = Item(self, data=data)
  486. return item.save(overwrite=overwrite)
  487. def _put_item(self, item_data, expects=None):
  488. """
  489. The internal variant of ``put_item`` (full data). This is used by the
  490. ``Item`` objects, since that operation is represented at the
  491. table-level by the API, but conceptually maps better to telling an
  492. individual ``Item`` to save itself.
  493. """
  494. kwargs = {}
  495. if expects is not None:
  496. kwargs['expected'] = expects
  497. self.connection.put_item(self.table_name, item_data, **kwargs)
  498. return True
  499. def _update_item(self, key, item_data, expects=None):
  500. """
  501. The internal variant of ``put_item`` (partial data). This is used by the
  502. ``Item`` objects, since that operation is represented at the
  503. table-level by the API, but conceptually maps better to telling an
  504. individual ``Item`` to save itself.
  505. """
  506. raw_key = self._encode_keys(key)
  507. kwargs = {}
  508. if expects is not None:
  509. kwargs['expected'] = expects
  510. self.connection.update_item(self.table_name, raw_key, item_data, **kwargs)
  511. return True
  512. def delete_item(self, **kwargs):
  513. """
  514. Deletes an item in DynamoDB.
  515. **IMPORTANT** - Be careful when using this method, there is no undo.
  516. To specify the key of the item you'd like to get, you can specify the
  517. key attributes as kwargs.
  518. Returns ``True`` on success.
  519. Example::
  520. # A simple hash key.
  521. >>> users.delete_item(username='johndoe')
  522. True
  523. # A complex hash+range key.
  524. >>> users.delete_item(username='jane', last_name='Doe')
  525. True
  526. # With a key that is an invalid variable name in Python.
  527. # Also, assumes a different schema than previous examples.
  528. >>> users.delete_item(**{
  529. ... 'date-joined': 127549192,
  530. ... })
  531. True
  532. """
  533. raw_key = self._encode_keys(kwargs)
  534. self.connection.delete_item(self.table_name, raw_key)
  535. return True
  536. def get_key_fields(self):
  537. """
  538. Returns the fields necessary to make a key for a table.
  539. If the ``Table`` does not already have a populated ``schema``,
  540. this will request it via a ``Table.describe`` call.
  541. Returns a list of fieldnames (strings).
  542. Example::
  543. # A simple hash key.
  544. >>> users.get_key_fields()
  545. ['username']
  546. # A complex hash+range key.
  547. >>> users.get_key_fields()
  548. ['username', 'last_name']
  549. """
  550. if not self.schema:
  551. # We don't know the structure of the table. Get a description to
  552. # populate the schema.
  553. self.describe()
  554. return [field.name for field in self.schema]
  555. def batch_write(self):
  556. """
  557. Allows the batching of writes to DynamoDB.
  558. Since each write/delete call to DynamoDB has a cost associated with it,
  559. when loading lots of data, it makes sense to batch them, creating as
  560. few calls as possible.
  561. This returns a context manager that will transparently handle creating
  562. these batches. The object you get back lightly-resembles a ``Table``
  563. object, sharing just the ``put_item`` & ``delete_item`` methods
  564. (which are all that DynamoDB can batch in terms of writing data).
  565. DynamoDB's maximum batch size is 25 items per request. If you attempt
  566. to put/delete more than that, the context manager will batch as many
  567. as it can up to that number, then flush them to DynamoDB & continue
  568. batching as more calls come in.
  569. Example::
  570. # Assuming a table with one record...
  571. >>> with users.batch_write() as batch:
  572. ... batch.put_item(data={
  573. ... 'username': 'johndoe',
  574. ... 'first_name': 'John',
  575. ... 'last_name': 'Doe',
  576. ... 'owner': 1,
  577. ... })
  578. ... # Nothing across the wire yet.
  579. ... batch.delete_item(username='bob')
  580. ... # Still no requests sent.
  581. ... batch.put_item(data={
  582. ... 'username': 'jane',
  583. ... 'first_name': 'Jane',
  584. ... 'last_name': 'Doe',
  585. ... 'date_joined': 127436192,
  586. ... })
  587. ... # Nothing yet, but once we leave the context, the
  588. ... # put/deletes will be sent.
  589. """
  590. # PHENOMENAL COSMIC DOCS!!! itty-bitty code.
  591. return BatchTable(self)
  592. def _build_filters(self, filter_kwargs, using=QUERY_OPERATORS):
  593. """
  594. An internal method for taking query/scan-style ``**kwargs`` & turning
  595. them into the raw structure DynamoDB expects for filtering.
  596. """
  597. filters = {}
  598. for field_and_op, value in filter_kwargs.items():
  599. field_bits = field_and_op.split('__')
  600. fieldname = '__'.join(field_bits[:-1])
  601. try:
  602. op = using[field_bits[-1]]
  603. except KeyError:
  604. raise exceptions.UnknownFilterTypeError(
  605. "Operator '%s' from '%s' is not recognized." % (
  606. field_bits[-1],
  607. field_and_op
  608. )
  609. )
  610. lookup = {
  611. 'AttributeValueList': [],
  612. 'ComparisonOperator': op,
  613. }
  614. # Special-case the ``NULL/NOT_NULL`` case.
  615. if field_bits[-1] == 'null':
  616. del lookup['AttributeValueList']
  617. if value is False:
  618. lookup['ComparisonOperator'] = 'NOT_NULL'
  619. else:
  620. lookup['ComparisonOperator'] = 'NULL'
  621. # Special-case the ``BETWEEN`` case.
  622. elif field_bits[-1] == 'between':
  623. if len(value) == 2 and isinstance(value, (list, tuple)):
  624. lookup['AttributeValueList'].append(
  625. self._dynamizer.encode(value[0])
  626. )
  627. lookup['AttributeValueList'].append(
  628. self._dynamizer.encode(value[1])
  629. )
  630. # Special-case the ``IN`` case
  631. elif field_bits[-1] == 'in':
  632. for val in value:
  633. lookup['AttributeValueList'].append(self._dynamizer.encode(val))
  634. else:
  635. # Fix up the value for encoding, because it was built to only work
  636. # with ``set``s.
  637. if isinstance(value, (list, tuple)):
  638. value = set(value)
  639. lookup['AttributeValueList'].append(
  640. self._dynamizer.encode(value)
  641. )
  642. # Finally, insert it into the filters.
  643. filters[fieldname] = lookup
  644. return filters
  645. def query(self, limit=None, index=None, reverse=False, consistent=False,
  646. attributes=None, max_page_size=None, **filter_kwargs):
  647. """
  648. Queries for a set of matching items in a DynamoDB table.
  649. Queries can be performed against a hash key, a hash+range key or
  650. against any data stored in your local secondary indexes.
  651. **Note** - You can not query against arbitrary fields within the data
  652. stored in DynamoDB.
  653. To specify the filters of the items you'd like to get, you can specify
  654. the filters as kwargs. Each filter kwarg should follow the pattern
  655. ``<fieldname>__<filter_operation>=<value_to_look_for>``.
  656. Optionally accepts a ``limit`` parameter, which should be an integer
  657. count of the total number of items to return. (Default: ``None`` -
  658. all results)
  659. Optionally accepts an ``index`` parameter, which should be a string of
  660. name of the local secondary index you want to query against.
  661. (Default: ``None``)
  662. Optionally accepts a ``reverse`` parameter, which will present the
  663. results in reverse order. (Default: ``None`` - normal order)
  664. Optionally accepts a ``consistent`` parameter, which should be a
  665. boolean. If you provide ``True``, it will force a consistent read of
  666. the data (more expensive). (Default: ``False`` - use eventually
  667. consistent reads)
  668. Optionally accepts a ``attributes`` parameter, which should be a
  669. tuple. If you provide any attributes only these will be fetched
  670. from DynamoDB. This uses the ``AttributesToGet`` and set's
  671. ``Select`` to ``SPECIFIC_ATTRIBUTES`` API.
  672. Optionally accepts a ``max_page_size`` parameter, which should be an
  673. integer count of the maximum number of items to retrieve
  674. **per-request**. This is useful in making faster requests & prevent
  675. the scan from drowning out other queries. (Default: ``None`` -
  676. fetch as many as DynamoDB will return)
  677. Returns a ``ResultSet``, which transparently handles the pagination of
  678. results you get back.
  679. Example::
  680. # Look for last names equal to "Doe".
  681. >>> results = users.query(last_name__eq='Doe')
  682. >>> for res in results:
  683. ... print res['first_name']
  684. 'John'
  685. 'Jane'
  686. # Look for last names beginning with "D", in reverse order, limit 3.
  687. >>> results = users.query(
  688. ... last_name__beginswith='D',
  689. ... reverse=True,
  690. ... limit=3
  691. ... )
  692. >>> for res in results:
  693. ... print res['first_name']
  694. 'Alice'
  695. 'Jane'
  696. 'John'
  697. # Use an LSI & a consistent read.
  698. >>> results = users.query(
  699. ... date_joined__gte=1236451000,
  700. ... owner__eq=1,
  701. ... index='DateJoinedIndex',
  702. ... consistent=True
  703. ... )
  704. >>> for res in results:
  705. ... print res['first_name']
  706. 'Alice'
  707. 'Bob'
  708. 'John'
  709. 'Fred'
  710. """
  711. if self.schema:
  712. if len(self.schema) == 1:
  713. if len(filter_kwargs) <= 1:
  714. if not self.global_indexes or not len(self.global_indexes):
  715. # If the schema only has one field, there's <= 1 filter
  716. # param & no Global Secondary Indexes, this is user
  717. # error. Bail early.
  718. raise exceptions.QueryError(
  719. "You must specify more than one key to filter on."
  720. )
  721. if attributes is not None:
  722. select = 'SPECIFIC_ATTRIBUTES'
  723. else:
  724. select = None
  725. results = ResultSet(
  726. max_page_size=max_page_size
  727. )
  728. kwargs = filter_kwargs.copy()
  729. kwargs.update({
  730. 'limit': limit,
  731. 'index': index,
  732. 'reverse': reverse,
  733. 'consistent': consistent,
  734. 'select': select,
  735. 'attributes_to_get': attributes,
  736. })
  737. results.to_call(self._query, **kwargs)
  738. return results
  739. def query_count(self, index=None, consistent=False, **filter_kwargs):
  740. """
  741. Queries the exact count of matching items in a DynamoDB table.
  742. Queries can be performed against a hash key, a hash+range key or
  743. against any data stored in your local secondary indexes.
  744. To specify the filters of the items you'd like to get, you can specify
  745. the filters as kwargs. Each filter kwarg should follow the pattern
  746. ``<fieldname>__<filter_operation>=<value_to_look_for>``.
  747. Optionally accepts an ``index`` parameter, which should be a string of
  748. name of the local secondary index you want to query against.
  749. (Default: ``None``)
  750. Optionally accepts a ``consistent`` parameter, which should be a
  751. boolean. If you provide ``True``, it will force a consistent read of
  752. the data (more expensive). (Default: ``False`` - use eventually
  753. consistent reads)
  754. Returns an integer which represents the exact amount of matched
  755. items.
  756. Example::
  757. # Look for last names equal to "Doe".
  758. >>> users.query_count(last_name__eq='Doe')
  759. 5
  760. # Use an LSI & a consistent read.
  761. >>> users.query_count(
  762. ... date_joined__gte=1236451000,
  763. ... owner__eq=1,
  764. ... index='DateJoinedIndex',
  765. ... consistent=True
  766. ... )
  767. 2
  768. """
  769. key_conditions = self._build_filters(
  770. filter_kwargs,
  771. using=QUERY_OPERATORS
  772. )
  773. raw_results = self.connection.query(
  774. self.table_name,
  775. index_name=index,
  776. consistent_read=consistent,
  777. select='COUNT',
  778. key_conditions=key_conditions,
  779. )
  780. return int(raw_results.get('Count', 0))
  781. def _query(self, limit=None, index=None, reverse=False, consistent=False,
  782. exclusive_start_key=None, select=None, attributes_to_get=None,
  783. **filter_kwargs):
  784. """
  785. The internal method that performs the actual queries. Used extensively
  786. by ``ResultSet`` to perform each (paginated) request.
  787. """
  788. kwargs = {
  789. 'limit': limit,
  790. 'index_name': index,
  791. 'scan_index_forward': reverse,
  792. 'consistent_read': consistent,
  793. 'select': select,
  794. 'attributes_to_get': attributes_to_get
  795. }
  796. if exclusive_start_key:
  797. kwargs['exclusive_start_key'] = {}
  798. for key, value in exclusive_start_key.items():
  799. kwargs['exclusive_start_key'][key] = \
  800. self._dynamizer.encode(value)
  801. # Convert the filters into something we can actually use.
  802. kwargs['key_conditions'] = self._build_filters(
  803. filter_kwargs,
  804. using=QUERY_OPERATORS
  805. )
  806. raw_results = self.connection.query(
  807. self.table_name,
  808. **kwargs
  809. )
  810. results = []
  811. last_key = None
  812. for raw_item in raw_results.get('Items', []):
  813. item = Item(self)
  814. item.load({
  815. 'Item': raw_item,
  816. })
  817. results.append(item)
  818. if raw_results.get('LastEvaluatedKey', None):
  819. last_key = {}
  820. for key, value in raw_results['LastEvaluatedKey'].items():
  821. last_key[key] = self._dynamizer.decode(value)
  822. return {
  823. 'results': results,
  824. 'last_key': last_key,
  825. }
  826. def scan(self, limit=None, segment=None, total_segments=None,
  827. max_page_size=None, attributes=None, **filter_kwargs):
  828. """
  829. Scans across all items within a DynamoDB table.
  830. Scans can be performed against a hash key or a hash+range key. You can
  831. additionally filter the results after the table has been read but
  832. before the response is returned.
  833. To specify the filters of the items you'd like to get, you can specify
  834. the filters as kwargs. Each filter kwarg should follow the pattern
  835. ``<fieldname>__<filter_operation>=<value_to_look_for>``.
  836. Optionally accepts a ``limit`` parameter, which should be an integer
  837. count of the total number of items to return. (Default: ``None`` -
  838. all results)
  839. Optionally accepts a ``segment`` parameter, which should be an integer
  840. of the segment to retrieve on. Please see the documentation about
  841. Parallel Scans (Default: ``None`` - no segments)
  842. Optionally accepts a ``total_segments`` parameter, which should be an
  843. integer count of number of segments to divide the table into.
  844. Please see the documentation about Parallel Scans (Default: ``None`` -
  845. no segments)
  846. Optionally accepts a ``max_page_size`` parameter, which should be an
  847. integer count of the maximum number of items to retrieve
  848. **per-request**. This is useful in making faster requests & prevent
  849. the scan from drowning out other queries. (Default: ``None`` -
  850. fetch as many as DynamoDB will return)
  851. Optionally accepts an ``attributes`` parameter, which should be a
  852. tuple. If you provide any attributes only these will be fetched
  853. from DynamoDB. This uses the ``AttributesToGet`` and set's
  854. ``Select`` to ``SPECIFIC_ATTRIBUTES`` API.
  855. Returns a ``ResultSet``, which transparently handles the pagination of
  856. results you get back.
  857. Example::
  858. # All results.
  859. >>> everything = users.scan()
  860. # Look for last names beginning with "D".
  861. >>> results = users.scan(last_name__beginswith='D')
  862. >>> for res in results:
  863. ... print res['first_name']
  864. 'Alice'
  865. 'John'
  866. 'Jane'
  867. # Use an ``IN`` filter & limit.
  868. >>> results = users.scan(
  869. ... age__in=[25, 26, 27, 28, 29],
  870. ... limit=1
  871. ... )
  872. >>> for res in results:
  873. ... print res['first_name']
  874. 'Alice'
  875. """
  876. results = ResultSet(
  877. max_page_size=max_page_size
  878. )
  879. kwargs = filter_kwargs.copy()
  880. kwargs.update({
  881. 'limit': limit,
  882. 'segment': segment,
  883. 'total_segments': total_segments,
  884. 'attributes': attributes,
  885. })
  886. results.to_call(self._scan, **kwargs)
  887. return results
  888. def _scan(self, limit=None, exclusive_start_key=None, segment=None,
  889. total_segments=None, attributes=None, **filter_kwargs):
  890. """
  891. The internal method that performs the actual scan. Used extensively
  892. by ``ResultSet`` to perform each (paginated) request.
  893. """
  894. kwargs = {
  895. 'limit': limit,
  896. 'segment': segment,
  897. 'total_segments': total_segments,
  898. 'attributes_to_get': attributes,
  899. }
  900. if exclusive_start_key:
  901. kwargs['exclusive_start_key'] = {}
  902. for key, value in exclusive_start_key.items():
  903. kwargs['exclusive_start_key'][key] = \
  904. self._dynamizer.encode(value)
  905. # Convert the filters into something we can actually use.
  906. kwargs['scan_filter'] = self._build_filters(
  907. filter_kwargs,
  908. using=FILTER_OPERATORS
  909. )
  910. raw_results = self.connection.scan(
  911. self.table_name,
  912. **kwargs
  913. )
  914. results = []
  915. last_key = None
  916. for raw_item in raw_results.get('Items', []):
  917. item = Item(self)
  918. item.load({
  919. 'Item': raw_item,
  920. })
  921. results.append(item)
  922. if raw_results.get('LastEvaluatedKey', None):
  923. last_key = {}
  924. for key, value in raw_results['LastEvaluatedKey'].items():
  925. last_key[key] = self._dynamizer.decode(value)
  926. return {
  927. 'results': results,
  928. 'last_key': last_key,
  929. }
  930. def batch_get(self, keys, consistent=False):
  931. """
  932. Fetches many specific items in batch from a table.
  933. Requires a ``keys`` parameter, which should be a list of dictionaries.
  934. Each dictionary should consist of the keys values to specify.
  935. Optionally accepts a ``consistent`` parameter, which should be a
  936. boolean. If you provide ``True``, a strongly consistent read will be
  937. used. (Default: False)
  938. Returns a ``ResultSet``, which transparently handles the pagination of
  939. results you get back.
  940. Example::
  941. >>> results = users.batch_get(keys=[
  942. ... {
  943. ... 'username': 'johndoe',
  944. ... },
  945. ... {
  946. ... 'username': 'jane',
  947. ... },
  948. ... {
  949. ... 'username': 'fred',
  950. ... },
  951. ... ])
  952. >>> for res in results:
  953. ... print res['first_name']
  954. 'John'
  955. 'Jane'
  956. 'Fred'
  957. """
  958. # We pass the keys to the constructor instead, so it can maintain it's
  959. # own internal state as to what keys have been processed.
  960. results = BatchGetResultSet(keys=keys, max_batch_get=self.max_batch_get)
  961. results.to_call(self._batch_get, consistent=False)
  962. return results
  963. def _batch_get(self, keys, consistent=False):
  964. """
  965. The internal method that performs the actual batch get. Used extensively
  966. by ``BatchGetResultSet`` to perform each (paginated) request.
  967. """
  968. items = {
  969. self.table_name: {
  970. 'Keys': [],
  971. },
  972. }
  973. if consistent:
  974. items[self.table_name]['ConsistentRead'] = True
  975. for key_data in keys:
  976. raw_key = {}
  977. for key, value in key_data.items():
  978. raw_key[key] = self._dynamizer.encode(value)
  979. items[self.table_name]['Keys'].append(raw_key)
  980. raw_results = self.connection.batch_get_item(request_items=items)
  981. results = []
  982. unprocessed_keys = []
  983. for raw_item in raw_results['Responses'].get(self.table_name, []):
  984. item = Item(self)
  985. item.load({
  986. 'Item': raw_item,
  987. })
  988. results.append(item)
  989. raw_unproccessed = raw_results.get('UnprocessedKeys', {})
  990. for raw_key in raw_unproccessed.get('Keys', []):
  991. py_key = {}
  992. for key, value in raw_key.items():
  993. py_key[key] = self._dynamizer.decode(value)
  994. unprocessed_keys.append(py_key)
  995. return {
  996. 'results': results,
  997. # NEVER return a ``last_key``. Just in-case any part of
  998. # ``ResultSet`` peeks through, since much of the
  999. # original underlying implementation is based on this key.
  1000. 'last_key': None,
  1001. 'unprocessed_keys': unprocessed_keys,
  1002. }
  1003. def count(self):
  1004. """
  1005. Returns a (very) eventually consistent count of the number of items
  1006. in a table.
  1007. Lag time is about 6 hours, so don't expect a high degree of accuracy.
  1008. Example::
  1009. >>> users.count()
  1010. 6
  1011. """
  1012. info = self.describe()
  1013. return info['Table'].get('ItemCount', 0)
  1014. class BatchTable(object):
  1015. """
  1016. Used by ``Table`` as the context manager for batch writes.
  1017. You likely don't want to try to use this object directly.
  1018. """
  1019. def __init__(self, table):
  1020. self.table = table
  1021. self._to_put = []
  1022. self._to_delete = []
  1023. self._unprocessed = []
  1024. def __enter__(self):
  1025. return self
  1026. def __exit__(self, type, value, traceback):
  1027. if self._to_put or self._to_delete:
  1028. # Flush anything that's left.
  1029. self.flush()
  1030. if self._unprocessed:
  1031. # Finally, handle anything that wasn't processed.
  1032. self.resend_unprocessed()
  1033. def put_item(self, data, overwrite=False):
  1034. self._to_put.append(data)
  1035. if self.should_flush():
  1036. self.flush()
  1037. def delete_item(self, **kwargs):
  1038. self._to_delete.append(kwargs)
  1039. if self.should_flush():
  1040. self.flush()
  1041. def should_flush(self):
  1042. if len(self._to_put) + len(self._to_delete) == 25:
  1043. return True
  1044. return False
  1045. def flush(self):
  1046. batch_data = {
  1047. self.table.table_name: [
  1048. # We'll insert data here shortly.
  1049. ],
  1050. }
  1051. for put in self._to_put:
  1052. item = Item(self.table, data=put)
  1053. batch_data[self.table.table_name].append({
  1054. 'PutRequest': {
  1055. 'Item': item.prepare_full(),
  1056. }
  1057. })
  1058. for delete in self._to_delete:
  1059. batch_data[self.table.table_name].append({
  1060. 'DeleteRequest': {
  1061. 'Key': self.table._encode_keys(delete),
  1062. }
  1063. })
  1064. resp = self.table.connection.batch_write_item(batch_data)
  1065. self.handle_unprocessed(resp)
  1066. self._to_put = []
  1067. self._to_delete = []
  1068. return True
  1069. def handle_unprocessed(self, resp):
  1070. if len(resp.get('UnprocessedItems', [])):
  1071. table_name = self.table.table_name
  1072. unprocessed = resp['UnprocessedItems'].get(table_name, [])
  1073. # Some items have not been processed. Stow them for now &
  1074. # re-attempt processing on ``__exit__``.
  1075. msg = "%s items were unprocessed. Storing for later."
  1076. boto.log.info(msg % len(unprocessed))
  1077. self._unprocessed.extend(unprocessed)
  1078. def resend_unprocessed(self):
  1079. # If there are unprocessed records (for instance, the user was over
  1080. # their throughput limitations), iterate over them & send until they're
  1081. # all there.
  1082. boto.log.info(
  1083. "Re-sending %s unprocessed items." % len(self._unprocessed)
  1084. )
  1085. while len(self._unprocessed):
  1086. # Again, do 25 at a time.
  1087. to_resend = self._unprocessed[:25]
  1088. # Remove them from the list.
  1089. self._unprocessed = self._unprocessed[25:]
  1090. batch_data = {
  1091. self.table.table_name: to_resend
  1092. }
  1093. boto.log.info("Sending %s items" % len(to_resend))
  1094. resp = self.table.connection.batch_write_item(batch_data)
  1095. self.handle_unprocessed(resp)
  1096. boto.log.info(
  1097. "%s unprocessed items left" % len(self._unprocessed)
  1098. )