Random sort

Sometimes, you want the results returned from a query to be sorted at random: For example, whenever you want to show at random 10 news items, or, at random 3 banners out of a set of hundreds.

This can be achieved very easily with Solr by using type="random" combined with a dynamicField :

In schema.xml make sure you have:

<dynamicField name="random_*" type="random" />

And in your search code, make sure you add something like:

Sort at random:

 void doBeforeRender(final HstRequest request,
                           final HstResponse response)
                                             throws HstComponentException {
  HippoSolrClient solrClient =
                    HippoSolrClient.class.getName(), "org.hippoecm.hst.solr");
  HippoQuery hippoQuery = solrClient.createQuery(query);
  // we map the sort now to <dynamicField name="random_*" type="random" />
  // to get a pseudo random search for every new request, we need to map to a
  // 'random' dynamic sort field : Otherwise the same random sort keeps being
  // returned as long as the index does not change. We assume 10 random
  // fields is enough
  sort = "random_" + new Random().nextInt(10);
  hippoQuery.getSolrQuery().addSortField(sort, SolrQuery.ORDER.asc);
  HippoQueryResult result = hippoQuery.execute();
Did you find this page helpful?
How could this documentation serve you better?
On this page
    Did you find this page helpful?
    How could this documentation serve you better?

    We rely on cookies

    to optimize our communication and to enhance your customer experience. By clicking on the Accept and Close button, you agree to the collection of cookies. You can also adjust your preferences by clicking on Manage Preferences. For more information please see our Privacy policy.

    Manage cookies
    Accept & close

    Cookies preferences

    Accept & close