Sorting search result in Lucene based on a numeric field

前端 未结 3 914
粉色の甜心
粉色の甜心 2020-12-15 10:53

I have some docs with two fields: text, count.

I\'ve used Lucene to index docs and now I want to search in text and get the result sorted by count in de

3条回答
  •  离开以前
    2020-12-15 11:41

    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

提交回复
热议问题