1

如何使用 spring data solr 舍入日期过滤器查询?

我想fq=startDate:[2013-06-14T23:59:59.999Z/DAY TO 2013-06-14T23:59:59.999Z/DAY]使用FilterQuery.

如何使用以下查询四舍五入FilterQuery

FilterQuery filterQuery = new SimpleFilterQuery();
filterQuery.addCriteria(new Criteria(EventDocument.FIELD_START_DATE).between(sc.getStartDate(), sc.getStartDate()));

任何提示将不胜感激。

4

1 回答 1

3

最简单的可能是使用SimpleStringCriteria

String start = JavaDateConverter.INSTANCE.convert(sc.getStartDate())+"/DAY";
String end = JavaDateConverter.INSTANCE.convert(sc.getEndDate())+"/DAY";
Criteria criteria = new SimpleStringCriteria("[" + start + " TO " + end + "]");

更复杂的是注册一个自定义转换器

@Configuration
@EnableSolrRepositories
public class SolrContext {

  //..skipped solr server initialization to shorten

  @Bean
  public SolrTemplate solrTemplate() throws Exception {
    SolrTemplate solrTemplate = new SolrTemplate(solrServerFactory());
    solrTemplate.setSolrCore("collection1"); 
    solrTemplate.registerQueryParser(SimpleQuery.class, queryParser());
    return solrTemplate;
  }

  @Bean  
  public QueryParser queryParser() {
    DefaultQueryParser queryParser = new DefaultQueryParser();

    //register custom converter for Date
    queryParser.registerConverter(RoundDayConverter.INSTANCE);
    return queryParser;
  }

  private enum RoundDayConverter implements Converter<Date, String> {
    INSTANCE;

    private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.dateTime().withZoneUTC();

    @Override
    public String convert(Date source) {
      if (source == null) {
        return "";
      }

      return ClientUtils.escapeQueryChars(FORMATTER.print(source.getTime())) + "/DAY";
    }
  }
}

由于上述内容适用于每个人Date,因此创建自定义类型并为此注册转换器可能是个好主意。

于 2014-01-27T07:00:19.430 回答