I have three fields in my document
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With