-
Notifications
You must be signed in to change notification settings - Fork 242
/
FullTextQueryImpl.java
485 lines (420 loc) · 14.3 KB
/
FullTextQueryImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/*
* Hibernate Search, full-text search for your domain model
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.search.query.hibernate.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.ScrollMode;
import org.hibernate.TypeMismatchException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.graph.GraphSemantic;
import org.hibernate.graph.RootGraph;
import org.hibernate.graph.spi.RootGraphImplementor;
import org.hibernate.query.IllegalQueryOperationException;
import org.hibernate.query.internal.QueryOptionsImpl;
import org.hibernate.query.spi.AbstractQuery;
import org.hibernate.query.spi.ParameterMetadataImplementor;
import org.hibernate.query.spi.QueryImplementor;
import org.hibernate.query.spi.QueryParameterBindings;
import org.hibernate.query.spi.ScrollableResultsImplementor;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.engine.search.query.SearchScroll;
import org.hibernate.search.impl.V5MigrationOrmSearchIntegratorAdapter;
import org.hibernate.search.mapper.orm.search.loading.EntityLoadingCacheLookupStrategy;
import org.hibernate.search.mapper.orm.search.loading.dsl.SearchLoadingOptionsStep;
import org.hibernate.search.mapper.orm.search.query.spi.HibernateOrmSearchQueryHints;
import org.hibernate.search.mapper.orm.search.query.spi.HibernateOrmSearchScrollableResultsAdapter;
import org.hibernate.search.query.DatabaseRetrievalMethod;
import org.hibernate.search.query.ObjectLookupMethod;
import org.hibernate.search.query.engine.spi.FacetManager;
import org.hibernate.search.query.engine.spi.HSQuery;
import org.hibernate.search.query.engine.spi.V5MigrationSearchSession;
import org.hibernate.search.spatial.Coordinates;
import org.hibernate.search.spatial.impl.Point;
import org.hibernate.search.util.common.SearchTimeoutException;
import org.hibernate.transform.ResultTransformer;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.QueryTimeoutException;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
/**
* Implementation of {@link org.hibernate.search.FullTextQuery}.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
@SuppressWarnings("rawtypes") // We extend the raw version of AbstractProducedQuery on purpose, see HSEARCH-2564
public class FullTextQueryImpl extends AbstractQuery implements FullTextQuery {
private final V5MigrationSearchSession<SearchLoadingOptionsStep> searchSession;
private final HSQuery hSearchQuery;
private final SessionImplementor sessionImplementor;
private final QueryOptionsImpl queryOptions = new QueryOptionsImpl();
//initialized at 0 since we don't expect to use hints at this stage
private final Map<String, Object> hints = new HashMap<String, Object>( 0 );
private Integer fetchSize = null;
private EntityLoadingCacheLookupStrategy cacheLookupStrategy = null;
private List<EntityGraphHint> entityGraphHints = new ArrayList<>();
private final Consumer<SearchLoadingOptionsStep> loadingOptionsContributor = o -> {
if ( cacheLookupStrategy != null ) {
o.cacheLookupStrategy( cacheLookupStrategy );
}
if ( fetchSize != null ) {
o.fetchSize( fetchSize );
}
for ( EntityGraphHint hint : entityGraphHints ) {
o.graph( hint.graph, hint.semantic );
}
};
private ResultTransformer resultTransformer;
public FullTextQueryImpl(Query luceneQuery, SessionImplementor sessionImplementor,
V5MigrationOrmSearchIntegratorAdapter searchIntegrator,
V5MigrationSearchSession<SearchLoadingOptionsStep> searchSession,
Class<?> ... entities) {
super( sessionImplementor );
this.sessionImplementor = sessionImplementor;
this.searchSession = searchSession;
this.hSearchQuery = searchIntegrator.createHSQuery( luceneQuery, searchSession,
loadingOptionsContributor, entities );
}
@Override
public FullTextQueryImpl setSort(Sort sort) {
hSearchQuery.sort( sort );
return this;
}
@Override
public List getResultList() {
return list();
}
@Override
public ScrollableResultsImplementor scroll() {
return scroll( ScrollMode.FORWARD_ONLY );
}
@Override
protected ScrollableResultsImplementor doScroll(ScrollMode scrollMode) {
extractQueryOptions();
SearchScroll<?> scroll = hSearchQuery.scroll( fetchSize != null ? fetchSize : 100 );
Integer maxResults = hSearchQuery.maxResults();
return new HibernateOrmSearchScrollableResultsAdapter<>( scroll,
maxResults != null ? maxResults : Integer.MAX_VALUE,
Search5ScrollHitExtractor.INSTANCE );
}
@Override
public List list() {
try {
return super.list();
}
catch (SearchTimeoutException e) {
throw new QueryTimeoutException( e );
}
}
@Override
protected List doList() {
List list = hSearchQuery.fetch();
if ( resultTransformer != null ) {
list = resultTransformer.transformList( list );
}
return list;
}
@Override
protected void beforeQuery() {
super.beforeQuery();
extractQueryOptions();
}
private void extractQueryOptions() {
Integer limit = getQueryOptions().getLimit().getMaxRows();
hSearchQuery.maxResults( limit );
Integer offset = getQueryOptions().getLimit().getFirstRow();
hSearchQuery.firstResult( offset == null ? 0 : offset );
Integer queryFetchSize = getQueryOptions().getFetchSize();
if ( queryFetchSize != null ) {
fetchSize = queryFetchSize;
}
Integer queryTimeout = getQueryOptions().getTimeout();
if ( queryTimeout != null ) {
hSearchQuery.failAfter( queryTimeout, TimeUnit.SECONDS );
}
}
@Override
public Explanation explain(Object entityId) {
return hSearchQuery.explain( entityId );
}
@Override
public int getResultSize() {
try {
return doGetResultSize();
}
catch (SearchTimeoutException e) {
throw new QueryTimeoutException( e );
}
catch (IllegalQueryOperationException e) {
throw new IllegalStateException( e );
}
catch (TypeMismatchException e) {
throw new IllegalArgumentException( e );
}
catch (HibernateException he) {
throw getSession().getExceptionConverter().convert( he, getLockOptions() );
}
}
public int doGetResultSize() {
return hSearchQuery.getResultSize();
}
@Override
public FullTextQuery applyGraph(RootGraph graph, GraphSemantic semantic) {
applyGraph( (RootGraphImplementor) graph, semantic );
return this;
}
@Override
protected void applyGraph(RootGraphImplementor<?> graph, GraphSemantic semantic) {
entityGraphHints.add( new EntityGraphHint<>( graph, semantic ) );
}
@Override
public FullTextQueryImpl setProjection(String... fields) {
hSearchQuery.projection( fields );
return this;
}
@Override
public FullTextQueryImpl setSpatialParameters(Coordinates center, String fieldName) {
hSearchQuery.setSpatialParameters( center, fieldName );
return this;
}
@Override
public FullTextQueryImpl setSpatialParameters(double latitude, double longitude, String fieldName) {
setSpatialParameters( Point.fromDegrees( latitude, longitude ), fieldName );
return this;
}
@Override
public FullTextQuery setMaxResults(int maxResults) {
super.setMaxResults( maxResults );
return this;
}
@Override
public FullTextQuery setFirstResult(int firstResult) {
super.setFirstResult( firstResult );
return this;
}
@Override
@SuppressWarnings("deprecation")
public FullTextQuery setHint(String hintName, Object value) {
hints.put( hintName, value );
switch ( hintName ) {
case HibernateOrmSearchQueryHints.JAVAX_TIMEOUT:
case HibernateOrmSearchQueryHints.JAKARTA_TIMEOUT:
setTimeout( hintValueToInteger( value ), TimeUnit.MILLISECONDS );
break;
case HibernateOrmSearchQueryHints.HIBERNATE_TIMEOUT:
setTimeout( hintValueToInteger( value ) );
break;
case HibernateOrmSearchQueryHints.JAVAX_FETCHGRAPH:
case HibernateOrmSearchQueryHints.JAKARTA_FETCHGRAPH:
case HibernateOrmSearchQueryHints.JAVAX_LOADGRAPH:
case HibernateOrmSearchQueryHints.JAKARTA_LOADGRAPH:
applyEntityGraphHint( hintName, hintValueToEntityGraph( value ) );
break;
default:
break;
}
return this;
}
@Override
public Map<String, Object> getHints() {
return hints;
}
@Override
public ParameterMetadataImplementor getParameterMetadata() {
throw parametersNoSupported();
}
@Override
public QueryParameterBindings getParameterBindings() {
// parameters not supported in Hibernate Search queries
return QueryParameterBindings.NO_PARAM_BINDINGS;
}
@Override
public QueryParameterBindings getQueryParameterBindings() {
// parameters not supported in Hibernate Search queries
return QueryParameterBindings.NO_PARAM_BINDINGS;
}
@Override
public QueryImplementor<?> setParameterList(String name, Object[] values) {
throw parametersNoSupported();
}
@Override
public QueryImplementor<?> setParameterList(String s, Collection collection, Class aClass) {
throw parametersNoSupported();
}
@Override
public QueryImplementor<?> setParameterList(int i, Collection collection, Class aClass) {
throw parametersNoSupported();
}
private UnsupportedOperationException parametersNoSupported() {
return new UnsupportedOperationException( "Parameters are not supported in Hibernate Search queries" );
}
@Override
public FullTextQueryImpl setFlushMode(FlushModeType flushModeType) {
return (FullTextQueryImpl) super.setFlushMode( flushModeType );
}
@Override
public FullTextQueryImpl setFetchSize(int fetchSize) {
return (FullTextQueryImpl) super.setFetchSize( fetchSize );
}
@Override
public QueryImplementor setLockOptions(LockOptions lockOptions) {
throw lockOptionsNotSupported();
}
@Deprecated
@Override
public FullTextQueryImpl setResultTransformer(ResultTransformer transformer) {
resultTransformer = transformer;
if ( transformer != null ) {
hSearchQuery.tupleTransformer( (tuple, fields) -> resultTransformer.transformTuple( tuple, fields ) );
}
else {
hSearchQuery.tupleTransformer( null );
}
return this;
}
/*
* Implementation note: this method is defined as generic in the interface,
* but we must implement it without generics (otherwise it won't compile).
*
* The actual reason is a bit hard to explain: basically we implement
* jakarta.persistence.Query as a raw type at some point, and our superclass
* (also extended as a raw type) also implements this interface, but as a non-raw type.
* This seems to confuse the compiler, which thinks there are two different methods.
*/
@Override
@SuppressWarnings("unchecked")
public Object unwrap(Class type) {
//I've purposely decided not to return the underlying Hibernate FullTextQuery
//as I see this as an implementation detail that should not be exposed.
if ( type == org.apache.lucene.search.Query.class ) {
return hSearchQuery.getLuceneQuery();
}
else if ( type.isInstance( this ) ) {
return this;
}
else {
throw new PersistenceException( "Unrecognized unwrap type [" + type.getName() + "]" );
}
}
@Override
public FullTextQueryImpl setLockMode(LockModeType lockModeType) {
throw lockOptionsNotSupported();
}
@Override
public LockModeType getLockMode() {
throw lockOptionsNotSupported();
}
@Override
public LockOptions getLockOptions() {
throw lockOptionsNotSupported();
}
private UnsupportedOperationException lockOptionsNotSupported() {
return new UnsupportedOperationException( "Lock options are not supported in Hibernate Search queries" );
}
@Override
public int executeUpdate() throws HibernateException {
return doExecuteUpdate();
}
@Override
protected int doExecuteUpdate() {
throw new UnsupportedOperationException( "executeUpdate is not supported in Hibernate Search queries" );
}
@Override
public QueryImplementor setLockMode(String alias, LockMode lockMode) {
throw lockOptionsNotSupported();
}
@Override
public FacetManager getFacetManager() {
return hSearchQuery.getFacetManager();
}
@Override
public FullTextQueryImpl setTimeout(int timeout) {
return setTimeout( timeout, TimeUnit.SECONDS );
}
@Override
public FullTextQueryImpl setTimeout(long timeout, TimeUnit timeUnit) {
hSearchQuery.failAfter( timeout, timeUnit );
return this;
}
@Override
public FullTextQueryImpl limitExecutionTimeTo(long timeout, TimeUnit timeUnit) {
hSearchQuery.truncateAfter( timeout, timeUnit );
return this;
}
@Override
public boolean hasPartialResults() {
return hSearchQuery.hasPartialResults();
}
@Override
public FullTextQueryImpl initializeObjectsWith(ObjectLookupMethod lookupMethod, DatabaseRetrievalMethod retrievalMethod) {
switch ( lookupMethod ) {
case SKIP:
this.cacheLookupStrategy = EntityLoadingCacheLookupStrategy.SKIP;
break;
case PERSISTENCE_CONTEXT:
this.cacheLookupStrategy = EntityLoadingCacheLookupStrategy.PERSISTENCE_CONTEXT;
break;
case SECOND_LEVEL_CACHE:
this.cacheLookupStrategy = EntityLoadingCacheLookupStrategy.PERSISTENCE_CONTEXT_THEN_SECOND_LEVEL_CACHE;
break;
}
return this;
}
@Override
public String getQueryString() {
return hSearchQuery.getQueryString();
}
@Override
public QueryOptionsImpl getQueryOptions() {
return queryOptions;
}
@Override
public SharedSessionContractImplementor getSession() {
return sessionImplementor;
}
@Override
public String toString() {
return "FullTextQueryImpl(" + getQueryString() + ")";
}
private static final class Search5ScrollHitExtractor
implements Function<Object, Object[]> {
private static final Search5ScrollHitExtractor INSTANCE = new Search5ScrollHitExtractor();
@Override
public Object[] apply(Object hit) {
if ( hit instanceof Object[] ) {
return (Object[]) hit;
}
else {
return new Object[] { hit };
}
}
}
private static int hintValueToInteger(Object value) {
if ( value instanceof Number ) {
return ( (Number) value ).intValue();
}
else {
return Integer.parseInt( String.valueOf( value ) );
}
}
private static RootGraphImplementor<?> hintValueToEntityGraph(Object value) {
return (RootGraphImplementor) value;
}
}