logeyg
logeyg

Reputation: 559

Discriminator Based Multi-Tenancy Filtering Using Hibernate Search

I am attempting to add full text search to an entity using hibernate-search. Our schema uses discriminator based multi-tenancy, where each tenant is a park with an id. The model looks like this:

@Entity
@Indexed
public class ProductModel {
  @Field
  // park is the tenant 
  private Long parkId;

  @Field(index = Index.YES, analyze = Analyze.YES)
  @Analyzer(definition = "customanalyzer")
  private String name;

  @Field(index = Index.YES, analyze = Analyze.YES)
  @Analyzer(definition = "customanalyzer")
  private String description;
}

When performing full text search, I will always be filtering based on a parkId. Would it make sense to annotate the parkId with @Field, and then add that filter to the lucene query like so:

org.apache.lucene.search.Query luceneQuery = qb
  .bool()
    .must(qb.keyword().onFields("parkId").matching(parkIdFilter)) 

    // any aditional queries, like on name, description
   .must(qb.keyword().onFields(fields).matching(textQuery).createQuery())
  .createQuery();

Or is there a better way to handle multi-tenancy using hibernate search with discriminator columns? I've seen the example mentioned in the docs but don't know how to apply that to my particular use case.

Upvotes: 0

Views: 1290

Answers (1)

yrodiere
yrodiere

Reputation: 9977

The easiest path would be to use Hibernate ORM's built-in multi-tenancy support, which is currently limited to either schema-based or database-based multi-tenancy. If you do, Hibernate Search will handle multi-tenancy automatically, no need for you to do anything special.

I must admit Hibernate ORM's doc is a bit puzzling, since the discriminator strategy is mentioned, but not implemented. I think (not sure) that you can set the hibernate.multiTenancy property to DISCRIMINATOR, and the only effect will be that Hibernate ORM will require you to use tenant IDs every time you open a session.

If that is the case (you will have to check), then you could do just that: set the hibernate.multiTenancy property to DISCRIMINATOR, and make sure to pass the tenant IDs every time you create a session. Then Hibernate Search will handle multi-tenancy out of the box, no additional work needed. You will still have to implement the multi-tenancy yourself on the database side, but at least on the index side you won't have to do anything.

If you don't want to use the built-in feature, then yes, you will have to annotate the parkId with @Field. I would recommend avoiding manually creating a boolean query just for that, though; you can simply use full text filters.

Upvotes: 2

Related Questions