3

I have the model below and I'm trying to use Hibernate Search for full text search.

I need to search into the "about" field for all the users with the UserRole.PROFESSIONIST role.

This is the model:

@Entity
@Indexed
public class User
{
    @Id
    @GeneratedValue
    Long id;

    ...

    String about;

    @IndexedEmbedded
    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = UserRole.class, fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles", joinColumns = {@JoinColumn(name = "user_id")})
    List<UserRole> roles = new ArrayList<>();
}    

This is the query:

List results = new ArrayList<>();

org.apache.lucene.search.Query containText = queryBuilder
    .keyword()
    .onField("about")
    .matching(text)
    .createQuery();

org.apache.lucene.search.Query isProfessionist = queryBuilder
    .keyword()
    .onFields("roles")
    .matching(UserRole.PROFESSIONIST.toString())
    .createQuery();

org.apache.lucene.search.Query query = queryBuilder
    .bool()
    .must(containText)
    .must(isProfessionist)
    .createQuery();

org.hibernate.search.jpa.FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, User.class);

results = jpaQuery.getResultList();

When I execute the query I get this error:

org.hibernate.search.exception.SearchException: Unable to find field roles in com.plusimple.core.models.User

Is what I'm trying to do possible? And if yes, what am I doing wrong?

Francesco Papagno
  • 617
  • 10
  • 29

1 Answers1

4

Since the target class is an enum, you'll have to add a @Field annotation to the property you want searchable (this doesn't need to be done when embedding full entities, as they have their own child properties that would be searchable).

Example:

@IndexedEmbedded
@Field(name="roles", analyze=Analyze.NO, index=Index.YES)
@Enumerated(EnumType.STRING)
@ElementCollection(targetClass = UserRole.class, fetch = FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = {@JoinColumn(name = "user_id")})
List<UserRole> roles = new ArrayList<>();
RandomMooCow
  • 734
  • 9
  • 23
  • 1
    Good point, I've opened https://hibernate.atlassian.net/browse/HSEARCH-1971 to improve on this. Thanks! – Sanne Aug 20 '15 at 19:58