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?

1 Answer 1

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<>();
Sign up to request clarification or add additional context in comments.

1 Comment

Good point, I've opened hibernate.atlassian.net/browse/HSEARCH-1971 to improve on this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.