0

Suppose I have user table with fields userId, userName, password and some other fields where userId is the partition key. How could I write a query to find something from userName and not from userId? I am working with Spring webflux, so it also does not have the ReactiveCrudRepository for DynamoDb. My User table is something like this:

@Data
@NoArgsConstructor
@AllArgsConstructor
@DynamoDbBean
public class User {

    private String userId;
    
    private String userName;
    
    private String password;
  
    private String firstName;

    private String lastName;
    
    private String timestamp;
    
    @DynamoDbPartitionKey
    public String getUserId() {
        return userId;
    }
 }

My repo class is:

@Repository
public class UserRepo {

    private DynamoDbAsyncTable<User> userDynamoDbAsyncTable;

    public UserRepo(DynamoDbAsyncTable<User> userDynamoDbAsyncTable) {
        this.userDynamoDbAsyncTable = userDynamoDbAsyncTable;
    }

    // CREATE
    public CompletableFuture<Void> save(User user) {
        return userDynamoDbAsyncTable.putItem(user);
    }

    // READ
    public CompletableFuture<User> getUserByID(String userId) {
        return userDynamoDbAsyncTable.getItem(getKeyBuild(userId));
    }

    // UPDATE
    public CompletableFuture<User> updateUser(User user) {
        return userDynamoDbAsyncTable.updateItem(user);
    }

    // DELETE
    public CompletableFuture<User> deleteUserById(String userId) {
        return userDynamoDbAsyncTable.deleteItem(getKeyBuild(userId));
    }

    // GET_ALL_ITEM
    public PagePublisher<User> getAllUser() {
        return userDynamoDbAsyncTable.scan();
    }

    private Key getKeyBuild(String userId) {
        return Key.builder().partitionValue(userId).build();
    }
}

Is there any way to query database something like findByUserName("John") which returns the User object with "John" as a username?

Umang Kamdar
  • 33
  • 2
  • 6

1 Answers1

0

You can't query without a partition key, if you have the partition key you can combine that with a sortKey, otherwise you will need to make your userName field a sortKey in Dynamo and use a GlobalSecondaryIndex to be able to search by userName alone.

@DynamoDbSortKey
public String getUserName() {
        return serName;
}

You could use table.scan() but that's not recommended, the recommended way is to use a partition key + sortKey or sortKey + GlobalSecondaryIndex with the table method table.query().

M_K
  • 3,247
  • 6
  • 30
  • 47