see search implementation https://github.com/dimagi/commcare-hq/blob/master/corehq/apps/hqwebapp/views.py#L853