Index list of entities, but knowing only ID of entities

Hello! I have a problem and I can’t solve it.

There is a Product entity which contains the next indexing field:

@GenericField
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "t_product_pilots", schema = DbSchema.KKK,
    joinColumns = @JoinColumn(name = "product_id"))
@Column(name = "pilot_id", nullable = false)
private Set<Long> pilots = new HashSet<>();

pilots contains IDs of Pilot entity.

The problem is how I can create an additional field/getter in Product entity which contains some info about Pilots and I can use it for searching.

Here is what I tried to do but it doesn’t work correctly:

@IndexedEmbedded(name = "pilot_data", includePaths = {
    "name", "description", "effects", "problems"
})
private List<Pilot> getPilotsForIndexing(@Autowired PilotRepository repo) {
    return repo.findAllById(pilots);
}

I want the next structure in indexing document:

...
"pilots": [1, 4, 5],
...
"pilot_data": [
    "name": "123",
    "description": "desc",
    "effects": "zero",
    "problems": "no problem"
],
...

And after that I want to search for it like this:

predicate.should(factory.wildcard()
    .field("pilot_data.name").boost(3)
    .field("pilot_data.description").boost(2)
    ...
);

Hey,

well the more straightforward way would be to change the mapping to have

private Set<Pilot> pilots = new HashSet<>();

That way, you’ll be working with @IndexedEmbedded as usual. But I suspect you cannot do that for some reason?

If that’s so, you may want to look at this example in the documentation Hibernate Search 7.2.1.Final: Reference Documentation related to the bridges and how you can access ORM’s session. Alternatively, you can also see this section about injecting beans Hibernate Search 7.2.1.Final: Reference Documentation

You’d have to implement and use a bridge (Hibernate Search 7.2.1.Final: Reference Documentation)
But then, since you only have an id you won’t be able to define dependencies, so when your Pilot changes that change won’t get reflected in this index …

Hence changing the mapping option would make it much-much simpler :wink: