Karim Stekelenburg
Karim Stekelenburg

Reputation: 643

How to query a struct by multiple attributes in Solidity?

Suppose I have the following contract:

contract UserContract {
    struct User {
        address walletAddress;
        string organisation;
        string fName;
        string lName;
        string email;
        uint index;
    }
    mapping(address => User) private users;
    address[] private userIndex;
}

I know how to write a function that returns user information corresponding to a given address, but I'd also like to write a function that can grab user info by the User's email address.

How does this work? Is my only option to create a separate mapping for this use-case that maps the User struct to a string? If so, does this mean the struct gets stored two times? Or does it only store references to that struct?

Thanks!

Upvotes: 4

Views: 2270

Answers (1)

Adam Kipnis
Adam Kipnis

Reputation: 11001

If you want to do a search by either address or email (ie, NOT a composite key), then yes, the simplest option is to use two different mappings. However, struct values are stored as copies (see this for information on how mappings are stored).

To avoid extra storage for complex structs, store it in an array and use the index for the mapping values.

contract UserContract {
    struct User {
        address walletAddress;
        string organisation;
        string fName;
        string lName;
        string email;
        uint index;
    }
    User[] users;
    mapping(address => uint256) private addressMap;
    mapping(string => uint256) private emailMap; // Note this must be private if you’re going to use `string` as the key. Otherwise, use bytes32
    address[] private userIndex;
}

Upvotes: 4

Related Questions