简体   繁体   中英

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.

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

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);

查询Solr日期字段的语法- Date:[YYYY-MM-DDTHH:mm:ssZ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM