Hibernate Search: Exist predicate

Hi.

I usually use exist predicate and check if a property is null or not. But now, is it possible to check a condition and after to use exist predicate? like

get results where not exist(property with a condition)

The code that i use for null check only is:

predicates.add(pf.bool().mustNot(pf.exists().field(request.getProperty())).toPredicate());

The code that i want to check firstly a condition is like this

predicates.add(pf.bool().mustNot(pf.exists().field(request.getProperty()).matching(value)).toPredicate());

Thank you!

Hey Tony,

Thanks for reaching out. If you’d like to find documents that don’t have a property matching a condition, then you could simply do something like:

.where( f -> f.bool()
		.mustNot(
				f.match().field( property ).matching( value )
		)
)

This would eliminate the documents with a property that matches the condition.
If I’ve missed the point of what you were trying to achieve – could you please write a condition in a simple boolean logic instead of trying to build a pseudo predicate.

Hey and thanks for the answer.
e.x. i have two properties BigDecimal value and boolean status.
I would like to get documents

  1. if value == null or
  2. if value != null and value > 100 and status = 1

You could nest the bool predicates as you like, so the two conditions that you want to combine with an OR would be represented as two should clauses of a bool operator and must clauses would emulate an AND. With that – your predicate could look something like this (you would just need to use correct field names and pass values matching the types you need (boolean/decimal etc.):

.where(
	// should clauses in bool predicate serve as "operands of an "or" operator"
	f -> f.bool()
		// if value == null
		// add a should clause for the field being absent (not exists == null) 
		.should( f.bool().mustNot( f.exists().field( "value" ) ) )
		// or:
		// if value != null and value > 100 and status = 1
		// a nested bool query with all conditions. Adding multiple must clauses behaves as if "operands of an "and" operator"
		.should(
			f.bool().must( f.range().field( "value" ).greaterThan( 100 ) )
			        .must( f.match().field( "status" ).matching( 1 ) )
		)
);

You can also check these examples from the reference documentation - Hibernate Search 6.1.8.Final: Reference Documentation and Hibernate Search 6.1.8.Final: Reference Documentation that show how bool is used to emulate and/or operators.

Also, as a heads-up – in Hibernate Search 6.2 we are introducing AND/OR/NOT predicates:

  • and
  • or
  • not
    which would make writing such predicates a bit cleaner – so might be something to look forward for upgrading once the final version is released :wink: .
1 Like

Great news for Hibernate Search 6.2. i will upgrade my version!
Thank you for your help ! :slight_smile:

1 Like