Optimize terms autocomplete query, refs #5858