Skip to content

Instantly share code, notes, and snippets.

@jlafon
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlafon/e8c2f787bbbafcfb041a to your computer and use it in GitHub Desktop.
Save jlafon/e8c2f787bbbafcfb041a to your computer and use it in GitHub Desktop.
Issue 25 example
import random
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, NumberAttribute
from pynamodb.indexes import LocalSecondaryIndex, AllProjection
class ViewIndex(LocalSecondaryIndex):
"""
This class represents a local secondary index
"""
class Meta:
# All attributes are projected
projection = AllProjection()
forum = UnicodeAttribute(hash_key=True)
view = NumberAttribute(range_key=True)
class TestModel(Model):
"""
A test model that uses a global secondary index
"""
class Meta:
read_capacity_units = 1
write_capacity_units = 1
table_name = 'TestModel'
host = 'http://localhost:8000'
forum = UnicodeAttribute(hash_key=True)
thread = UnicodeAttribute(range_key=True)
view_index = ViewIndex()
view = NumberAttribute(default=0)
if TestModel.exists():
TestModel.delete_table()
if not TestModel.exists():
TestModel.create_table(wait=True)
with TestModel.batch_write() as batch:
for i in range(50):
batch.save(TestModel(
'forum-hash-key',
'thread-{}'.format(i),
view=int(random.randint(0, 500))
))
for item in TestModel.view_index.query('forum-hash-key', view__gt=0):
print("Item queried from index: {0}".format(item.view))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment