Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
查询并扫描索引
将使用 SQL 中的 SELECT 语句查询并扫描索引与使用 Amazon DynamoDB 中的 Query
和 Scan
操作查询并扫描索引进行比较。
SQL
在关系数据库中,不能直接使用索引。相反,您通过发出 SELECT
语句来查询表,查询优化程序可使用任何索引。
查询优化程序 是一个关系数据库管理系统 (RDBMS) 组件,它将评估可用索引并确定是否可使用这些索引来加快查询速度。如果索引可用来加快查询速度,则 RDBMS 会先访问索引,然后使用索引查找表中的数据。
以下几个 SQL 语句可使用 GenreAndPriceIndex 提高性能。我们假定 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 中,直接对索引执行 Query
和 Scan
操作,就如同对表执行此操作一样。您可以使用 DynamoDB API 或 PartiQL(一种与 SQL 兼容的查询语言)来查询或扫描索引。您必须指定 TableName
和 IndexName
。
下面是一些 DynamoDB 中对 GenreAndPriceIndex 的查询。(此索引的键架构包含 Genre 和 Price。)
- 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