Search code examples
hibernatekotlinhibernate-search

How can I index optional relations in hibernate search


I'm trying to update my hibernate search implementation to add relations between entities and it works fine, but only for entities that in fact have a relation to another entity. If it is null, it's just not indexed (this works according to the documentation).

I tried adding a RoutingBinder just in case I needed to have a route for the fields depending on the state of relation but no luck.

Similar example of what I have:

@Entity
@Indexed
class Product(
  @field:FullTextField
  var model: String,
  @OneToOne(mappedBy = "mappedTo", optional = true, cascade = [CascadeType.ALL])
  var mappedBy: Alias?
) {
  @Id
  var id: Long = 0
}

@Entity
@Indexed
class Alias(
  @Id
  @field:FullTextField
  var keyword: String,
  @OneToOne(optional = true, cascade = [CascadeType.ALL])
  @IndexedEmbedded
  var mappedTo: Product?
)

I would like to be able to search by keyword and model regardless of the state of the relation between these 2 entities.


Solution

  • If one of the entities is always present and the other one is optional, e.g. a product may have an alias, but an alias is always attached to a product -- then you can simply search by products (in this case, you'd need to move your @IndexedEmbedded to the product entity from the Alias).

    If you have two entities and both may-or-may-not have a relation but you'd want to find matches in both of them you can take a look at searching against multiple entities. Note that in this case, indexes should be compatible.

    As for the routing bridges, it serves a slightly different purpose. You won't be able to add entries to the index if the entity does not exist with it. This bridge can help either to filter the indexed entities (reducing the number of indexed ones) or put the indexed documents in a specific shard.