8

Hibernate search is sorting results depending on relevance, it is normal. In addition to that, if two documents are having the same score, they are ordered by their primary keys.

For example,

book1 : id=1, bookTitle = "hibernate search by example".

book2 : id=2, bookTitle = "hibernate search in action"

If I am doing a query to look for terms "hibernate search", I would have this order : book1 then book2

I would like to invert this order : book2 then book1. Which means inverting primary key order. Is there a possible way to do this without implementing a custom Similarity ? At the same time keeping relevance order.

Bilal BBB
  • 1,154
  • 13
  • 20

1 Answers1

11

Yes, you need to create a Sort object which specifies the desired sorting, and set it in your query. See Section 5.1.3.3 of the Hibernate docs. Then, in the list of SortFields pass SortField.FIELD_SCORE. SortField's constructor also allows you to reverse the order.

org.hibernate.search.FullTextQuery query = s.createFullTextQuery( luceneQuery, MyEntity.class );
org.apache.lucene.search.Sort sort = new Sort(
    SortField.FIELD_SCORE, 
    new SortField("id", SortField.STRING, true));
query.setSort(sort);
List results = query.list();
femtoRgon
  • 32,893
  • 7
  • 60
  • 87
  • If I use a Sort object, do I keep scoring order of hibernate search ? In the example above, if I look for "hibernate search", a document with id = 3 which contains only the term "hibernate" would be sorted third after id = 2 and id = 1 ? Even if I invert Id order ? – Bilal BBB May 13 '15 at 21:42
  • I said this because I tried ("id", SortField.LONG, true), it works fine but the order depends only on id and not on id and document score – Bilal BBB May 13 '15 at 21:44
  • That's why the first `SortField` in the Sort ctor needs to be `SortField.FIELD_SCORE`. That tells it to sort by score first. – femtoRgon May 13 '15 at 21:44
  • Thanks I didn't see it, I'll try it – Bilal BBB May 13 '15 at 21:45
  • what if I want only 10 records, sorted by score, asc or desc based on input params ? – Dax Joshi Dec 30 '15 at 05:43
  • @DaxJoshi See the [Hibernate Search docs](https://docs.jboss.org/hibernate/search/3.3/reference/en-US/html/search-query.html) on the first point, the [SortField docs](https://lucene.apache.org/core/5_3_1/core/index.html?org/apache/lucene/search/SortField.html) on the second (though I fail to see why on earth you would want to give the user the option to sort *worst first*). If you still have questions, you can ask by clicking the button at the top right. – femtoRgon Dec 30 '15 at 16:40