Implement a Date range query

By default, Solr supports efficient date range queries by using TrieRange (NumericRangequery). TrieRange logic is supported for int, float, long, double and date fields. By default, the fieldType names for these are:

<fieldType name="tint" class="solr.TrieIntField" precisionStep="8"
                         omitNorms="true" positionIncrementGap="0"/>
<fieldType name="tfloat" class="solr.TrieFloatField" precisionStep="8"
                         omitNorms="true" positionIncrementGap="0"/>
<fieldType name="tlong" class="solr.TrieLongField" precisionStep="8"
                         omitNorms="true" positionIncrementGap="0"/>
<fieldType name="tdouble" class="solr.TrieDoubleField" precisionStep="8"
                         omitNorms="true" positionIncrementGap="0"/>
<fieldType name="tdate" class="solr.TrieDateField" precisionStep="6"
                         omitNorms="true" positionIncrementGap="0"/>

Now, if you have indexed your data as a t* field, it can be used in range queries efficiently (without indexing it as TrieRange field you can still use range queries).

So, assume you have a bean that contains:

@IndexField
public Calendar getDate() {
  return getProperty("example:date");
}

and in your Solr schema.xml you have defined:

<field name="date" type="tdate" indexed="true" stored="true" />

then you can do range queries as follows:

Range query:

HippoSolrClient solrClient =
      HstServices.getComponentManager().getComponent(
                    HippoSolrClient.class.getName(), "org.hippoecm.hst.solr");
HippoQuery hippoQuery = solrClient.createQuery(query);
Date from = ...;
Date to = ...
String fromDate;
if (from == null) {
    fromDate = "*";
} else {
    fromDate = org.apache.solr.common.util.DateUtil.
                                    getThreadLocalDateFormat().format(from);
}
String toDate;
if (to == null) {
    toDate = "*";
} else {
    toDate = org.apache.solr.common.util.DateUtil.
                                    getThreadLocalDateFormat().format(to);
}
query = query + " AND date:["+fromDate+" TO " + toDate + "]";
log.debug("Date range added to query : '{}'", query);
HippoQueryResult result = hippoQuery.execute();
request.setAttribute("result", result);
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?