Search UI Set Sort Dynamically

Hi all - I am using the React Search UI with Elastic Cloud. I am looking for a way to set the search results order dynamically based on if the search box is populated. The logic is:

  • Always default to a sort of date desc if the search box is empty (on initial page load, even if facet filters are selected, etc)
  • Once the search box is populated the sorting should switch to _score desc
  • If the search box is cleared sorting should go back to date desc

Thanks in advance.

Hi there,

You can use the onSearch hook to change the request state before its called. Below is an example of how you would implement your request:

onSearch: (requestState, queryConfig, next) => {
    let updatedState = requestState;
    if (requestState.searchTerm === "" && requestState.sortList.length === 0) {
      updatedState = {
        ...requestState,
        sortList: [{ field: "date_established", direction: "desc" }]
      };
    }
    return Promise.resolve(next(updatedState, queryConfig));
  },

To highlight:

  • using date_established as an example. You can change this to any date field you require
  • Will only add the sorting option if search term is empty
  • Will not override the existing sort option

and it working in codesandbox vigilant-blackwell-3d3478 - CodeSandbox

Hope this helps!

Thank you @joemcelroy that is exactly what I was looking for. Is there a documentation page for onSearch? I can't seem to find one.

Good to hear! You can find the documentation about this hook and others here SearchProvider | Elastic docs

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.