Dimitri
Dimitri

Reputation: 8280

Solrj Date request

How to request by date using SolrJ?

I get as a parameter a date in this format '01/10/2014'. Then I convert this format to a Date object and convert the object to a UTC format. Here is a code example of what I am doing :

public class DateHelper {
    public static final String DD_MM_YYYY_FORMAT = "dd/MM/yyyy";
    public static final String SOLR_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    public static Date getDateFromString(String date, String format) {
        if (StringUtils.isNotEmpty(date)) {
            try {
                return FastDateFormat.getInstance(format).parse(date);
            } catch (ParseException e) {
                LOGGER.error(e.getMessage());
            }
        }
        return null;
    }

    public static String getStringFromDate(Date date, String format) {
        if (date != null) {
            try {
                return FastDateFormat.getInstance(format).format(date);
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            }
        }
        return "";
    }        

    public static void main(String...args){
        Date dateFromString = DateHelper.getDateFromString('01/10/2014', DateHelper.DD_MM_YYYY_FORMAT);
        String date = DateHelper.getStringFromDate(dateFromString, DateHelper.SOLR_DATE_FORMAT);
        System.out.println(date);
    }
}

This small program displays '2014-10-01T00:00:00Z'. When I try to submit this date in Solr using a filter query, I receive this error from Sorl :

org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: Invalid Date String:'2014-10-01T00'

Here is my Solr query :

SolrQuery solrQuery = new SolrQuery("*:*");
String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);

getSolrServer().query(solrQuery, METHOD.POST);

How can I solve this problem? THx for your help.

P.S : The class FastDateFormat is from Apache Commons Lang 3. I am using solr version 4.8.1.

Upvotes: 0

Views: 3533

Answers (2)

Manish Jain
Manish Jain

Reputation: 15

Syntax to query solr date field -- Date:[YYYY-MM-DDTHH:mm:ssZ]

Upvotes: 0

rchukh
rchukh

Reputation: 2947

This happens because of the way filterQuery is created:

String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);

That way the solr gets:

date:2014-10-01T00:00:00Z

And the exception is thrown because of the multiple : symbols that the Query Parser cannot parse correctly.


In order to fix it the special characters that are part of Query Syntax should be escaped.

From the java side it can be done this way (using ClientUtils.escapeQueryChars from SolrJ):

String date = String.format( "date:%s", ClientUtils.escapeQueryChars(dateInput));
query.addFilterQuery(date);

Upvotes: 2

Related Questions