Yauheni
Yauheni

Reputation: 196

Hibernate Search. Exclusion from indexing records with specific properties

I have two entites, Book:

@Entity
@Indexed
public class Book extends BaseEntity {
@Field
@Analyzer(definition = "customanalyzer")
private String subtitle;
private boolean prohibited;

@DateBridge(resolution = Resolution.DAY)
private Date publicationDate;

@IndexedEmbedded
@ManyToMany(fetch = FetchType.EAGER)
@Cascade(value = {CascadeType.ALL})
private List<Author> authors = new ArrayList<Author>();

public Book() {
}

and Author

@Entity
@Indexed
@Analyzer(impl = EnglishAnalyzer.class)
public class Author extends Identifiable<Long> {
@Field
private String name;

I must find only that the author whose book is not prohibited. If I invoke that query

QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(c).get();
    Query luceneQuery = qb
            .keyword()
            .fuzzy()
            .onFields("name")
            .matching(q)
            .createQuery();

    FullTextQuery createFullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, Author.class);

The question is, how can I understand what the author of the book is prohibited? Maybe something like a query, you can add a condition to the search was only in those books that are not banned? Or how to do something so that luсene not index forbidden books?

Upvotes: 0

Views: 1234

Answers (1)

Atul Kumar
Atul Kumar

Reputation: 749

You can do this by implementing EntityIndexingInterceptor and then define the implentation in your domain class as:

@Indexed(interceptor=BookIndexingInterceptor.class)
public class Book extends BaseEntity{

Example of implementation is as below:

   public class BookIndexingInterceptor implements
        EntityIndexingInterceptor<Book> {
    @Override
    public IndexingOverride onAdd(Book entity) {
        if(entity.prohibited == true)
            return IndexingOverride.SKIP;

        return IndexingOverride.APPLY_DEFAULT;
    }

    @Override
    public IndexingOverride onUpdate(Book entity) {
        if(entity.prohibited == true)
            return IndexingOverride.REMOVE;

        return IndexingOverride.APPLY_DEFAULT;
    }

    @Override
    public IndexingOverride onDelete(Book entity) {
        return IndexingOverride.APPLY_DEFAULT;
    }

    @Override
    public IndexingOverride onCollectionUpdate(Book entity) {
        if(entity.prohibited == true)
            return IndexingOverride.REMOVE;

        return IndexingOverride.APPLY_DEFAULT;
    }
}

Upvotes: 3

Related Questions