-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
SearchPipelineServiceTests.java
1343 lines (1195 loc) · 66.1 KB
/
SearchPipelineServiceTests.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
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
package org.opensearch.search.pipeline;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TotalHits;
import org.junit.Before;
import org.opensearch.OpenSearchParseException;
import org.opensearch.ResourceNotFoundException;
import org.opensearch.Version;
import org.opensearch.action.search.DeleteSearchPipelineRequest;
import org.opensearch.action.search.MockSearchPhaseContext;
import org.opensearch.action.search.PutSearchPipelineRequest;
import org.opensearch.action.search.QueryPhaseResultConsumer;
import org.opensearch.action.search.SearchPhaseContext;
import org.opensearch.action.search.SearchPhaseController;
import org.opensearch.action.search.SearchPhaseName;
import org.opensearch.action.search.SearchPhaseResults;
import org.opensearch.action.search.SearchProgressListener;
import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.search.SearchResponse;
import org.opensearch.action.search.SearchResponseSections;
import org.opensearch.client.Client;
import org.opensearch.cluster.ClusterChangedEvent;
import org.opensearch.cluster.ClusterName;
import org.opensearch.cluster.ClusterState;
import org.opensearch.cluster.metadata.IndexMetadata;
import org.opensearch.cluster.metadata.Metadata;
import org.opensearch.cluster.node.DiscoveryNode;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.breaker.CircuitBreaker;
import org.opensearch.common.breaker.NoopCircuitBreaker;
import org.opensearch.common.bytes.BytesArray;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.lucene.search.TopDocsAndMaxScore;
import org.opensearch.common.metrics.OperationStats;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.util.concurrent.AtomicArray;
import org.opensearch.common.util.concurrent.OpenSearchExecutors;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.index.IndexSettings;
import org.opensearch.index.query.TermQueryBuilder;
import org.opensearch.plugins.SearchPipelinePlugin;
import org.opensearch.search.SearchHit;
import org.opensearch.search.SearchHits;
import org.opensearch.search.SearchModule;
import org.opensearch.search.SearchPhaseResult;
import org.opensearch.search.builder.SearchSourceBuilder;
import org.opensearch.search.query.QuerySearchResult;
import org.opensearch.test.InternalAggregationTestCase;
import org.opensearch.test.MockLogAppender;
import org.opensearch.test.OpenSearchTestCase;
import org.opensearch.threadpool.ThreadPool;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SearchPipelineServiceTests extends OpenSearchTestCase {
private static final SearchPipelinePlugin DUMMY_PLUGIN = new SearchPipelinePlugin() {
@Override
public Map<String, Processor.Factory<SearchRequestProcessor>> getRequestProcessors(Parameters parameters) {
return Map.of("foo", (factories, tag, description, ignoreFailure, config, ctx) -> null);
}
public Map<String, Processor.Factory<SearchResponseProcessor>> getResponseProcessors(Parameters parameters) {
return Map.of("bar", (factories, tag, description, ignoreFailure, config, ctx) -> null);
}
@Override
public Map<String, Processor.Factory<SearchPhaseResultsProcessor>> getSearchPhaseResultsProcessors(Parameters parameters) {
return Map.of("zoe", (factories, tag, description, ignoreFailure, config, ctx) -> null);
}
};
private ThreadPool threadPool;
@Before
public void setup() {
threadPool = mock(ThreadPool.class);
ExecutorService executorService = OpenSearchExecutors.newDirectExecutorService();
when(threadPool.generic()).thenReturn(executorService);
when(threadPool.executor(anyString())).thenReturn(executorService);
}
public void testSearchPipelinePlugin() {
Client client = mock(Client.class);
SearchPipelineService searchPipelineService = new SearchPipelineService(
mock(ClusterService.class),
threadPool,
null,
null,
null,
this.xContentRegistry(),
this.writableRegistry(),
List.of(DUMMY_PLUGIN),
client,
false
);
Map<String, Processor.Factory<SearchRequestProcessor>> requestProcessorFactories = searchPipelineService
.getRequestProcessorFactories();
assertEquals(1, requestProcessorFactories.size());
assertTrue(requestProcessorFactories.containsKey("foo"));
Map<String, Processor.Factory<SearchResponseProcessor>> responseProcessorFactories = searchPipelineService
.getResponseProcessorFactories();
assertEquals(1, responseProcessorFactories.size());
assertTrue(responseProcessorFactories.containsKey("bar"));
}
public void testSearchPipelinePluginDuplicate() {
Client client = mock(Client.class);
IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new SearchPipelineService(
mock(ClusterService.class),
threadPool,
null,
null,
null,
this.xContentRegistry(),
this.writableRegistry(),
List.of(DUMMY_PLUGIN, DUMMY_PLUGIN),
client,
false
)
);
assertTrue(e.getMessage(), e.getMessage().contains(" already registered"));
}
public void testResolveSearchPipelineDoesNotExist() {
Client client = mock(Client.class);
SearchPipelineService searchPipelineService = new SearchPipelineService(
mock(ClusterService.class),
threadPool,
null,
null,
null,
this.xContentRegistry(),
this.writableRegistry(),
List.of(DUMMY_PLUGIN),
client,
true
);
final SearchRequest searchRequest = new SearchRequest("_index").pipeline("bar");
IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> searchPipelineService.resolvePipeline(searchRequest)
);
assertTrue(e.getMessage(), e.getMessage().contains(" not defined"));
}
public void testResolveIndexDefaultPipeline() throws Exception {
SearchPipelineService service = createWithProcessors();
SearchPipelineMetadata metadata = new SearchPipelineMetadata(
Map.of(
"p1",
new PipelineConfiguration(
"p1",
new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"),
XContentType.JSON
)
)
);
Settings defaultPipelineSetting = Settings.builder()
.put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1)
.put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 0)
.put(IndexMetadata.SETTING_INDEX_VERSION_CREATED.getKey(), Version.CURRENT)
.put(IndexSettings.DEFAULT_SEARCH_PIPELINE.getKey(), "p1")
.build();
IndexMetadata indexMetadata = new IndexMetadata.Builder("my_index").settings(defaultPipelineSetting).build();
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousState = clusterState;
clusterState = ClusterState.builder(clusterState)
.metadata(Metadata.builder().put(indexMetadata, false).putCustom(SearchPipelineMetadata.TYPE, metadata))
.build();
ClusterChangedEvent cce = new ClusterChangedEvent("", clusterState, previousState);
service.applyClusterState(cce);
SearchRequest searchRequest = new SearchRequest("my_index").source(SearchSourceBuilder.searchSource().size(5));
PipelinedRequest pipelinedRequest = service.resolvePipeline(searchRequest);
assertEquals("p1", pipelinedRequest.getPipeline().getId());
assertEquals(10, pipelinedRequest.source().size());
// Bypass the default pipeline
searchRequest.pipeline("_none");
pipelinedRequest = service.resolvePipeline(searchRequest);
assertEquals("_none", pipelinedRequest.getPipeline().getId());
assertEquals(5, pipelinedRequest.source().size());
}
private static class FakeRequestProcessor extends AbstractProcessor implements SearchRequestProcessor {
private final Consumer<SearchRequest> executor;
private final String type;
public FakeRequestProcessor(String type, String tag, String description, boolean ignoreFailure, Consumer<SearchRequest> executor) {
super(tag, description, ignoreFailure);
this.executor = executor;
this.type = type;
}
@Override
public SearchRequest processRequest(SearchRequest request) throws Exception {
executor.accept(request);
return request;
}
/*
* Gets the type of processor
*/
@Override
public String getType() {
return this.type;
}
}
private static class FakeResponseProcessor extends AbstractProcessor implements SearchResponseProcessor {
private final Consumer<SearchResponse> executor;
private String type;
public FakeResponseProcessor(
String type,
String tag,
String description,
boolean ignoreFailure,
Consumer<SearchResponse> executor
) {
super(tag, description, ignoreFailure);
this.executor = executor;
this.type = type;
}
@Override
public SearchResponse processResponse(SearchRequest request, SearchResponse response) throws Exception {
executor.accept(response);
return response;
}
/**
* Gets the type of processor
*/
@Override
public String getType() {
return this.type;
}
}
private static class FakeSearchPhaseResultsProcessor extends AbstractProcessor implements SearchPhaseResultsProcessor {
private Consumer<SearchPhaseResult> querySearchResultConsumer;
private String type;
public FakeSearchPhaseResultsProcessor(
String type,
String tag,
String description,
boolean ignoreFailure,
Consumer<SearchPhaseResult> querySearchResultConsumer
) {
super(tag, description, ignoreFailure);
this.querySearchResultConsumer = querySearchResultConsumer;
this.type = type;
}
@Override
public <Result extends SearchPhaseResult> void process(
SearchPhaseResults<Result> searchPhaseResult,
SearchPhaseContext searchPhaseContext
) {
List<Result> resultAtomicArray = searchPhaseResult.getAtomicArray().asList();
// updating the maxScore
resultAtomicArray.forEach(querySearchResultConsumer);
}
@Override
public SearchPhaseName getBeforePhase() {
return SearchPhaseName.QUERY;
}
@Override
public SearchPhaseName getAfterPhase() {
return SearchPhaseName.FETCH;
}
/**
* Gets the type of processor
*/
@Override
public String getType() {
return this.type;
}
}
private SearchPipelineService createWithProcessors() {
Map<String, Processor.Factory<SearchRequestProcessor>> requestProcessors = new HashMap<>();
requestProcessors.put("scale_request_size", (processorFactories, tag, description, ignoreFailure, config, ctx) -> {
float scale = ((Number) config.remove("scale")).floatValue();
return new FakeRequestProcessor(
"scale_request_size",
tag,
description,
ignoreFailure,
req -> req.source().size((int) (req.source().size() * scale))
);
});
Map<String, Processor.Factory<SearchResponseProcessor>> responseProcessors = new HashMap<>();
responseProcessors.put("fixed_score", (processorFactories, tag, description, ignoreFailure, config, ctx) -> {
float score = ((Number) config.remove("score")).floatValue();
return new FakeResponseProcessor(
"fixed_score",
tag,
description,
ignoreFailure,
rsp -> rsp.getHits().forEach(h -> h.score(score))
);
});
Map<String, Processor.Factory<SearchPhaseResultsProcessor>> searchPhaseProcessors = new HashMap<>();
searchPhaseProcessors.put("max_score", (processorFactories, tag, description, ignoreFailure, config, context) -> {
final float finalScore = config.containsKey("score") ? ((Number) config.remove("score")).floatValue() : 100f;
final Consumer<SearchPhaseResult> querySearchResultConsumer = (result) -> result.queryResult().topDocs().maxScore = finalScore;
return new FakeSearchPhaseResultsProcessor("max_score", tag, description, ignoreFailure, querySearchResultConsumer);
});
return createWithProcessors(requestProcessors, responseProcessors, searchPhaseProcessors);
}
@Override
protected NamedWriteableRegistry writableRegistry() {
SearchModule searchModule = new SearchModule(Settings.EMPTY, Collections.emptyList());
return new NamedWriteableRegistry(searchModule.getNamedWriteables());
}
private SearchPipelineService createWithProcessors(
Map<String, Processor.Factory<SearchRequestProcessor>> requestProcessors,
Map<String, Processor.Factory<SearchResponseProcessor>> responseProcessors,
Map<String, Processor.Factory<SearchPhaseResultsProcessor>> phaseProcessors
) {
Client client = mock(Client.class);
ThreadPool threadPool = mock(ThreadPool.class);
ExecutorService executorService = OpenSearchExecutors.newDirectExecutorService();
when(threadPool.generic()).thenReturn(executorService);
when(threadPool.executor(anyString())).thenReturn(executorService);
return new SearchPipelineService(
mock(ClusterService.class),
threadPool,
null,
null,
null,
null,
this.writableRegistry(),
Collections.singletonList(new SearchPipelinePlugin() {
@Override
public Map<String, Processor.Factory<SearchRequestProcessor>> getRequestProcessors(Parameters parameters) {
return requestProcessors;
}
@Override
public Map<String, Processor.Factory<SearchResponseProcessor>> getResponseProcessors(Parameters parameters) {
return responseProcessors;
}
@Override
public Map<String, Processor.Factory<SearchPhaseResultsProcessor>> getSearchPhaseResultsProcessors(Parameters parameters) {
return phaseProcessors;
}
}),
client,
true
);
}
public void testUpdatePipelines() {
SearchPipelineService searchPipelineService = createWithProcessors();
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousClusterState = clusterState;
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState));
assertEquals(0, searchPipelineService.getPipelines().size());
PipelineConfiguration pipeline = new PipelineConfiguration(
"_id",
new BytesArray(
"{ "
+ "\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ], "
+ "\"response_processors\" : [ { \"fixed_score\" : { \"score\" : 1.0 } } ],"
+ "\"phase_results_processors\" : [ { \"max_score\" : { \"score\": 100 } } ]"
+ "}"
),
XContentType.JSON
);
SearchPipelineMetadata pipelineMetadata = new SearchPipelineMetadata(Map.of("_id", pipeline));
clusterState = ClusterState.builder(clusterState)
.metadata(Metadata.builder().putCustom(SearchPipelineMetadata.TYPE, pipelineMetadata).build())
.build();
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState));
assertEquals(1, searchPipelineService.getPipelines().size());
assertEquals("_id", searchPipelineService.getPipelines().get("_id").pipeline.getId());
assertNull(searchPipelineService.getPipelines().get("_id").pipeline.getDescription());
assertEquals(1, searchPipelineService.getPipelines().get("_id").pipeline.getSearchRequestProcessors().size());
assertEquals(
"scale_request_size",
searchPipelineService.getPipelines().get("_id").pipeline.getSearchRequestProcessors().get(0).getType()
);
assertEquals(1, searchPipelineService.getPipelines().get("_id").pipeline.getSearchPhaseResultsProcessors().size());
assertEquals(
"max_score",
searchPipelineService.getPipelines().get("_id").pipeline.getSearchPhaseResultsProcessors().get(0).getType()
);
assertEquals(1, searchPipelineService.getPipelines().get("_id").pipeline.getSearchResponseProcessors().size());
assertEquals(
"fixed_score",
searchPipelineService.getPipelines().get("_id").pipeline.getSearchResponseProcessors().get(0).getType()
);
}
public void testPutPipeline() {
SearchPipelineService searchPipelineService = createWithProcessors();
String id = "_id";
SearchPipelineService.PipelineHolder pipeline = searchPipelineService.getPipelines().get(id);
assertNull(pipeline);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
PutSearchPipelineRequest putRequest = new PutSearchPipelineRequest(id, new BytesArray("{}"), XContentType.JSON);
ClusterState previousClusterState = clusterState;
clusterState = SearchPipelineService.innerPut(putRequest, clusterState);
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState));
pipeline = searchPipelineService.getPipelines().get(id);
assertNotNull(pipeline);
assertEquals(id, pipeline.pipeline.getId());
assertNull(pipeline.pipeline.getDescription());
assertEquals(0, pipeline.pipeline.getSearchRequestProcessors().size());
assertEquals(0, pipeline.pipeline.getSearchResponseProcessors().size());
// Overwrite pipeline
putRequest = new PutSearchPipelineRequest(id, new BytesArray("{ \"description\": \"empty pipeline\"}"), XContentType.JSON);
previousClusterState = clusterState;
clusterState = SearchPipelineService.innerPut(putRequest, clusterState);
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState));
pipeline = searchPipelineService.getPipelines().get(id);
assertNotNull(pipeline);
assertEquals(id, pipeline.pipeline.getId());
assertEquals("empty pipeline", pipeline.pipeline.getDescription());
assertEquals(0, pipeline.pipeline.getSearchRequestProcessors().size());
assertEquals(0, pipeline.pipeline.getSearchResponseProcessors().size());
assertEquals(0, pipeline.pipeline.getSearchPhaseResultsProcessors().size());
}
public void testPutInvalidPipeline() throws IllegalAccessException {
SearchPipelineService searchPipelineService = createWithProcessors();
String id = "_id";
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousState = clusterState;
PutSearchPipelineRequest putRequest = new PutSearchPipelineRequest(
id,
new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : \"foo\" } } ] }"),
XContentType.JSON
);
clusterState = SearchPipelineService.innerPut(putRequest, clusterState);
try (MockLogAppender mockAppender = MockLogAppender.createForLoggers(LogManager.getLogger(SearchPipelineService.class))) {
mockAppender.addExpectation(
new MockLogAppender.SeenEventExpectation(
"test1",
SearchPipelineService.class.getCanonicalName(),
Level.WARN,
"failed to update search pipelines"
)
);
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
mockAppender.assertAllExpectationsMatched();
}
assertEquals(0, searchPipelineService.getPipelines().size());
}
public void testDeletePipeline() {
SearchPipelineService searchPipelineService = createWithProcessors();
PipelineConfiguration config = new PipelineConfiguration(
"_id",
new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"),
XContentType.JSON
);
SearchPipelineMetadata searchPipelineMetadata = new SearchPipelineMetadata(Map.of("_id", config));
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousState = clusterState;
clusterState = ClusterState.builder(clusterState)
.metadata(Metadata.builder().putCustom(SearchPipelineMetadata.TYPE, searchPipelineMetadata).build())
.build();
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
assertEquals(1, searchPipelineService.getPipelines().size());
// Delete pipeline:
DeleteSearchPipelineRequest deleteRequest = new DeleteSearchPipelineRequest("_id");
previousState = clusterState;
clusterState = SearchPipelineService.innerDelete(deleteRequest, clusterState);
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
assertEquals(0, searchPipelineService.getPipelines().size());
final ClusterState finalClusterState = clusterState;
// Delete missing pipeline
ResourceNotFoundException e = expectThrows(
ResourceNotFoundException.class,
() -> SearchPipelineService.innerDelete(deleteRequest, finalClusterState)
);
assertEquals("pipeline [_id] is missing", e.getMessage());
}
public void testDeletePipelinesWithWildcard() {
SearchPipelineService searchPipelineService = createWithProcessors();
BytesArray definition = new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }");
SearchPipelineMetadata metadata = new SearchPipelineMetadata(
Map.of(
"p1",
new PipelineConfiguration("p1", definition, XContentType.JSON),
"p2",
new PipelineConfiguration("p2", definition, XContentType.JSON),
"q1",
new PipelineConfiguration("q1", definition, XContentType.JSON)
)
);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousState = clusterState;
clusterState = ClusterState.builder(clusterState)
.metadata(Metadata.builder().putCustom(SearchPipelineMetadata.TYPE, metadata))
.build();
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
assertNotNull(searchPipelineService.getPipelines().get("p1"));
assertNotNull(searchPipelineService.getPipelines().get("p2"));
assertNotNull(searchPipelineService.getPipelines().get("q1"));
// Delete all pipelines starting with "p"
DeleteSearchPipelineRequest deleteRequest = new DeleteSearchPipelineRequest("p*");
previousState = clusterState;
clusterState = SearchPipelineService.innerDelete(deleteRequest, clusterState);
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
assertEquals(1, searchPipelineService.getPipelines().size());
assertNotNull(searchPipelineService.getPipelines().get("q1"));
// Prefix wildcard fails if no matches
final ClusterState finalClusterState = clusterState;
ResourceNotFoundException e = expectThrows(
ResourceNotFoundException.class,
() -> SearchPipelineService.innerDelete(deleteRequest, finalClusterState)
);
assertEquals("pipeline [p*] is missing", e.getMessage());
// Delete all removes remaining pipeline
DeleteSearchPipelineRequest deleteAllRequest = new DeleteSearchPipelineRequest("*");
previousState = clusterState;
clusterState = SearchPipelineService.innerDelete(deleteAllRequest, clusterState);
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
assertEquals(0, searchPipelineService.getPipelines().size());
// Delete all does not throw exception if no pipelines
SearchPipelineService.innerDelete(deleteAllRequest, clusterState);
}
public void testTransformRequest() throws Exception {
SearchPipelineService searchPipelineService = createWithProcessors();
SearchPipelineMetadata metadata = new SearchPipelineMetadata(
Map.of(
"p1",
new PipelineConfiguration(
"p1",
new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"),
XContentType.JSON
)
)
);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousState = clusterState;
clusterState = ClusterState.builder(clusterState)
.metadata(Metadata.builder().putCustom(SearchPipelineMetadata.TYPE, metadata))
.build();
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
int size = 10;
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(new TermQueryBuilder("foo", "bar")).size(size);
SearchRequest request = new SearchRequest("_index").source(sourceBuilder).pipeline("p1");
PipelinedRequest pipelinedRequest = searchPipelineService.resolvePipeline(request);
assertEquals(2 * size, pipelinedRequest.source().size());
assertEquals(size, request.source().size());
// This request doesn't specify a pipeline, it doesn't get transformed.
request = new SearchRequest("_index").source(sourceBuilder);
pipelinedRequest = searchPipelineService.resolvePipeline(request);
assertEquals(size, pipelinedRequest.source().size());
}
public void testTransformResponse() throws Exception {
SearchPipelineService searchPipelineService = createWithProcessors();
SearchPipelineMetadata metadata = new SearchPipelineMetadata(
Map.of(
"p1",
new PipelineConfiguration(
"p1",
new BytesArray("{\"response_processors\" : [ { \"fixed_score\": { \"score\" : 2 } } ] }"),
XContentType.JSON
)
)
);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousState = clusterState;
clusterState = ClusterState.builder(clusterState)
.metadata(Metadata.builder().putCustom(SearchPipelineMetadata.TYPE, metadata))
.build();
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
int size = 10;
SearchHit[] hits = new SearchHit[size];
for (int i = 0; i < size; i++) {
hits[i] = new SearchHit(i, "doc" + i, Collections.emptyMap(), Collections.emptyMap());
hits[i].score(i);
}
SearchHits searchHits = new SearchHits(hits, new TotalHits(size * 2, TotalHits.Relation.EQUAL_TO), size);
SearchResponseSections searchResponseSections = new SearchResponseSections(searchHits, null, null, false, false, null, 0);
SearchResponse searchResponse = new SearchResponse(searchResponseSections, null, 1, 1, 0, 10, null, null);
// First try without specifying a pipeline, which should be a no-op.
SearchRequest searchRequest = new SearchRequest();
PipelinedRequest pipelinedRequest = searchPipelineService.resolvePipeline(searchRequest);
SearchResponse notTransformedResponse = pipelinedRequest.transformResponse(searchResponse);
assertSame(searchResponse, notTransformedResponse);
// Now apply a pipeline
searchRequest = new SearchRequest().pipeline("p1");
pipelinedRequest = searchPipelineService.resolvePipeline(searchRequest);
SearchResponse transformedResponse = pipelinedRequest.transformResponse(searchResponse);
assertEquals(size, transformedResponse.getHits().getHits().length);
for (int i = 0; i < size; i++) {
assertEquals(2.0, transformedResponse.getHits().getHits()[i].getScore(), 0.0001f);
}
}
public void testTransformSearchPhase() {
SearchPipelineService searchPipelineService = createWithProcessors();
SearchPipelineMetadata metadata = new SearchPipelineMetadata(
Map.of(
"p1",
new PipelineConfiguration(
"p1",
new BytesArray("{\"phase_results_processors\" : [ { \"max_score\" : { } } ]}"),
XContentType.JSON
)
)
);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build();
ClusterState previousState = clusterState;
clusterState = ClusterState.builder(clusterState)
.metadata(Metadata.builder().putCustom(SearchPipelineMetadata.TYPE, metadata))
.build();
searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousState));
SearchPhaseController controller = new SearchPhaseController(
writableRegistry(),
s -> InternalAggregationTestCase.emptyReduceContextBuilder()
);
SearchPhaseContext searchPhaseContext = new MockSearchPhaseContext(10);
QueryPhaseResultConsumer searchPhaseResults = new QueryPhaseResultConsumer(
searchPhaseContext.getRequest(),
OpenSearchExecutors.newDirectExecutorService(),
new NoopCircuitBreaker(CircuitBreaker.REQUEST),
controller,
SearchProgressListener.NOOP,
writableRegistry(),
2,
exc -> {}
);
final QuerySearchResult querySearchResult = new QuerySearchResult();
querySearchResult.setShardIndex(1);
querySearchResult.topDocs(new TopDocsAndMaxScore(new TopDocs(null, new ScoreDoc[1]), 1f), null);
searchPhaseResults.consumeResult(querySearchResult, () -> {});
// First try without specifying a pipeline, which should be a no-op.
SearchRequest searchRequest = new SearchRequest();
PipelinedRequest pipelinedRequest = searchPipelineService.resolvePipeline(searchRequest);
AtomicArray<SearchPhaseResult> notTransformedSearchPhaseResults = searchPhaseResults.getAtomicArray();
pipelinedRequest.transformSearchPhaseResults(
searchPhaseResults,
searchPhaseContext,
SearchPhaseName.QUERY.getName(),
SearchPhaseName.FETCH.getName()
);
assertSame(searchPhaseResults.getAtomicArray(), notTransformedSearchPhaseResults);
// Now set the pipeline as p1
searchRequest = new SearchRequest().pipeline("p1");
pipelinedRequest = searchPipelineService.resolvePipeline(searchRequest);
pipelinedRequest.transformSearchPhaseResults(
searchPhaseResults,
searchPhaseContext,
SearchPhaseName.QUERY.getName(),
SearchPhaseName.FETCH.getName()
);
List<SearchPhaseResult> resultAtomicArray = searchPhaseResults.getAtomicArray().asList();
assertEquals(1, resultAtomicArray.size());
// updating the maxScore
for (SearchPhaseResult result : resultAtomicArray) {
assertEquals(100f, result.queryResult().topDocs().maxScore, 0);
}
// Check Processor doesn't run for between other phases
searchRequest = new SearchRequest().pipeline("p1");
pipelinedRequest = searchPipelineService.resolvePipeline(searchRequest);
AtomicArray<SearchPhaseResult> notTransformedSearchPhaseResult = searchPhaseResults.getAtomicArray();
pipelinedRequest.transformSearchPhaseResults(
searchPhaseResults,
searchPhaseContext,
SearchPhaseName.DFS_QUERY.getName(),
SearchPhaseName.QUERY.getName()
);
assertSame(searchPhaseResults.getAtomicArray(), notTransformedSearchPhaseResult);
}
public void testGetPipelines() {
//
assertEquals(0, SearchPipelineService.innerGetPipelines(null, "p1").size());
SearchPipelineMetadata metadata = new SearchPipelineMetadata(
Map.of(
"p1",
new PipelineConfiguration(
"p1",
new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"),
XContentType.JSON
),
"p2",
new PipelineConfiguration(
"p2",
new BytesArray("{\"response_processors\" : [ { \"fixed_score\": { \"score\" : 2 } } ] }"),
XContentType.JSON
),
"p3",
new PipelineConfiguration(
"p3",
new BytesArray("{\"phase_results_processors\" : [ { \"max_score\" : { } } ]}"),
XContentType.JSON
)
)
);
// Return all when no ids specified
List<PipelineConfiguration> pipelines = SearchPipelineService.innerGetPipelines(metadata);
assertEquals(3, pipelines.size());
pipelines.sort(Comparator.comparing(PipelineConfiguration::getId));
assertEquals("p1", pipelines.get(0).getId());
assertEquals("p2", pipelines.get(1).getId());
assertEquals("p3", pipelines.get(2).getId());
// Get specific pipeline
pipelines = SearchPipelineService.innerGetPipelines(metadata, "p1");
assertEquals(1, pipelines.size());
assertEquals("p1", pipelines.get(0).getId());
// Get both pipelines explicitly
pipelines = SearchPipelineService.innerGetPipelines(metadata, "p1", "p2");
assertEquals(2, pipelines.size());
pipelines.sort(Comparator.comparing(PipelineConfiguration::getId));
assertEquals("p1", pipelines.get(0).getId());
assertEquals("p2", pipelines.get(1).getId());
// Match all
pipelines = SearchPipelineService.innerGetPipelines(metadata, "*");
assertEquals(3, pipelines.size());
pipelines.sort(Comparator.comparing(PipelineConfiguration::getId));
assertEquals("p1", pipelines.get(0).getId());
assertEquals("p2", pipelines.get(1).getId());
assertEquals("p3", pipelines.get(2).getId());
// Match prefix
pipelines = SearchPipelineService.innerGetPipelines(metadata, "p*");
assertEquals(3, pipelines.size());
pipelines.sort(Comparator.comparing(PipelineConfiguration::getId));
assertEquals("p1", pipelines.get(0).getId());
assertEquals("p2", pipelines.get(1).getId());
assertEquals("p3", pipelines.get(2).getId());
}
public void testValidatePipeline() throws Exception {
SearchPipelineService searchPipelineService = createWithProcessors();
ProcessorInfo reqProcessor = new ProcessorInfo("scale_request_size");
ProcessorInfo rspProcessor = new ProcessorInfo("fixed_score");
ProcessorInfo injProcessor = new ProcessorInfo("max_score");
DiscoveryNode n1 = new DiscoveryNode("n1", buildNewFakeTransportAddress(), Version.CURRENT);
DiscoveryNode n2 = new DiscoveryNode("n2", buildNewFakeTransportAddress(), Version.CURRENT);
PutSearchPipelineRequest putRequest = new PutSearchPipelineRequest(
"p1",
new BytesArray(
"{"
+ "\"request_processors\": [{ \"scale_request_size\": { \"scale\" : 2 } }],"
+ "\"response_processors\": [{ \"fixed_score\": { \"score\" : 2 } }],"
+ "\"phase_results_processors\" : [ { \"max_score\" : { } } ]"
+ "}"
),
XContentType.JSON
);
SearchPipelineInfo completePipelineInfo = new SearchPipelineInfo(
Map.of(Pipeline.REQUEST_PROCESSORS_KEY, List.of(reqProcessor), Pipeline.RESPONSE_PROCESSORS_KEY, List.of(rspProcessor))
);
SearchPipelineInfo incompletePipelineInfo = new SearchPipelineInfo(Map.of(Pipeline.REQUEST_PROCESSORS_KEY, List.of(reqProcessor)));
// One node is missing a processor
expectThrows(
OpenSearchParseException.class,
() -> searchPipelineService.validatePipeline(Map.of(n1, completePipelineInfo, n2, incompletePipelineInfo), putRequest)
);
// Discovery failed, no infos passed.
expectThrows(IllegalStateException.class, () -> searchPipelineService.validatePipeline(Collections.emptyMap(), putRequest));
// Invalid configuration in request
PutSearchPipelineRequest badPutRequest = new PutSearchPipelineRequest(
"p1",
new BytesArray(
"{"
+ "\"request_processors\": [{ \"scale_request_size\": { \"scale\" : \"banana\" } }],"
+ "\"response_processors\": [{ \"fixed_score\": { \"score\" : 2 } }]"
+ "}"
),
XContentType.JSON
);
expectThrows(
ClassCastException.class,
() -> searchPipelineService.validatePipeline(Map.of(n1, completePipelineInfo, n2, completePipelineInfo), badPutRequest)
);
// Success
searchPipelineService.validatePipeline(Map.of(n1, completePipelineInfo, n2, completePipelineInfo), putRequest);
}
/**
* Tests a pipeline defined in the search request source.
*/
public void testInlinePipeline() throws Exception {
SearchPipelineService searchPipelineService = createWithProcessors();
Map<String, Object> pipelineSourceMap = new HashMap<>();
Map<String, Object> requestProcessorConfig = new HashMap<>();
requestProcessorConfig.put("scale", 2);
Map<String, Object> requestProcessorObject = new HashMap<>();
requestProcessorObject.put("scale_request_size", requestProcessorConfig);
pipelineSourceMap.put(Pipeline.REQUEST_PROCESSORS_KEY, List.of(requestProcessorObject));
Map<String, Object> responseProcessorConfig = new HashMap<>();
responseProcessorConfig.put("score", 2);
Map<String, Object> responseProcessorObject = new HashMap<>();
responseProcessorObject.put("fixed_score", responseProcessorConfig);
pipelineSourceMap.put(Pipeline.RESPONSE_PROCESSORS_KEY, List.of(responseProcessorObject));
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource().size(100).searchPipelineSource(pipelineSourceMap);
SearchRequest searchRequest = new SearchRequest().source(sourceBuilder);
// Verify pipeline
PipelinedRequest pipelinedRequest = searchPipelineService.resolvePipeline(searchRequest);
Pipeline pipeline = pipelinedRequest.getPipeline();
assertEquals(SearchPipelineService.AD_HOC_PIPELINE_ID, pipeline.getId());
assertEquals(1, pipeline.getSearchRequestProcessors().size());
assertEquals(1, pipeline.getSearchResponseProcessors().size());
// Verify that pipeline transforms request
assertEquals(200, pipelinedRequest.source().size());
int size = 10;
SearchHit[] hits = new SearchHit[size];
for (int i = 0; i < size; i++) {
hits[i] = new SearchHit(i, "doc" + i, Collections.emptyMap(), Collections.emptyMap());
hits[i].score(i);
}
SearchHits searchHits = new SearchHits(hits, new TotalHits(size * 2, TotalHits.Relation.EQUAL_TO), size);
SearchResponseSections searchResponseSections = new SearchResponseSections(searchHits, null, null, false, false, null, 0);
SearchResponse searchResponse = new SearchResponse(searchResponseSections, null, 1, 1, 0, 10, null, null);
SearchResponse transformedResponse = pipeline.transformResponse(searchRequest, searchResponse);
for (int i = 0; i < size; i++) {
assertEquals(2.0, transformedResponse.getHits().getHits()[i].getScore(), 0.0001);
}
}
public void testInfo() {
SearchPipelineService searchPipelineService = createWithProcessors();
SearchPipelineInfo info = searchPipelineService.info();
assertTrue(info.containsProcessor(Pipeline.REQUEST_PROCESSORS_KEY, "scale_request_size"));
assertTrue(info.containsProcessor(Pipeline.RESPONSE_PROCESSORS_KEY, "fixed_score"));
}
public void testExceptionOnPipelineCreation() {
Map<String, Processor.Factory<SearchRequestProcessor>> badFactory = Map.of("bad_factory", (pf, t, i, f, c, ctx) -> {
throw new RuntimeException();
});
SearchPipelineService searchPipelineService = createWithProcessors(badFactory, Collections.emptyMap(), Collections.emptyMap());
Map<String, Object> pipelineSourceMap = new HashMap<>();
pipelineSourceMap.put(Pipeline.REQUEST_PROCESSORS_KEY, List.of(Map.of("bad_factory", Collections.emptyMap())));
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource().searchPipelineSource(pipelineSourceMap);
SearchRequest searchRequest = new SearchRequest().source(sourceBuilder);
// Exception thrown when creating the pipeline
expectThrows(SearchPipelineProcessingException.class, () -> searchPipelineService.resolvePipeline(searchRequest));
}
public void testExceptionOnRequestProcessing() {
SearchRequestProcessor throwingRequestProcessor = new FakeRequestProcessor("throwing_request", null, null, false, r -> {
throw new RuntimeException();
});
Map<String, Processor.Factory<SearchRequestProcessor>> throwingRequestProcessorFactory = Map.of(
"throwing_request",
(pf, t, i, f, c, ctx) -> throwingRequestProcessor
);
SearchPipelineService searchPipelineService = createWithProcessors(
throwingRequestProcessorFactory,
Collections.emptyMap(),
Collections.emptyMap()
);
Map<String, Object> pipelineSourceMap = new HashMap<>();
pipelineSourceMap.put(Pipeline.REQUEST_PROCESSORS_KEY, List.of(Map.of("throwing_request", Collections.emptyMap())));
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource().searchPipelineSource(pipelineSourceMap);
SearchRequest searchRequest = new SearchRequest().source(sourceBuilder);
// Exception thrown when processing the request
expectThrows(SearchPipelineProcessingException.class, () -> searchPipelineService.resolvePipeline(searchRequest));
}
public void testExceptionOnResponseProcessing() throws Exception {
SearchResponseProcessor throwingResponseProcessor = new FakeResponseProcessor("throwing_response", null, null, false, r -> {
throw new RuntimeException();
});
Map<String, Processor.Factory<SearchResponseProcessor>> throwingResponseProcessorFactory = Map.of(
"throwing_response",
(pf, t, i, f, c, ctx) -> throwingResponseProcessor
);
SearchPipelineService searchPipelineService = createWithProcessors(
Collections.emptyMap(),
throwingResponseProcessorFactory,
Collections.emptyMap()
);
Map<String, Object> pipelineSourceMap = new HashMap<>();
pipelineSourceMap.put(Pipeline.RESPONSE_PROCESSORS_KEY, List.of(Map.of("throwing_response", new HashMap<>())));
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource().size(100).searchPipelineSource(pipelineSourceMap);
SearchRequest searchRequest = new SearchRequest().source(sourceBuilder);
PipelinedRequest pipelinedRequest = searchPipelineService.resolvePipeline(searchRequest);
SearchResponse response = new SearchResponse(null, null, 0, 0, 0, 0, null, null);
// Exception thrown when processing response
expectThrows(SearchPipelineProcessingException.class, () -> pipelinedRequest.transformResponse(response));
}
public void testCatchExceptionOnRequestProcessing() throws IllegalAccessException {
SearchRequestProcessor throwingRequestProcessor = new FakeRequestProcessor("throwing_request", null, null, true, r -> {
throw new RuntimeException();
});
Map<String, Processor.Factory<SearchRequestProcessor>> throwingRequestProcessorFactory = Map.of(
"throwing_request",
(pf, t, i, f, c, ctx) -> throwingRequestProcessor
);
SearchPipelineService searchPipelineService = createWithProcessors(
throwingRequestProcessorFactory,
Collections.emptyMap(),
Collections.emptyMap()
);
Map<String, Object> pipelineSourceMap = new HashMap<>();
pipelineSourceMap.put(Pipeline.REQUEST_PROCESSORS_KEY, List.of(Map.of("throwing_request", Collections.emptyMap())));