Refactored the code, generating ES query.