Sorting search result in Lucene based on a numeric field

Below line will do the trick. Last parameter is boolean reverse if you set it to true it will sort in reverse order i.e. descending in your case.

  SortField longSort = new SortedNumericSortField(FIELD_NAME_LONG, SortField.Type.LONG, true);

Sample code:

  IndexSearcher searcher = new IndexSearcher(reader);
  Query q = new MultiFieldQueryParser(new String[] { FIELD_NAME_NAME}, analyzer).parse("YOUR_QUERY") );

  SortField longSort = new SortedNumericSortField(FIELD_NAME_LONG, SortField.Type.LONG, true);

  Sort sort = new Sort(longSort);
  ScoreDoc[] hits = searcher.search(q, 10 , sort).scoreDocs;

Also it's necessary that you add you sort enabled field as a NumericDocValuesField when you create your index.

 doc.add(new NumericDocValuesField(FIELD_NAME_LONG, longValue));//sort enabled field

Code is as per lucene-core-5.0.0


first:

Fieldable count = new NumericField("count", Store.YES, true);

second:

SortField field = new SortField("count", SortField.INT);
Sort sort = new Sort(field);

third:

TopFieldDocs docs = searcher.search(query, 20, sort);
ScoreDoc[] sds = docs.scoreDocs;

Like this is OK !


The default search implementation of Apache Lucene returns results sorted by score (the most relevant result first), then by id (the oldest result first).

This behavior can be customized at query time with an additionnal Sort parameter .

TopFieldDocs Searcher#search(Query query, Filter filter, int n, Sort sort)

The Sort parameter specifies the fields or properties used for sorting. The default implementation is defined this way :

new Sort(new SortField[] { SortField.FIELD_SCORE, SortField.FIELD_DOC });

To change sorting, you just have to replace fields with the ones you want :

new Sort(new SortField[] {
SortField.FIELD_SCORE,
new SortField("field_1", SortField.STRING),
new SortField("field_2", SortField.STRING) });

This sounds simple, but will not work until the following conditions are met :

  • You have to specify the type parameter of SortField(String field, int type) to make Lucene find your field, even if this is normaly optional.
  • The sort fields must be indexed but not tokenized :

    document.add (new Field ("byNumber", Integer.toString(x), Field.Store.NO, Field.Index.NOT_ANALYZED));

  • The sort fields content must be plain text only. If only one single element has a special character or accent in one of the fields used for sorting, the whole search will return unsorted results.

Check this tutorial.

Tags:

Java

Lucene