Hello,
is it possible to index a field “LocalDateTime” as “LocalDate”?
I tried to do it via a bridge.
@Override
public LocalDate toIndexedValue(final LocalDateTime value, final ValueBridgeToIndexedValueContext context) {
return value == null ? null : value.toLocalDate();
}
The field looks like this:
@GenericField(
valueBridge = @ValueBridgeRef(type = LocalDateTimeBridge.class),
name = "date_created")
@Column(name = "CreatedOn", nullable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
updatable = false)
private LocalDateTime created;
With the query search I get an exception:
HSEARCH600050: Unable to convert DSL argument: Cannot cast java.time.LocalDate to java.time.LocalDateTime
Perhaps I am using the wrong approach. Does anyone have any ideas?
Thanks for your help!
I recommend you read Hibernate Search 6.1.1.Final: Reference Documentation .
But in short, the value bridge will change what you index, not what Hibernate Search expects you to pass to the Search DSL. Values passed to the DSL go through the value bridge as well, which in your case means Hibernate Search expects values of type LocalDateTime
(the type that your bridge takes as input).
You can tell Hibernate Search to ignore the value bridge by calling .matching( <some value>, ValueConvert.NO )
instead of .matching( <some value> )
when building your predicate.
Alternatively (but that’s more complex), you can also use a ValueBinder
instead of a ValueBridge
, and then you’ll have the ability to define a DSL converter explicitly, which would allow you to accept LocalDate
values.
That being said, the best solution in my opinion would be to get rid of your custom bridge, index values with full resolution, and use a range
predicate when searching:
LocalDate toMatch = /* ... */;
List<MyEntity> hits = searchSession.search( MyEntity.class )
.where( f -> f.range().field( "date" )
.range( Range.canonical( toMatch.atStartOfDay(),
toMatch.plus( 1, ChronoUnit.DAYS ).atStartOfDay() ) )
.fetchHits( 20 );
Finally, if you still want to truncate dates at indexing time, and want this to be configurable directly in Hibernate Search (without a custom bridge), you can drop a comment on [HSEARCH-2378] - Hibernate JIRA explaining your use case; @gsmet tends to agree we need that feature too, so maybe he’ll want to implement it
I will try the approaches.
Thank you very much!