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:

@Overridepublic
 void doBeforeRender(final HstRequest request,
                           final HstResponse response)
                                             throws HstComponentException {
  HippoSolrClient solrClient =
      HstServices.getComponentManager().getComponent(
                    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?