Querying IndexedEmbedded entities (sometimes) returning wrong result

I’m attaching a test case that demonstrates unwanted search results.

I understand that Hibernate Search uses some tricks to support joined entities, using Apache Lucene, but I’m hoping you can suggest a solution.

I’m searching for “Foo” entities where its “Bar” children match TWO fields:
bar_name: Bar2
AND
bar_visibility: public

			QueryBuilder qb = session.getSearchFactory().buildQueryBuilder().forEntity(Foo.class).get();

			BooleanJunction<?> bool = qb.bool();
			bool.must(qb.keyword().onField("bar_name").matching("Bar2").createQuery());
			bool.must(qb.keyword().onField("bar_visibility").matching("public").createQuery());

			org.apache.lucene.search.Query query = bool.createQuery();

I only want Foo results where Bars match BOTH of the above criteria (hence my use of bool.must).

But, that’s not what’s happening. I’m seeing Foo results when just ONE of the two “must” criteria match:

########################
# executing query: +bar_name:bar2 +bar_visibility:public
# 1 results returned:
# Foo: id=1, name=Foo1, bars: [Bar: id=2, name=Bar2, visibility=private, Bar: id=1, name=Bar1, visibility=public]
########################

This happens when there are 2 Bar entities associated to a Foo entity. I.e., if you comment one lines

			Bar bar1 = new Bar(1L, "Bar1", "public", foo1);
			foo1.getBars().add(bar1);
			s.persist(bar1);

in “YourTestCase.java”, it correctly returns 0 results, as I’d expect.

Sorry, your system is not letting me upload my test case. How should I send it to you?

Here’s the ticket: https://hibernate.atlassian.net/browse/HSEARCH-4314

Copying the answer from the ticket here: