Lucene中DateField的Date限制

类别:Java 点击:0 评论:0 推荐:

在实际使用在发现Lunene中对利用时间范围做查询时是有限制的.也就是说要查询的时间不可能无穷的小,也不可能无穷的大.在他的文档中可以找到这句话:
org.apache.lucene.document.DataField
dates before 1970 cannot be used, and therefore cannot be indexed when using this class
1970是格林尼治时间的开始.如果需要被加如索引的时间在1970年之前,则不能使用.
再来看看的源码
package org.apache.lucene.document;

import java.util.Date;

public class DateField {
  private DateField() {}

  // make date strings long enough to last a millenium
  private static int DATE_LEN = Long.toString(1000L*365*24*60*60*1000,
            Character.MAX_RADIX).length();

  public static String MIN_DATE_STRING() {
    return timeToString(0);
  }

  public static String MAX_DATE_STRING() {
    char[] buffer = new char[DATE_LEN];
    char c = Character.forDigit(Character.MAX_RADIX-1, Character.MAX_RADIX);
    for (int i = 0 ; i < DATE_LEN; i++)
      buffer[i] = c;
    return new String(buffer);
  }

  /**
   * Converts a Date to a string suitable for indexing.
   * @throws RuntimeException if the date specified in the
   * method argument is before 1970
   */
  public static String dateToString(Date date) {
    return timeToString(date.getTime());
  }
  /**
   * Converts a millisecond time to a string suitable for indexing.
   * @throws RuntimeException if the time specified in the
   * method argument is negative, that is, before 1970
   */
  public static String timeToString(long time) {
    if (time < 0)
      throw new RuntimeException("time too early");

    String s = Long.toString(time, Character.MAX_RADIX);

    if (s.length() > DATE_LEN)
      throw new RuntimeException("time too late");

    // Pad with leading zeros
    if (s.length() < DATE_LEN) {
      StringBuffer sb = new StringBuffer(s);
      while (sb.length() < DATE_LEN)
        sb.insert(0, 0);
      s = sb.toString();
    }

    return s;
  }

  /** Converts a string-encoded date into a millisecond time. */
  public static long stringToTime(String s) {
    return Long.parseLong(s, Character.MAX_RADIX);
  }
  /** Converts a string-encoded date into a Date object. */
  public static Date stringToDate(String s) {
    return new Date(stringToTime(s));
  }
}
是不是很郁闷,不知道作者为什么要做这样的限制.java.util.Date类的限制是可以到1900年的(没有验证过.如果不对各位可以拍砖).
不过开源的好处就是可以改源码.呵呵.把上面对时间的限制去掉后重新编译打包.一切OK,世界霎时安静了

PS:修改的目的是为了对一些一九五几年的图片做时间索引,如果没有这种需求可以不用修改.我想作者对此做了限制应该是有他的道理的.改天去他的maillist那里问问.

本文地址:http://com.8s8s.com/it/it11794.htm