REFACTOR code for es terms query