DynamoDB支持两种 secondary index
:
Global secondary index
- partition key
和sort key
可以和原表不同,它的WCU和RCU单独进行设置Local secondary index
- partition key
和原表相同, sort key
和原表不同。之所以叫"Local", 是因为它的partition key必须和原表相同。而且LSI与原表共享WCU和LCU通常更建议使用GSI。但LSI支持查询的强一致性,GSI不支持,GSI只支持查询的最终一致性
应用会根据表的主键(primary key
)进行查询,但是有时也需要用其他sort key
进行查询。为了让应用能根据其他sort key来查询,可以创建一个或多个LSI(local secondary index)
,然后使用Query
或Scan
来对这些索引进行查询
例如game table的partition key和sort key分别是user_id
和game_id
,如果想根据user_id
+ game_ts
来查询,则创建一个LSI:
进入DynamoDB服务,点击Create Table
。partition key
和sort key
分别是user_id
和game_id
, 并选择Customize settings
:
点击Create local index
:
将game_ts
设置为Sort key
,并点击Create index
:
最后点击Create table
,完成表的创建。
创建完成后,在Indexes
页面查看到LSI列表及信息:
在查询时,能够根据LSI查询:
1.LSI必须在建表的时候指定,建表完成后就不能进行添加了
2.一个表最多有5个LSI
应用有时要根据不同的字段进行查询,GSI可以支持这些查询
GSI = Partition key + optional sort key
相当于另一张新表
创建时必须指定WCU/RCU
可以动态的更改/增加。和LSI不一样。
实践:
尽量减少index数量,以减少额外的存储和IO花费
小心选择projection(影射),因为secondary index会占用额外空间。根据查询时需要的属性来选择
To get the fastest queries with the lowest possible latency, project all the attributes that you expect those queries to return. In particular, if you query a local secondary index for attributes that are not projected, DynamoDB automatically fetches those attributes from the table, which requires reading the entire item from the table. This introduces latency and additional I/O operations that you can avoid.
Keep in mind that “occasional” queries can often turn into “essential” queries. If there are attributes that you don’t intend to project because you anticipate querying them only occasionally, consider whether circumstances might change and you might regret not projecting those attributes after all.
For more information about table fetches, see Provisioned throughput considerations for Local Secondary Indexes .
An item collection is all the items in a table and its local secondary indexes that have the same partition key. No item collection can exceed 10 GB, so it’s possible to run out of space for a particular partition key value.
When you add or update a table item, DynamoDB updates all local secondary indexes that are affected. If the indexed attributes are defined in the table, the local secondary indexes grow too.
When you create a local secondary index, think about how much data will be written to it, and how many of those data items will have the same partition key value. If you expect that the sum of table and index items for a particular partition key value might exceed 10 GB, consider whether you should avoid creating the index.
If you can’t avoid creating the local secondary index, you must anticipate the item collection size limit and take action before you exceed it. For strategies on working within the limit and taking corrective action, see Item collection size limit .