Recent Documents First in Apache Lucene

Recent Documents First in Apache Lucene

Phill Luby
22nd September 2012

Home Insights Recent Documents First in Apache Lucene

Having spent a long time looking for how to put the latest documents first in Apache Lucene to no avail. Finally, I’ve found a solution that works.

Most of the answers on the web suggested using a boost on documents based on their date. However, I was unconvinced how these solutions would pan out in the long term. The other day, I came across Apache Lucene Sort Tips which describes how to use the TopFieldDocCollector. By chance it mentioned the constant SortField.FIELD_SCORE that can be used when constructing a multi-field Sort object.

So, the answer is simple, but I thought I’d write a post specifically addressing this use-case so that an answer is easy for others to find. You need a field containing the modified date of all your documents. Storing this as an ISO 8601 string does the trick. Now you construct a sort object passing SortField.FIELD_SCORE as the first field and your date field (descending) as the second and hey presto!

So, here’s how we create our sort:

var sort = new Sort(new\[\] {
    SortField.FIELD\_SCORE,
    new SortField("last\_modified", SortField.STRING, true)});

And use this with a TopFieldDocCollector in the usual way.

Massive thanks to the author of the original post. I just thought it was worth posting something specifically for this use-case.

Share Article

Insights.

Exciting News! Agile Yorkshire Shortlisted for Leeds Digital Festival Awards
Exciting News! Agile Yorkshire Shortlisted for Leeds Digital Festival Awards

a community we’ve proudly supported for over a decade

Discover More
Ada Lovelace Day: A Celebration of Women in Tech!
Ada Lovelace Day: A Celebration of Women in Tech!

This event will explore and promote strategies for increasing accessibility to technology careers for individuals from disadvantaged communities.

Discover More
An A-Level Student's First Journey into the World of Work: Jai Soni's Inspiring Week at NewRedo
An A-Level Student's First Journey into the World of Work: Jai Soni's Inspiring Week at NewRedo

“This week has been an eye-opening experience. I’ve learned so much from Alan and the team, not just about engineering but also about how our work can make a real difference. It’s been incredibly inspiring,”

Discover More