Hibernate搜索。从具有特定属性的索引记录中排除

时间:2014-11-19 19:25:59

标签: hibernate lucene hibernate-search

我有两个人,书:

@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() {
}

和作者

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

我必须只找到那本书不被禁止的作者。如果我调用该查询

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);

问题是,我如何理解禁止该书的作者?也许像查询一样,你可以在搜索中添加一个条件只在那些没有被禁止的书中?或者如何做一些事情,以便luсene不索引禁书?

1 个答案:

答案 0 :(得分:2)

您可以通过实施EntityIndexingInterceptor来完成此操作,然后将域类中的实施定义为:

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

实施示例如下:

   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;
    }
}