proceder
proceder

Reputation: 57

Hibernate Search - search in ManyToOne relation

I have two indexed entities. Player:

@Indexed
@Entity
public class Player {

    @Field
    private String firstName;

    @ContainedIn
    @ManyToOne
    private Club playersClub;

}

and Club:

@Indexed
@Entity
public class Club {

    @Fields({
        @Field(store=Store.COMPRESS),
        @Field(name = "sorting_name", analyze = Analyze.NO)
    })
    private String name;

    @IndexedEmbedded(depth = 1)
    @OneToMany(mappedBy = "playersClub")
    private Set<Player> players;

}

Now when I search into ClubSearchService like this:

luceneQuery = queryBuilder
                    ...
                    .onField("name").andField("players.firstName")
                    ...

it works fine, but when I want search in other way(PlayerSearchService):

               .onField("firstName").andField("lastName").andField("number").andField("country").andField("playersClub.name")

there is an error

org.hibernate.search.SearchException: Unable to find field playersClub.name in pl.domain.Player

Hibernate Search cannot search into ManyToOne item?

Upvotes: 2

Views: 3083

Answers (1)

Sanne
Sanne

Reputation: 6107

Yes it is possible to index ManyToOne relations as well.

In most simple cases you have one entity such as Club marked as @Indexed and then you want to index some of its fields and also embed via @IndexedEmbedded attributes from a related entity Player.

So far you got it right, and this is defining essentially the "flattened" schema for your club index.

The problem is that when defining the schema for the player index you marked firstname as an indexed field, but didn't instruct it to embed the relation to playersClub. Essentially you're missing the @IndexedEmbedded on this property.

To not be confused with the @ContainedIn annotation: this is purely to make sure that Hibernate Search will re-index the entities in which it is contained; it is not making both sides embedding each other in a symmetric way.

In more formal terms, the relation established by @IndexedEmbedded is a directed graph: if you want it to follow both directions you have to establish them both explicitly.

Upvotes: 4

Related Questions