查询并扫描索引 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

查询并扫描索引

将使用 SQL 中的 SELECT 语句查询并扫描索引与使用 Amazon DynamoDB 中的 QueryScan 操作查询并扫描索引进行比较。

使用 SQL 查询并扫描索引

在关系数据库中,不能直接使用索引。相反,您通过发出 SELECT 语句来查询表,查询优化程序可使用任何索引。

查询优化程序 是一个关系数据库管理系统 (RDBMS) 组件,它将评估可用索引并确定是否可使用这些索引来加快查询速度。如果索引可用来加快查询速度,则 RDBMS 会先访问索引,然后使用索引查找表中的数据。

以下是一些可用于GenreAndPriceIndex提高性能的 SQL 语句。我们假定 Music 表包含足够多的数据以促使查询优化程序决定使用此索引,而不是扫描整个表。

/* All of the rock songs */ SELECT * FROM Music WHERE Genre = 'Rock';
/* All of the cheap country songs */ SELECT Artist, SongTitle, Price FROM Music WHERE Genre = 'Country' AND Price < 0.50;

在 DynamoDB 中查询并扫描索引

在 DynamoDB 中,直接对索引执行 QueryScan 操作,就如同对表执行此操作一样。您可以使用 DynamoDB API 或 PartiQL(一种与 SQL 兼容的查询语言)来查询或扫描索引。您必须指定 TableNameIndexName

以下是 DynamoDB GenreAndPriceIndex中的一些查询。(此索引的键架构包含 GenrePrice。)

DynamoDB API
// All of the rock songs { TableName: "Music", IndexName: "GenreAndPriceIndex", KeyConditionExpression: "Genre = :genre", ExpressionAttributeValues: { ":genre": "Rock" }, };

此示例使用 ProjectionExpression 指示您只希望结果中显示部分而不是全部属性。

// All of the cheap country songs { TableName: "Music", IndexName: "GenreAndPriceIndex", KeyConditionExpression: "Genre = :genre and Price < :price", ExpressionAttributeValues: { ":genre": "Country", ":price": 0.50 }, ProjectionExpression: "Artist, SongTitle, Price" };

以下是正在进行的扫描GenreAndPriceIndex

// Return all of the data in the index { TableName: "Music", IndexName: "GenreAndPriceIndex" }
PartiQL for DynamoDB

使用 PartiQL,您可以使用 Select 语句来对索引执行查询和扫描。

// All of the rock songs SELECT * FROM Music.GenreAndPriceIndex WHERE Genre = 'Rock'
// All of the cheap country songs SELECT * FROM Music.GenreAndPriceIndex WHERE Genre = 'Rock' AND Price < 0.50

以下是正在进行的扫描GenreAndPriceIndex

// Return all of the data in the index SELECT * FROM Music.GenreAndPriceIndex
注意

有关使用 Select 的代码示例,请参阅 PartiQL for DynamoDB 的 Select 语句