Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort dynamic choice list search results by relevance #35494

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions corehq/apps/userreports/reports/filters/choice_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from django.utils.functional import cached_property
from django.utils.translation import gettext

from sqlalchemy import or_
from sqlalchemy import or_, case
from sqlalchemy.exc import ProgrammingError

from corehq.apps.domain.models import Domain
Expand Down Expand Up @@ -195,9 +195,11 @@ def _sql_column(self):
def get_values_for_query(self, query_context):
query = self._adapter.session_helper.Session.query(self._sql_column)
if query_context.query:
query = query.filter(self._sql_column.ilike("%{}%".format(query_context.query)))
query = self._apply_query_filter(query, query_context)
else:
query = query.distinct().order_by(self._sql_column)

query = query.distinct().order_by(self._sql_column).limit(query_context.limit).offset(query_context.offset)
query = query.limit(query_context.limit).offset(query_context.offset)
try:
values = [v[0] for v in query]
self._adapter.track_load(len(values))
Expand All @@ -211,6 +213,19 @@ def get_choices_for_known_values(self, values, user):
def default_value(self, user):
return None

def _apply_query_filter(self, query, query_context):
query = query.filter(self._sql_column.ilike("%{}%".format(query_context.query)))
# We need to sort this by relevance, otherwise we might
# be pushing the most exact matches to the end of the list
# and cut it off by applying the limit
return query.distinct().order_by(
case([
(self._sql_column.ilike(query_context.query), 0), # Exact matches first
(self._sql_column.ilike(f"%{query_context.query}%"), 1)], # Substring matches
else_=2 # Everything else
).asc()
)

def _make_choice_from_value(self, value):
if value is None or value == '':
return Choice(NONE_CHOICE, '[Blank]')
Expand Down
Loading