Search code examples
hibernate-search

Sorting on embedded entity name in hibernate search


I have the following Entity definitions.

public class Order {
    @Id
    @DocumentId
    private Long id;

    @Field
    @IndexedEmbedded(includePaths = {"name"})
    @OneToOne
    @JoinColumn(name = "ACCOUNT_ID")
    private Account account;

    // the rest are omitted for brevity purpose
}

public class Account {
    @Id
    @DocumentId
    private Long id;

    @SortableField(forField = "name_Sort")
    @Field(name = "name_Sort", store = Store.YES, normalizer= @Normalizer(definition = SearchConstants.LOWER_CASE_NORMALIZER))
    @Column(name = "NAME")
    private String name;    
}

If I search on Order and want to have the search results sorted by account name, is there good way of doing so possibly using the embedded indexed annotation? I know we can do it by adding an extra string field in Order that is called accountName, then just add sorting annotation on top of that. Is it possible to achieve this without specifying the sorting annotation in Order but just use the sorting annotation that is already defined in Account?


Solution

  • Change this:

        @IndexedEmbedded(includePaths = {"name"})
    

    To this:

        @IndexedEmbedded(includePaths = {"name", "name_Sort"})
    

    Then you can use the field account.name_Sort for sorts on orders:

    QueryBuilder builder = fullTextSession.getSearchFactory()
        .buildQueryBuilder().forEntity( Order.class ).get();
    Query luceneQuery = /* ... */;
    FullTextQuery query = s.createFullTextQuery( luceneQuery, Order.class );
    query.setSort(
        builder.sort().byField("account.name_Sort").createSort()
    );
    List results = query.list();