How do I query DynamoDB2 table by global secondary index only using boto 2.25.0?

半城伤御伤魂 提交于 2019-12-03 19:07:31

It is possible using LSI/GSI.

See the boto tutorial here (search for LSI, and you will get the example). DynamoDB2 — boto v2.25.0 : http://boto.readthedocs.org/en/latest/ref/dynamodb2.html

Adding a full working example (tried with dynamo local: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html)

conn = DynamoDBConnection(
    host='localhost',
    port=8000,
    aws_access_key_id='DEVDB', #anything will do
    aws_secret_access_key='DEVDB', #anything will do
    is_secure=False)
tables = conn.list_tables()
print "Before Creation:", tables

table_name = 'myTable'
if table_name not in tables['TableNames']:
    Table.create(table_name
        , schema=[HashKey('firstKey')]
        , throughput={'read': 5, 'write': 2}
        , global_indexes=[
            GlobalAllIndex('secondKeyIndex', parts=[HashKey('secondKey')], throughput={'read': 5, 'write': 3})]
        , connection=conn
    )
    #print_table_details(conn, table_name)
table = Table(table_name, connection=conn)
item = Item(table, data={
    'firstKey': str(uuid.uuid4()),
    'secondKey': 'DUMMY-second'
})
item.save()
results = table.query(secondKey__eq='DUMMY-second', index='secondKeyIndex')
for res in results:
    print res['firstKey'], res['secondKey']

The result of execution is:

91d4d056-1da3-42c6-801e-5b8e9c42a93f DUMMY-second
15c17b09-4975-419a-b603-427e4c765f03 DUMMY-second
dd947b7d-935e-458f-84d3-ed6cd4f32f5a DUMMY-second

Also adding the exact packages (Due to Dynamo1/2 - there is chance of mistake):

from boto.dynamodb2.fields import HashKey, RangeKey, GlobalAllIndex
from boto.dynamodb2.layer1 import DynamoDBConnection
from boto.dynamodb2.table import Table
from boto.dynamodb2.items import Item

For all those looking for a newer version when using query_2: check out https://github.com/boto/boto/issues/2708

Query arguments are formatted differently. I haven't tried it, but I believe the syntax should be:

res2 = table.query(secondKey__eq='skey01',index='secondKeyIndex')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!