不使用主键查找项目

Finding item without using primary key

我尝试使用用户名在 dynamodb table 中查找用户(用户名+密码),用户 ID (int) 是主键,因此 getitem 有效:

val user = Try(table.getItem("userid",2233))//this works

使用用户名查找用户(验证密码)不起作用,但是我试过了

我有一个伴生对象:

object Authentication {
  @DynamoDBTable(tableName = "users")
  case class User(username: String, passwordMd5: String)
  ...
}

并尝试使用这个扫描():

val scanExpression = new DynamoDBScanExpression()
scanExpression.addFilterCondition("username",
  new Condition()
    .withComparisonOperator(ComparisonOperator.EQ)
    .withAttributeValueList(new AttributeValue().withS("some_username")))`

但这给了我以下错误:

com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: Class class Authentication$User$ must be annotated with interface com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable

我需要什么来解决这个问题?

解决方案(重写):

val client = new AmazonDynamoDBClient(new  ProfileCredentialsProvider())
client.setRegion(Region.getRegion(Regions.XXX))
val dynamoDB = new DynamoDB(client)
val table = dynamoDB.getTable("users")
val index = table.getIndex("username-index")

val spec = new QuerySpec()
  .withKeyConditionExpression("username = :v_username")
  .withValueMap(new ValueMap()
  .withString(":v_username", username))

val items = index.query(spec)

val iterator = items.iterator()
val user = Try(iterator.next())

问题是使用 index.query(spec) 而不是 table.query(spec)

我需要更多关于您的 table 是如何设置来回答问题的信息。

  1. 您还有其他非主要索引吗?
  2. 你使用主键吗?还是主要+范围?

为了根据不是用户主键的键查找用户:

  1. 您可以添加二级索引
  2. 执行扫描操作并手动过滤出匹配结果
  3. 添加范围键(即他们的用户名)