

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

# 在 DynamoDB 映射器中使用二级索引
<a name="ddb-mapper-secondary-indices"></a>

****  
**DynamoDB Mapper 是开发者预览版。它功能不完整，可能会发生变化。**

## 为二级索引定义架构
<a name="ddb-mapper-secondary-indices-schema"></a>

DynamoDB 表支持二级索引，这些二级索引使用与基表本身定义的键不同的键来访问数据。与基表一样，DynamoDB 映射器使用类型与索引进行交互。`[ItemSchema](https://docs.aws.amazon.com/sdk-for-kotlin/api/latest/dynamodb-mapper/aws.sdk.kotlin.hll.dynamodbmapper.items/-item-schema/index.html)`

DynamoDB 二级索引无需包含基表中的所有属性。因此，映射到索引的 Kotlin 类可能与映射到该索引基表的 Kotlin 类不同。在这种情况下，必须为索引类声明一个单独的架构。

以下代码手动为 DynamoDB `cars` 表创建索引架构。

```
import aws.sdk.kotlin.hll.dynamodbmapper.items.ItemConverter
import aws.sdk.kotlin.hll.dynamodbmapper.items.ItemSchema
import aws.sdk.kotlin.hll.dynamodbmapper.model.itemOf

// This is a data class for modelling the index of the Car table. Note
// that it contains a subset of the fields from the Car class and also 
// uses different names for them.
data class Model(val name: String, val manufacturer: String)

// We define an item converter.
val modelConverter = object : ItemConverter<Model> {
    override fun convertTo(from: Model, onlyAttributes: Set<String>?): Item  = itemOf(
        "model" to AttributeValue.S(from.name),
        "make" to AttributeValue.S(from.manufacturer),
    )

    override fun convertFrom(to: Item): Model = Model(
        name = to["model"]?.asSOrNull() ?: error("Invalid attribute `model`"),
        manufacturer = to["make"]?.asSOrNull() ?: error("Invalid attribute `make`"),
    )
}
val modelKey = KeySpec.String("model")
val makeKey = KeySpec.String("make")

val modelSchema = ItemSchema(modelConverter, modelKey, makeKey) // The partition key specification is the second parameter.

/* Note that `Model` index's partition key is `model` and its sort key is `make`,
   whereas the `Car` base table uses `make` as the partition key and `model` as the sort key:

        @DynamoDbItem
        data class Car(
            @DynamoDbPartitionKey
            val make: String,
    
            @DynamoDbSortKey
            val model: String,
    
            val initialYear: Int
        )
*/
```

我们现在可以在操作中使用`Model`实例。

## 在操作中使用二级索引
<a name="ddb-mapper-gs-index-ops"></a>

DynamoDB 映射器支持对索引的一部分操作，即和。`queryPaginated` `scanPaginated`要对索引调用这些操作，必须先从表对象中获取对索引的引用。在以下示例中，我们使用之前为`cars-by-model`索引创建的（此处未显示创建内容）：`modelSchema`

```
val table = mapper.getTable("cars", CarSchema)
val index = table.getIndex("cars-by-model", modelSchema)

val modelFlow = index
    .scanPaginated { }
    .items()

modelFlow.collect { model -> println(model) }
```