Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

java - Sorting search result in Lucene based on a numeric field

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 descending order. How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...