refactored the message querying by key logic