devkuzmin
devkuzmin

Reputation: 13

Using a Lucene Filter in Hibernate search

I have a class Item. Item has 'status' property. The status can be 'A' - active and 'I' - inactive. Time to time the status changes. Item has some other properties e.g. 'name' etc. that can be indexed. Users of the application can search items by name etc. After that they are shown with a list of relevant items. Inactive items should not be shown.

To filter out inactive items I declared a filter:

@FullTextFilterDef(name = "statusFilter", impl = StatusFilterFactory.class)
public class Item
{ ... }


public class StatusFilterFactory {

  @Factory
  public Filter getFilter() {
    BooleanQuery query = new BooleanQuery();
    Term statusTerm = new Term("status", "A");
    query.add(new TermQuery(statusTerm), BooleanClause.Occur.MUST);
    return new CachingWrapperFilter(new QueryWrapperFilter(query));
  }
}

And when I need to create a list of items I use enableFullTextFilter("statusFilter") method:

fullTextQuery.setSort(sort).setFirstResult(offset).setMaxResults(limit).enableFullTextFilter("statusFilter");

but if I don't use this method, I have the same result. The inactive items are filtered out.

The questions are:

  1. Do I need to declare this filter? or I can use it directly (how?).
  2. It seems the newly created inactive items are not indexed at all. Why? How does declaration of a filter affect the indexing?

Thanks in advance.

Upvotes: 1

Views: 2576

Answers (1)

Sanne
Sanne

Reputation: 6107

1.

If you don't want to use @FullTextFilterDef you can use

org.hibernate.search.FullTextQuery.setFilter(Filter)

But the declarative definition is recommended, as the above method is semi-deprecated and being considered to be removed. (Actually please let us know if you really need it to stay).

2.

No, a Filter instance has no effect on index updates. Something else is affecting your test, for example don't forget that index updated are performed at commit time, not before.

Alternatives

You might also want to consider using an indexing interceptor. The effect compared to a Filter is similar:

  • When using an interceptor you keep the index smaller, it might be more efficient.
  • When using the Filter you have the option to allow searching for inactive entries; this might be useful if in a different use case you need to allow searching for inactive Items as well.

Upvotes: 1

Related Questions