tags:

views:

309

answers:

3

Is it possible to search on date ranges using Lucene in Java? How do I build Lucene search queries based on date fields and dates ranges? For example:

  • between specified dates
  • prior to a specified date
  • after a specified date
  • within the last 24 hours
  • within the past week
  • within the past month.

[Edit] i'm using Lucene 2.4.1 and my system is really legacy and really poorly tested so i would like if possible not to have to upgrade

A: 

Yes it is possible. If you need some sample code I'll find some for you - just ask in comment to this post.

Have a look at Lucene in Action - you can find answer to this question and many others also.

Trickster
+2  A: 

Lucene 2.9+ comes with a special query intended for that: http://www.lucidimagination.com/blog/tag/range-queries/

For date ranges you'd convert them into UNIX timestamps. The linked blog describes the idea, on the references you'll also find the presentation from Uwe Schindler describing it in more detail.

ankon
+3  A: 

Lucene (before version 2.9 anyway) only stores String values, and it only supports lexographic range queries on that data. So if you want to store date/time data and performa range queries on it, you need to explicitly format your data/time values in such a way as to make them lexographically ordered.

For example, store your date/times as something like 2009-10-29T15:34:00, and then do range queries like [2009-10-29T15:00:00 TO 2009-10-29T16:00:00]

As has been pointed out elsewhere, Lucene 2.9 finally introduced support for range queries against non-string data, making this all rather easier.

skaffman