-
Notifications
You must be signed in to change notification settings - Fork 242
/
ElasticsearchHSQueryImpl.java
1288 lines (1110 loc) · 45 KB
/
ElasticsearchHSQueryImpl.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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.elasticsearch.impl;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.FloatField;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopDocs;
import org.hibernate.search.bridge.FieldBridge;
import org.hibernate.search.bridge.TwoWayFieldBridge;
import org.hibernate.search.bridge.spi.ConversionContext;
import org.hibernate.search.bridge.util.impl.ContextualExceptionBridgeHelper;
import org.hibernate.search.elasticsearch.ElasticsearchProjectionConstants;
import org.hibernate.search.elasticsearch.filter.ElasticsearchFilter;
import org.hibernate.search.elasticsearch.logging.impl.Log;
import org.hibernate.search.elasticsearch.util.impl.FieldHelper;
import org.hibernate.search.elasticsearch.util.impl.FieldHelper.ExtendedFieldType;
import org.hibernate.search.elasticsearch.util.impl.Window;
import org.hibernate.search.elasticsearch.work.impl.ElasticsearchWork;
import org.hibernate.search.elasticsearch.work.impl.ExplainResult;
import org.hibernate.search.elasticsearch.work.impl.SearchResult;
import org.hibernate.search.elasticsearch.work.impl.builder.SearchWorkBuilder;
import org.hibernate.search.engine.impl.FilterDef;
import org.hibernate.search.engine.integration.impl.ExtendedSearchIntegrator;
import org.hibernate.search.engine.metadata.impl.BridgeDefinedField;
import org.hibernate.search.engine.metadata.impl.DocumentFieldMetadata;
import org.hibernate.search.engine.metadata.impl.FacetMetadata;
import org.hibernate.search.engine.metadata.impl.TypeMetadata;
import org.hibernate.search.engine.service.spi.ServiceReference;
import org.hibernate.search.engine.spi.DocumentBuilderIndexedEntity;
import org.hibernate.search.engine.spi.EntityIndexBinding;
import org.hibernate.search.filter.impl.FullTextFilterImpl;
import org.hibernate.search.indexes.spi.IndexManager;
import org.hibernate.search.query.dsl.impl.DiscreteFacetRequest;
import org.hibernate.search.query.dsl.impl.FacetRange;
import org.hibernate.search.query.dsl.impl.RangeFacetRequest;
import org.hibernate.search.query.engine.impl.AbstractHSQuery;
import org.hibernate.search.query.engine.impl.EntityInfoImpl;
import org.hibernate.search.query.engine.impl.FacetComparators;
import org.hibernate.search.query.engine.impl.FacetManagerImpl;
import org.hibernate.search.query.engine.impl.TimeoutManagerImpl;
import org.hibernate.search.query.engine.spi.DocumentExtractor;
import org.hibernate.search.query.engine.spi.EntityInfo;
import org.hibernate.search.query.engine.spi.HSQuery;
import org.hibernate.search.query.facet.Facet;
import org.hibernate.search.query.facet.FacetSortOrder;
import org.hibernate.search.query.facet.FacetingRequest;
import org.hibernate.search.spatial.DistanceSortField;
import org.hibernate.search.util.impl.CollectionHelper;
import org.hibernate.search.util.impl.ReflectionHelper;
import org.hibernate.search.util.logging.impl.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
/**
* Query implementation based on Elasticsearch.
*
* @author Gunnar Morling
*/
public class ElasticsearchHSQueryImpl extends AbstractHSQuery {
private static final JsonParser JSON_PARSER = new JsonParser();
private static final Log LOG = LoggerFactory.make( Log.class );
private static final Pattern DOT = Pattern.compile( "\\." );
private static final String SPATIAL_DISTANCE_FIELD = "_distance";
/**
* ES default limit for (firstResult + maxResult)
*/
private static final int MAX_RESULT_WINDOW_SIZE = 10000;
private static final Set<String> SUPPORTED_PROJECTION_CONSTANTS = Collections.unmodifiableSet(
CollectionHelper.asSet(
ElasticsearchProjectionConstants.ID,
ElasticsearchProjectionConstants.OBJECT_CLASS,
ElasticsearchProjectionConstants.SCORE,
ElasticsearchProjectionConstants.SOURCE,
ElasticsearchProjectionConstants.SPATIAL_DISTANCE,
ElasticsearchProjectionConstants.THIS,
ElasticsearchProjectionConstants.TOOK,
ElasticsearchProjectionConstants.TIMED_OUT
)
);
/**
* The constructor-provided payload for the Search API, holding
* the search query in particular.
* <p>
* This raw payload will serve as a basis for the actual payload to be sent toElasticsearch,
* which will also contain automatically generated data related in particular to sorts
* and projections.
*/
private final JsonObject rawSearchPayload;
private Integer resultSize;
private IndexSearcher searcher;
private SearchResult searchResult;
private int sortByDistanceIndex = -1;
private transient FacetManagerImpl facetManager;
public ElasticsearchHSQueryImpl(JsonObject rawSearchPayload, ExtendedSearchIntegrator extendedIntegrator) {
super( extendedIntegrator );
this.rawSearchPayload = rawSearchPayload;
}
@Override
public HSQuery luceneQuery(Query query) {
throw LOG.hsQueryLuceneQueryUnsupported();
}
@Override
public FacetManagerImpl getFacetManager() {
if ( facetManager == null ) {
facetManager = new FacetManagerImpl( this );
}
return facetManager;
}
@Override
public Query getLuceneQuery() {
throw LOG.hsQueryLuceneQueryUnsupported();
}
@Override
public String getQueryString() {
return rawSearchPayload.toString();
}
@Override
public DocumentExtractor queryDocumentExtractor() {
return new ElasticsearchScrollAPIDocumentExtractor();
}
SearchResult getSearchResult() {
if ( searchResult == null ) {
execute();
}
return searchResult;
}
@Override
public int queryResultSize() {
if ( searchResult == null ) {
execute();
}
return resultSize;
}
@Override
public Explanation explain(int documentId) {
if ( searchResult == null ) {
execute();
}
JsonObject hit = searchResult.getHits()
// TODO Is it right to use the document id that way? I am not quite clear about its semantics
.get( documentId )
.getAsJsonObject();
try ( ServiceReference<ElasticsearchService> elasticsearchService =
getExtendedSearchIntegrator().getServiceManager().requestReference( ElasticsearchService.class ) ) {
/*
* Do not add every property of the original payload: some properties, such as "_source", do not have the same syntax
* and are not necessary to the explanation.
*/
JsonObject explainPayload = JsonBuilder.object()
.add( "query", searcher.payload.get( "query" ) )
.build();
ElasticsearchWork<ExplainResult> work = elasticsearchService.get().getWorkFactory().explain(
hit.get( "_index" ).getAsString(),
hit.get( "_type" ).getAsString(),
hit.get( "_id" ).getAsString(),
explainPayload )
.build();
ExplainResult result = elasticsearchService.get().getWorkProcessor().executeSyncUnsafe( work );
JsonObject explanation = result.getJsonObject().get( "explanation" ).getAsJsonObject();
return convertExplanation( explanation );
}
}
private Explanation convertExplanation(JsonObject explanation) {
float value = explanation.get( "value" ).getAsFloat();
String description = explanation.get( "description" ).getAsString();
JsonElement explanationDetails = explanation.get( "details" );
List<Explanation> details;
if ( explanationDetails != null ) {
details = new ArrayList<>( explanationDetails.getAsJsonArray().size() );
for ( JsonElement detail : explanationDetails.getAsJsonArray() ) {
details.add( convertExplanation( detail.getAsJsonObject() ) );
}
}
else {
details = Collections.emptyList();
}
return Explanation.match( value, description, details );
}
@Override
protected void clearCachedResults() {
searcher = null;
searchResult = null;
resultSize = null;
}
@Override
protected TimeoutManagerImpl buildTimeoutManager() {
return new TimeoutManagerImpl(
rawSearchPayload,
timeoutExceptionFactory,
this.extendedIntegrator.getTimingSource()
);
}
@Override
public List<EntityInfo> queryEntityInfos() {
if ( searchResult == null ) {
execute();
}
JsonArray hits = searchResult.getHits();
List<EntityInfo> results = new ArrayList<>( hits.size() );
for ( JsonElement hit : hits ) {
EntityInfo entityInfo = searcher.convertQueryHit( searchResult, hit.getAsJsonObject() );
if ( entityInfo != null ) {
results.add( entityInfo );
}
}
return results;
}
@Override
protected Set<String> getSupportedProjectionConstants() {
return SUPPORTED_PROJECTION_CONSTANTS;
}
private void execute() {
searcher = new IndexSearcher();
searchResult = searcher.search();
resultSize = searchResult.getTotalHitCount();
}
/**
* Stores all information required to execute the query: query string, relevant indices, query parameters, ...
*/
private class IndexSearcher {
private final ElasticsearchQueryOptions queryOptions;
private final Map<String, Class<?>> entityTypesByName = new HashMap<>();
private final Map<Class<?>, FieldProjection> idProjectionByEntityType = new HashMap<>();
private final Map<Class<?>, FieldProjection[]> fieldProjectionsByEntityType = new HashMap<>();
private final Set<String> indexNames = new HashSet<>();
private final JsonObject payload;
private IndexSearcher() {
JsonArray typeFilters = new JsonArray();
Iterable<Class<?>> queriedEntityTypes = getQueriedEntityTypes();
for ( Class<?> queriedEntityType : queriedEntityTypes ) {
entityTypesByName.put( queriedEntityType.getName(), queriedEntityType );
EntityIndexBinding binding = extendedIntegrator.getIndexBinding( queriedEntityType );
IndexManager[] indexManagers = binding.getIndexManagers();
for ( IndexManager indexManager : indexManagers ) {
if ( !( indexManager instanceof ElasticsearchIndexManager ) ) {
throw LOG.cannotRunEsQueryTargetingEntityIndexedWithNonEsIndexManager(
queriedEntityType,
rawSearchPayload.toString()
);
}
ElasticsearchIndexManager esIndexManager = (ElasticsearchIndexManager) indexManager;
indexNames.add( esIndexManager.getActualIndexName() );
}
typeFilters.add( getEntityTypeFilter( queriedEntityType ) );
}
try ( ServiceReference<ElasticsearchService> elasticsearchService =
getExtendedSearchIntegrator().getServiceManager().requestReference( ElasticsearchService.class ) ) {
this.queryOptions = elasticsearchService.get().getQueryOptions();
}
// Query filters; always a type filter, possibly a tenant id filter;
JsonObject filteredQuery = getFilteredQuery( rawSearchPayload.get( "query" ), typeFilters );
JsonBuilder.Object payloadBuilder = JsonBuilder.object();
payloadBuilder.add( "query", filteredQuery );
addProjections( payloadBuilder );
if ( !getFacetManager().getFacetRequests().isEmpty() ) {
JsonBuilder.Object facets = JsonBuilder.object();
for ( Entry<String, FacetingRequest> facetRequestEntry : getFacetManager().getFacetRequests().entrySet() ) {
addFacetingRequest( facets, facetRequestEntry.getValue() );
}
payloadBuilder.add( "aggregations", facets );
}
// Initialize the sortByDistanceIndex to detect if the results are sorted by distance and the position
// of the sort
sortByDistanceIndex = getSortByDistanceIndex();
addScriptFields( payloadBuilder );
// TODO: HSEARCH-2254 embedded fields (see https://github.com/searchbox-io/Jest/issues/304)
if ( sort != null ) {
validateSortFields( extendedIntegrator, getQueriedEntityTypes() );
payloadBuilder.add( "sort", ToElasticsearch.fromLuceneSort( sort ) );
}
this.payload = payloadBuilder.build();
}
private JsonObject getFilteredQuery(JsonElement originalQuery, JsonArray typeFilters) {
JsonArray filters = new JsonArray();
JsonObject tenantFilter = getTenantIdFilter();
if ( tenantFilter != null ) {
filters.add( tenantFilter );
}
// wrap type filters into should if there is more than one
filters.add( ToElasticsearch.condition( "should", typeFilters ) );
// facet filters
for ( Query query : getFacetManager().getFacetFilters().getFilterQueries() ) {
filters.add( ToElasticsearch.fromLuceneQuery( query ) );
}
// user filter
if ( userFilter != null ) {
filters.add( ToElasticsearch.fromLuceneFilter( userFilter ) );
}
if ( !filterDefinitions.isEmpty() ) {
for ( FullTextFilterImpl fullTextFilter : filterDefinitions.values() ) {
JsonObject filter = buildFullTextFilter( fullTextFilter );
if ( filter != null ) {
filters.add( filter );
}
}
}
JsonBuilder.Object boolBuilder = JsonBuilder.object();
if ( originalQuery != null && !originalQuery.isJsonNull() ) {
boolBuilder.add( "must", originalQuery );
}
if ( filters.size() == 1 ) {
boolBuilder.add( "filter", filters.get( 0 ) );
}
else {
boolBuilder.add( "filter", filters );
}
return JsonBuilder.object().add( "bool", boolBuilder.build() ).build();
}
private JsonObject getEntityTypeFilter(Class<?> queriedEntityType) {
JsonObject value = new JsonObject();
value.addProperty( "value", queriedEntityType.getName() );
JsonObject type = new JsonObject();
type.add( "type", value );
return type;
}
private JsonObject getTenantIdFilter() {
if ( tenantId == null ) {
return null;
}
JsonObject value = new JsonObject();
value.addProperty( DocumentBuilderIndexedEntity.TENANT_ID_FIELDNAME, tenantId );
JsonObject tenantFilter = new JsonObject();
tenantFilter.add( "term", value );
return tenantFilter;
}
private Iterable<Class<?>> getQueriedEntityTypes() {
if ( indexedTargetedEntities == null || indexedTargetedEntities.isEmpty() ) {
return extendedIntegrator.getIndexBindings().keySet();
}
else {
return indexedTargetedEntities;
}
}
private void addProjections(JsonBuilder.Object payloadBuilder) {
boolean includeAllSource = false;
JsonBuilder.Array builder = JsonBuilder.array();
Iterable<Class<?>> queriedEntityTypes = getQueriedEntityTypes();
/*
* IDs are always projected: always initialize their projections regardless of the
* "projectedFields" attribute.
*/
for ( Class<?> entityType : queriedEntityTypes ) {
EntityIndexBinding binding = extendedIntegrator.getIndexBinding( entityType );
DocumentBuilderIndexedEntity documentBuilder = binding.getDocumentBuilder();
String idFieldName = documentBuilder.getIdFieldName();
TypeMetadata typeMetadata = documentBuilder.getTypeMetadata();
FieldProjection projection = createProjection( builder, typeMetadata, idFieldName );
idProjectionByEntityType.put( entityType, projection );
}
if ( projectedFields != null ) {
for ( int i = 0 ; i < projectedFields.length ; ++i ) {
String projectedField = projectedFields[i];
if ( projectedField == null ) {
continue;
}
switch ( projectedField ) {
case ElasticsearchProjectionConstants.SOURCE:
includeAllSource = true;
break;
case ElasticsearchProjectionConstants.SCORE:
// Make sure to compute scores even if we don't sort by relevance
payloadBuilder.addProperty( "track_scores", true );
break;
case ElasticsearchProjectionConstants.ID:
case ElasticsearchProjectionConstants.THIS:
case ElasticsearchProjectionConstants.OBJECT_CLASS:
case ElasticsearchProjectionConstants.SPATIAL_DISTANCE:
case ElasticsearchProjectionConstants.TOOK:
case ElasticsearchProjectionConstants.TIMED_OUT:
// Ignore: no impact on source filtering
break;
default:
for ( Class<?> entityType : queriedEntityTypes ) {
EntityIndexBinding binding = extendedIntegrator.getIndexBinding( entityType );
TypeMetadata typeMetadata = binding.getDocumentBuilder().getTypeMetadata();
FieldProjection projection = createProjection( builder, typeMetadata, projectedField );
FieldProjection[] projectionsForType = fieldProjectionsByEntityType.get( entityType );
if ( projectionsForType == null ) {
projectionsForType = new FieldProjection[projectedFields.length];
fieldProjectionsByEntityType.put( entityType, projectionsForType );
}
projectionsForType[i] = projection;
}
break;
}
}
}
JsonElement filter;
if ( includeAllSource ) {
filter = new JsonPrimitive( "*" );
}
else {
JsonArray array = builder.build();
if ( array.size() > 0 ) {
filter = array;
}
else {
// Projecting only on score or other document-independent values
filter = new JsonPrimitive( false );
}
}
payloadBuilder.add( "_source", filter );
}
private FieldProjection createProjection(JsonBuilder.Array sourceFilterCollector, TypeMetadata rootTypeMetadata, String projectedField) {
DocumentFieldMetadata fieldMetadata = rootTypeMetadata.getDocumentFieldMetadataFor( projectedField );
if ( fieldMetadata != null ) {
return createProjection( sourceFilterCollector, rootTypeMetadata, fieldMetadata );
}
else {
// We check if it is a field created by a field bridge
BridgeDefinedField bridgeDefinedField = rootTypeMetadata.getBridgeDefinedFieldMetadataFor( projectedField );
if ( bridgeDefinedField != null ) {
return createProjection( sourceFilterCollector, rootTypeMetadata, bridgeDefinedField );
}
else {
/*
* No metadata: fall back to dynamically converting the resulting
* JSON to the most appropriate Java type.
*/
sourceFilterCollector.add( new JsonPrimitive( projectedField ) );
return new JsonDrivenProjection( projectedField );
}
}
}
private FieldProjection createProjection(JsonBuilder.Array sourceFilterCollector, TypeMetadata rootTypeMetadata,
DocumentFieldMetadata fieldMetadata) {
String absoluteName = fieldMetadata.getAbsoluteName();
FieldBridge fieldBridge = fieldMetadata.getFieldBridge();
ExtendedFieldType type = FieldHelper.getType( fieldMetadata );
if ( ExtendedFieldType.BOOLEAN.equals( type ) ) {
sourceFilterCollector.add( new JsonPrimitive( absoluteName ) );
return new PrimitiveProjection( rootTypeMetadata, absoluteName, type );
}
else if ( fieldBridge instanceof TwoWayFieldBridge ) {
sourceFilterCollector.add( new JsonPrimitive( absoluteName ) );
PrimitiveProjection defaultFieldProjection = new PrimitiveProjection( rootTypeMetadata, absoluteName, type );
Collection<BridgeDefinedField> bridgeDefinedFields = fieldMetadata.getBridgeDefinedFields().values();
List<PrimitiveProjection> bridgeDefinedFieldsProjections = CollectionHelper.newArrayList( bridgeDefinedFields.size() );
for ( BridgeDefinedField bridgeDefinedField : bridgeDefinedFields ) {
PrimitiveProjection primitiveProjection = createProjection( sourceFilterCollector, rootTypeMetadata, bridgeDefinedField );
bridgeDefinedFieldsProjections.add( primitiveProjection );
}
return new TwoWayFieldBridgeProjection(
absoluteName, (TwoWayFieldBridge) fieldBridge, defaultFieldProjection, bridgeDefinedFieldsProjections
);
}
else {
/*
* Don't fail immediately: this entity type may not be present in the results, in which case
* we don't need to be able to project on this field for this exact entity type.
* Just make sure we *will* ultimately fail if we encounter this entity type.
*/
return new FailingOneWayFieldBridgeProjection( absoluteName, fieldBridge.getClass() );
}
}
private PrimitiveProjection createProjection(JsonBuilder.Array sourceFilterCollector, TypeMetadata rootTypeMetadata,
BridgeDefinedField bridgeDefinedField) {
String absoluteName = bridgeDefinedField.getAbsoluteName();
ExtendedFieldType type = FieldHelper.getType( bridgeDefinedField );
sourceFilterCollector.add( new JsonPrimitive( absoluteName ) );
return new PrimitiveProjection( rootTypeMetadata, absoluteName, type );
}
private void addFacetingRequest(JsonBuilder.Object facets, FacetingRequest facetingRequest) {
String facetFieldAbsoluteName = facetingRequest.getFieldName();
FacetMetadata facetMetadata = null;
for ( Class<?> entityType : getQueriedEntityTypes() ) {
EntityIndexBinding binding = extendedIntegrator.getIndexBinding( entityType );
TypeMetadata typeMetadata = binding.getDocumentBuilder().getTypeMetadata();
facetMetadata = typeMetadata.getFacetMetadataFor( facetFieldAbsoluteName );
if ( facetMetadata != null ) {
break;
}
}
if ( facetMetadata == null ) {
throw LOG.unknownFieldNameForFaceting( facetingRequest.getFacetingName(), facetingRequest.getFieldName() );
}
String sourceFieldAbsoluteName = facetMetadata.getSourceField().getAbsoluteName();
String facetSubfieldName = facetMetadata.getPath().getRelativeName();
ToElasticsearch.addFacetingRequest( facets, facetingRequest, sourceFieldAbsoluteName, facetSubfieldName );
}
/**
* Returns the index of the DistanceSortField in the Sort array.
*
* @return the index, -1 if no DistanceSortField has been found
*/
private int getSortByDistanceIndex() {
int i = 0;
if ( sort != null ) {
for ( SortField sortField : sort.getSort() ) {
if ( sortField instanceof DistanceSortField ) {
return i;
}
i++;
}
}
return -1;
}
/**
* Indicates if the results are sorted by distance (note that it might be a secondary order).
*/
private boolean isSortedByDistance() {
return sortByDistanceIndex >= 0;
}
private void addScriptFields(JsonBuilder.Object payloadBuilder) {
if ( isPartOfProjectedFields( ElasticsearchProjectionConstants.SPATIAL_DISTANCE ) && !isSortedByDistance() ) {
// when the results are sorted by distance, Elasticsearch returns the distance in a "sort" field in
// the results. If we don't sort by distance, we need to request for the distance using a script_field.
payloadBuilder.add( "script_fields",
JsonBuilder.object().add( SPATIAL_DISTANCE_FIELD, JsonBuilder.object()
.add( "script", JsonBuilder.object()
.add( "params",
JsonBuilder.object()
.addProperty( "lat", spatialSearchCenter.getLatitude() )
.addProperty( "lon", spatialSearchCenter.getLongitude() )
)
// We multiply by 0.001 to Convert from meters to kilmeters
.addProperty( "inline", "doc['" + spatialFieldName + "'] ? doc['" + spatialFieldName + "'].arcDistance(lat,lon)*0.001 : null" )
.addProperty( "lang", "groovy" )
)
)
);
}
}
SearchResult search() {
return search( false );
}
SearchResult searchWithScrollEnabled() {
return search( true );
}
private SearchResult search(boolean enableScrolling) {
try ( ServiceReference<ElasticsearchService> elasticsearchService =
getExtendedSearchIntegrator().getServiceManager().requestReference( ElasticsearchService.class ) ) {
SearchWorkBuilder builder = elasticsearchService.get().getWorkFactory()
.search( payload ).indexes( indexNames );
if ( enableScrolling ) {
/*
* Note: "firstResult" is currently being ignored by Elasticsearch when scrolling.
* See https://github.com/elastic/elasticsearch/issues/9373
* To work this around, we don't use the "from" parameter here, and the document
* extractor will skip the results by scrolling until it gets the right index.
*/
builder.scrolling(
/*
* The "size" parameter has a slightly different meaning when scrolling: it defines the window
* size for the first search *and* for the next calls to the scroll API.
* We still reduce the number of results in accordance to "maxResults", but that's done on our side
* in the document extractor.
*/
getQueryOptions().getScrollFetchSize(),
getQueryOptions().getScrollTimeout()
);
}
else {
builder.paging(
firstResult,
// If the user has given a 'size' value, take it as is, let ES itself complain if it's too high; if no value is
// given, I take as much as possible, as by default only 10 rows would be returned
maxResults != null ? maxResults : MAX_RESULT_WINDOW_SIZE - firstResult
);
}
ElasticsearchWork<SearchResult> work = builder.build();
return elasticsearchService.get().getWorkProcessor().executeSyncUnsafe( work );
}
}
private ElasticsearchQueryOptions getQueryOptions() {
return queryOptions;
}
/**
* Scroll through search results, using a previously obtained scrollId.
*/
SearchResult scroll(String scrollId) {
try ( ServiceReference<ElasticsearchService> elasticsearchService =
getExtendedSearchIntegrator().getServiceManager().requestReference( ElasticsearchService.class ) ) {
ElasticsearchQueryOptions queryOptions = getQueryOptions();
ElasticsearchWork<SearchResult> work = elasticsearchService.get().getWorkFactory()
.scroll( scrollId, queryOptions.getScrollTimeout() ).build();
return elasticsearchService.get().getWorkProcessor().executeSyncUnsafe( work );
}
}
void clearScroll(String scrollId) {
try ( ServiceReference<ElasticsearchService> elasticsearchService =
getExtendedSearchIntegrator().getServiceManager().requestReference( ElasticsearchService.class ) ) {
ElasticsearchWork<?> work = elasticsearchService.get().getWorkFactory()
.clearScroll( scrollId ).build();
elasticsearchService.get().getWorkProcessor().executeSyncUnsafe( work );
}
}
EntityInfo convertQueryHit(SearchResult searchResult, JsonObject hit) {
String type = hit.get( "_type" ).getAsString();
Class<?> clazz = entityTypesByName.get( type );
if ( clazz == null ) {
LOG.warnf( "Found unknown type in Elasticsearch index: " + type );
return null;
}
EntityIndexBinding binding = extendedIntegrator.getIndexBinding( clazz );
ConversionContext conversionContext = new ContextualExceptionBridgeHelper();
conversionContext.setClass( clazz );
FieldProjection idProjection = idProjectionByEntityType.get( clazz );
Object id = idProjection.convertHit( hit, conversionContext );
Object[] projections = null;
if ( projectedFields != null ) {
projections = new Object[projectedFields.length];
for ( int i = 0; i < projections.length; i++ ) {
String field = projectedFields[i];
if ( field == null ) {
continue;
}
switch ( field ) {
case ElasticsearchProjectionConstants.SOURCE:
projections[i] = hit.getAsJsonObject().get( "_source" ).toString();
break;
case ElasticsearchProjectionConstants.ID:
projections[i] = id;
break;
case ElasticsearchProjectionConstants.OBJECT_CLASS:
projections[i] = clazz;
break;
case ElasticsearchProjectionConstants.SCORE:
projections[i] = hit.getAsJsonObject().get( "_score" ).getAsFloat();
break;
case ElasticsearchProjectionConstants.SPATIAL_DISTANCE:
JsonElement distance = null;
// if we sort by distance, we need to find the index of the DistanceSortField and use it
// to extract the values from the sort array
// if we don't sort by distance, we use the field generated by the script_field added earlier
if ( isSortedByDistance() ) {
distance = hit.getAsJsonObject().get( "sort" ).getAsJsonArray().get( sortByDistanceIndex );
}
else {
JsonElement fields = hit.getAsJsonObject().get( "fields" );
if ( fields != null ) { // "fields" seems to be missing if there are only null results in script fields
distance = hit.getAsJsonObject().get( "fields" ).getAsJsonObject().get( SPATIAL_DISTANCE_FIELD );
}
}
if ( distance != null && distance.isJsonArray() ) {
JsonArray array = distance.getAsJsonArray();
distance = array.size() >= 1 ? array.get( 0 ) : null;
}
if ( distance == null || distance.isJsonNull() ) {
projections[i] = null;
}
else {
Double distanceAsDouble = distance.getAsDouble();
if ( distanceAsDouble == Double.MAX_VALUE || distanceAsDouble.isInfinite() ) {
/*
* When we extract the distance from the sort, its default value is:
* - Double.MAX_VALUE on older ES versions (5.0 and lower)
* - Double.POSITIVE_INFINITY on newer ES versions (from somewhere around 5.2 onwards)
*/
projections[i] = null;
}
else {
projections[i] = distance.getAsDouble();
}
}
break;
case ElasticsearchProjectionConstants.TOOK:
projections[i] = searchResult.getTook();
break;
case ElasticsearchProjectionConstants.TIMED_OUT:
projections[i] = searchResult.getTimedOut();
break;
case ElasticsearchProjectionConstants.THIS:
// Use EntityInfo.ENTITY_PLACEHOLDER as placeholder.
// It will be replaced when we populate
// the EntityInfo with the real entity.
projections[i] = EntityInfo.ENTITY_PLACEHOLDER;
break;
default:
FieldProjection projection = fieldProjectionsByEntityType.get( clazz )[i];
projections[i] = projection.convertHit( hit, conversionContext );
}
}
}
return new EntityInfoImpl( clazz, binding.getDocumentBuilder().getIdPropertyName(), (Serializable) id, projections );
}
}
private abstract static class FieldProjection {
/**
* Returns the value of the projected field as retrieved from the ES result and converted using the corresponding
* field bridge. In case this bridge is not a 2-way bridge, the unconverted value will be returned.
*/
public abstract Object convertHit(JsonObject hit, ConversionContext conversionContext);
protected final JsonElement extractFieldValue(JsonObject parent, String projectedField) {
String field = projectedField;
if ( FieldHelper.isEmbeddedField( projectedField ) ) {
String[] parts = DOT.split( projectedField );
field = parts[parts.length - 1];
for ( int i = 0; i < parts.length - 1; i++ ) {
JsonElement newParent = parent.get( parts[i] );
if ( newParent == null ) {
return null;
}
parent = newParent.getAsJsonObject();
}
}
return parent.getAsJsonObject().get( field );
}
}
private static class TwoWayFieldBridgeProjection extends FieldProjection {
private final String absoluteName;
private final TwoWayFieldBridge bridge;
private final PrimitiveProjection defaultFieldProjection;
private final List<PrimitiveProjection> bridgeDefinedFieldsProjections;
public TwoWayFieldBridgeProjection(String absoluteName,
TwoWayFieldBridge bridge,
PrimitiveProjection defaultFieldProjection,
List<PrimitiveProjection> bridgeDefinedFieldsProjections) {
super();
this.absoluteName = absoluteName;
this.bridge = bridge;
this.defaultFieldProjection = defaultFieldProjection;
this.bridgeDefinedFieldsProjections = bridgeDefinedFieldsProjections;
}
@Override
public Object convertHit(JsonObject hit, ConversionContext conversionContext) {
return convertFieldValue( hit, conversionContext );
}
private Object convertFieldValue(JsonObject hit, ConversionContext conversionContext) {
Document tmp = new Document();
defaultFieldProjection.addDocumentField( tmp, hit, conversionContext );
// Add to the document the additional fields created when indexing the value
for ( PrimitiveProjection subProjection : bridgeDefinedFieldsProjections ) {
subProjection.addDocumentField( tmp, hit, conversionContext );
}
return conversionContext.twoWayConversionContext( bridge ).get( absoluteName, tmp );
}
}
private static class PrimitiveProjection extends FieldProjection {
private final TypeMetadata rootTypeMetadata;
private final String absoluteName;
private final ExtendedFieldType fieldType;
public PrimitiveProjection(TypeMetadata rootTypeMetadata, String absoluteName, ExtendedFieldType fieldType) {
super();
this.rootTypeMetadata = rootTypeMetadata;
this.absoluteName = absoluteName;
this.fieldType = fieldType;
}
public void addDocumentField(Document tmp, JsonObject hit, ConversionContext conversionContext) {
JsonElement jsonValue = extractFieldValue( hit.get( "_source" ).getAsJsonObject(), absoluteName );
if ( jsonValue == null || jsonValue.isJsonNull() ) {
return;
}
switch ( fieldType ) {
case INTEGER:
tmp.add( new IntField( absoluteName, jsonValue.getAsInt(), Store.NO ) );
break;
case LONG:
tmp.add( new LongField( absoluteName, jsonValue.getAsLong(), Store.NO ) );
break;
case FLOAT:
tmp.add( new FloatField( absoluteName, jsonValue.getAsFloat(), Store.NO ) );
break;
case DOUBLE:
tmp.add( new DoubleField( absoluteName, jsonValue.getAsDouble(), Store.NO ) );
break;
case UNKNOWN_NUMERIC:
throw LOG.unexpectedNumericEncodingType( rootTypeMetadata.getType().getName(), absoluteName );
case BOOLEAN:
tmp.add( new StringField( absoluteName, String.valueOf( jsonValue.getAsBoolean() ), Store.NO ) );
break;
default:
tmp.add( new StringField( absoluteName, jsonValue.getAsString(), Store.NO ) );
break;
}
}
@Override
public Object convertHit(JsonObject hit, ConversionContext conversionContext) {
JsonElement jsonValue = extractFieldValue( hit.get( "_source" ).getAsJsonObject(), absoluteName );
if ( jsonValue == null || jsonValue.isJsonNull() ) {
return null;
}
switch ( fieldType ) {
case INTEGER:
return jsonValue.getAsInt();
case LONG:
return jsonValue.getAsLong();
case FLOAT:
return jsonValue.getAsFloat();
case DOUBLE:
return jsonValue.getAsDouble();
case UNKNOWN_NUMERIC:
throw LOG.unexpectedNumericEncodingType( rootTypeMetadata.getType().getName(), absoluteName );
case BOOLEAN:
return jsonValue.getAsBoolean();
default:
return jsonValue.getAsString();
}
}
}
private static class JsonDrivenProjection extends FieldProjection {
private final String absoluteName;
public JsonDrivenProjection(String absoluteName) {
super();
this.absoluteName = absoluteName;
}
@Override
public Object convertHit(JsonObject hit, ConversionContext conversionContext) {
JsonElement value = extractFieldValue( hit.get( "_source" ).getAsJsonObject(), absoluteName );
if ( value == null || value.isJsonNull() ) {
return null;
}
// TODO: HSEARCH-2255 should we do it?
if ( !value.isJsonPrimitive() ) {
throw LOG.unsupportedProjectionOfNonJsonPrimitiveFields( value );
}
JsonPrimitive primitive = value.getAsJsonPrimitive();
if ( primitive.isBoolean() ) {
return primitive.getAsBoolean();
}
else if ( primitive.isNumber() ) {
// TODO HSEARCH-2255 this will expose a Gson-specific Number implementation; Can we somehow return an Integer,
// Long... etc. instead?
return primitive.getAsNumber();
}
else if ( primitive.isString() ) {
return primitive.getAsString();
}
else {
// TODO HSEARCH-2255 Better raise an exception?
return primitive.toString();
}
}
}
/**
* A projection used whenever a given type has a one-way field bridge, which is forbidden.
*
* @author Yoann Rodiere
*/
private static class FailingOneWayFieldBridgeProjection extends FieldProjection {
private final String absoluteName;