Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lucene sort by score and then modified date

Tags:

lucene

I have three fields in my document

  1. Title
  2. Content
  3. Modified Date

So when I search a term it's giving by results sorted by score

Now I would like to further sort the results with same score based upon on modifiedDate i.e. showing recent documents on top with the same score.

I tried sort by score, modified date but it's not working. Anyone can point me to the right direction?

like image 585
TheCodingFrog Avatar asked Jan 07 '23 02:01

TheCodingFrog


1 Answers

This can be done simply by defining a Sort:

Sort sort = new Sort(
    SortField.FIELD_SCORE, 
    new SortField("myDateField", SortField.Type.STRING));
indexSearcher.search(myQuery, numHits, sort);

Two possible gotchas here:

  • You should make sure your date is indexed in a searchable, and sortable, form. Generally, the best way to accomplish this is to convert it using DateTools.

  • The field used for sorting must be indexed, and should not be analyzed (a StringField, for instance). Up to you whether it is stored.

So adding the date field might look something like:

Field dateField = new StringField(
    "myDateField", 
    DateTools.DateToString(myDateInstance, DateTools.Resolution.MINUTE),
    Field.Store.YES);
document.add(dateField);

Note: You can also index dates as a numeric field using Date.getTime(). I prefer the DateTools string approach, as it provides some nicer tools for handling them, particularly with regards to precision, but either way can work.

like image 52
femtoRgon Avatar answered Jan 18 '23 23:01

femtoRgon