2 September 2011

Why NumericField displayed null instead of time in miliseconds during search ?

Solution works for Lucene 3.3.0 (might works for other version too)

On internet you can find some example that to add NumericField to Document  like that:
doc.add(new NumericField("timestamp").setLongValue(Calendar.getInstance().getTimeInMillis()));

and that's it.However,when you try use NumericField in Search (to display this lovely date), then you see null instead of date and you think this example are cockamamies.

(Example of example from "Lucene in (slow like turtle or more ofthen no) Action ")
"Chances are, like many other Lucene users, you’ll need to index dates and times. Such  values are easily handled by first converting them to an equivalent int or long value, and then indexing  that value as a number. The simplest approach is to use Date.getTime to get the equivalent value, in  millisecond precision, for a java Date object:  doc.add(new NumericField("timestamp").setLongValue(new Date).getTime())); "
Source: Michael McCandless, Erik Hatcher, and Otis Gospodnetić Lucene in Action  (Manning,2010)

Most of example forgot to add interesting information that ....
"By default, a NumericField's value is not stored but is indexed for range filtering and sorting. You can use the NumericField(String,Field.Store,boolean) constructor if you need to change these defaults."
(SOURCE:  http://lucene.apache.org/java/3_3_0/api/all/index.html?org/apache/lucene/document/NumericField.html )

So how should looks example?

  doc.add(new NumericField("timestamp",Field.Store.NO,true).setLongValue(Calendar.getInstance().getTimeInMillis()));

  Remember to keep smiling :)