forked from opensearch-project/neural-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseNeuralSearchIT.java
1779 lines (1622 loc) · 69.5 KB
/
BaseNeuralSearchIT.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
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.neuralsearch;
import org.junit.After;
import org.opensearch.action.search.SearchResponse;
import org.opensearch.client.ResponseException;
import org.opensearch.core.xcontent.DeprecationHandler;
import org.opensearch.core.xcontent.MediaType;
import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.ml.common.model.MLModelState;
import static org.opensearch.knn.common.KNNConstants.MODEL_INDEX_NAME;
import static org.opensearch.neuralsearch.common.VectorUtil.vectorAsListToArray;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Before;
import org.opensearch.client.Request;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.Response;
import org.opensearch.client.RestClient;
import org.opensearch.client.WarningsHandler;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.index.query.QueryBuilder;
import org.opensearch.knn.index.SpaceType;
import org.opensearch.neuralsearch.processor.NormalizationProcessor;
import org.opensearch.neuralsearch.processor.ExplanationResponseProcessor;
import org.opensearch.neuralsearch.util.NeuralSearchClusterUtil;
import org.opensearch.neuralsearch.util.TokenWeightUtil;
import org.opensearch.search.SearchHit;
import org.opensearch.search.sort.SortBuilder;
import org.opensearch.test.ClusterServiceUtils;
import org.opensearch.threadpool.TestThreadPool;
import org.opensearch.threadpool.ThreadPool;
import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.google.common.collect.ImmutableList;
import static org.opensearch.neuralsearch.util.TestUtils.INGEST_PIPELINE_TYPE;
import static org.opensearch.neuralsearch.util.TestUtils.MAX_TASK_RETRIES;
import static org.opensearch.neuralsearch.util.TestUtils.DEFAULT_TASK_RESULT_QUERY_INTERVAL_IN_MILLISECOND;
import static org.opensearch.neuralsearch.util.TestUtils.DEFAULT_USER_AGENT;
import static org.opensearch.neuralsearch.util.TestUtils.DEFAULT_NORMALIZATION_METHOD;
import static org.opensearch.neuralsearch.util.TestUtils.DEFAULT_COMBINATION_METHOD;
import static org.opensearch.neuralsearch.util.TestUtils.ML_PLUGIN_SYSTEM_INDEX_PREFIX;
import static org.opensearch.neuralsearch.util.TestUtils.OPENDISTRO_SECURITY;
import static org.opensearch.neuralsearch.util.TestUtils.OPENSEARCH_SYSTEM_INDEX_PREFIX;
import static org.opensearch.neuralsearch.util.TestUtils.PARAM_NAME_WEIGHTS;
import static org.opensearch.neuralsearch.util.TestUtils.MAX_RETRY;
import static org.opensearch.neuralsearch.util.TestUtils.MAX_TIME_OUT_INTERVAL;
import static org.opensearch.neuralsearch.util.TestUtils.SEARCH_PIPELINE_TYPE;
import static org.opensearch.neuralsearch.util.TestUtils.SECURITY_AUDITLOG_PREFIX;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.SneakyThrows;
@ThreadLeakScope(ThreadLeakScope.Scope.NONE)
public abstract class BaseNeuralSearchIT extends OpenSearchSecureRestTestCase {
protected static final Locale LOCALE = Locale.ROOT;
protected static final Map<ProcessorType, String> PIPELINE_CONFIGS_BY_TYPE = Map.of(
ProcessorType.TEXT_EMBEDDING,
"processor/PipelineConfiguration.json",
ProcessorType.SPARSE_ENCODING,
"processor/SparseEncodingPipelineConfiguration.json",
ProcessorType.TEXT_IMAGE_EMBEDDING,
"processor/PipelineForTextImageEmbeddingProcessorConfiguration.json",
ProcessorType.TEXT_EMBEDDING_WITH_NESTED_FIELDS_MAPPING,
"processor/PipelineConfigurationWithNestedFieldsMapping.json",
ProcessorType.SPARSE_ENCODING_PRUNE,
"processor/SparseEncodingPipelineConfigurationWithPrune.json"
);
private static final Set<RestStatus> SUCCESS_STATUSES = Set.of(RestStatus.CREATED, RestStatus.OK);
protected static final String CONCURRENT_SEGMENT_SEARCH_ENABLED = "search.concurrent_segment_search.enabled";
protected static final String RRF_SEARCH_PIPELINE = "rrf-search-pipeline";
private final Set<String> IMMUTABLE_INDEX_PREFIXES = Set.of(
SECURITY_AUDITLOG_PREFIX,
OPENSEARCH_SYSTEM_INDEX_PREFIX,
ML_PLUGIN_SYSTEM_INDEX_PREFIX
);
protected final ClassLoader classLoader = this.getClass().getClassLoader();
protected ThreadPool threadPool;
protected ClusterService clusterService;
@Before
public void setupSettings() {
threadPool = setUpThreadPool();
clusterService = createClusterService(threadPool);
if (isUpdateClusterSettings()) {
updateClusterSettings();
}
NeuralSearchClusterUtil.instance().initialize(clusterService);
}
// Wipe of all the resources after execution of the tests.
@After
public void cleanUp() {
if (shouldCleanUpResources()) {
deleteExistingIngestionPipelines();
deleteExistingSearchPipelines();
deleteExistingModels();
deleteExistingIndices();
}
}
protected boolean shouldCleanUpResources() {
return true;
}
protected ThreadPool setUpThreadPool() {
return new TestThreadPool(getClass().getName(), threadPoolSettings());
}
public Settings threadPoolSettings() {
return Settings.EMPTY;
}
public static ClusterService createClusterService(ThreadPool threadPool) {
return ClusterServiceUtils.createClusterService(threadPool);
}
protected void updateClusterSettings() {
updateClusterSettings("plugins.ml_commons.only_run_on_ml_node", false);
// default threshold for native circuit breaker is 90, it may be not enough on test runner machine
updateClusterSettings("plugins.ml_commons.native_memory_threshold", 100);
updateClusterSettings("plugins.ml_commons.jvm_heap_memory_threshold", 95);
updateClusterSettings("plugins.ml_commons.allow_registering_model_via_url", true);
}
@SneakyThrows
protected void updateClusterSettings(final String settingKey, final Object value) {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("persistent")
.field(settingKey, value)
.endObject()
.endObject();
Response response = makeRequest(
client(),
"PUT",
"_cluster/settings",
null,
toHttpEntity(builder.toString()),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, ""))
);
assertEquals(RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
}
protected String registerModelGroupAndUploadModel(final String requestBody) throws Exception {
String modelGroupId = getModelGroupId();
// model group id is dynamically generated, we need to update model update request body after group is registered
return uploadModel(String.format(LOCALE, requestBody, modelGroupId));
}
protected String uploadModel(final String requestBody) throws Exception {
Response uploadResponse = makeRequest(
client(),
"POST",
"/_plugins/_ml/models/_register",
null,
toHttpEntity(requestBody),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> uploadResJson = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(uploadResponse.getEntity()),
false
);
String taskId = uploadResJson.get("task_id").toString();
assertNotNull(taskId);
Map<String, Object> taskQueryResult = getTaskQueryResponse(taskId);
boolean isComplete = checkComplete(taskQueryResult);
for (int i = 0; !isComplete && i < MAX_TASK_RETRIES; i++) {
taskQueryResult = getTaskQueryResponse(taskId);
isComplete = checkComplete(taskQueryResult);
Thread.sleep(DEFAULT_TASK_RESULT_QUERY_INTERVAL_IN_MILLISECOND);
}
String modelId = Optional.ofNullable(taskQueryResult.get("model_id")).map(Object::toString).orElse(null);
assertNotNull(modelId);
return modelId;
}
protected void loadModel(final String modelId) throws Exception {
Response uploadResponse = makeRequest(
client(),
"POST",
String.format(LOCALE, "/_plugins/_ml/models/%s/_deploy", modelId),
null,
toHttpEntity(""),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> uploadResJson = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(uploadResponse.getEntity()),
false
);
String taskId = uploadResJson.get("task_id").toString();
assertNotNull(taskId);
Map<String, Object> taskQueryResult = getTaskQueryResponse(taskId);
boolean isComplete = checkComplete(taskQueryResult);
for (int i = 0; !isComplete && i < MAX_TASK_RETRIES; i++) {
taskQueryResult = getTaskQueryResponse(taskId);
isComplete = checkComplete(taskQueryResult);
Thread.sleep(DEFAULT_TASK_RESULT_QUERY_INTERVAL_IN_MILLISECOND);
}
assertTrue(String.format(Locale.ROOT, "failed to load the model, last task finished with status %s", taskQueryResult.get("state")), isComplete);
}
/**
* Upload default model and load into the cluster
*
* @return modelID
*/
@SneakyThrows
protected String prepareModel() {
String requestBody = Files.readString(Path.of(classLoader.getResource("processor/UploadModelRequestBody.json").toURI()));
String modelId = registerModelGroupAndUploadModel(requestBody);
loadModel(modelId);
return modelId;
}
/**
* Upload default model and load into the cluster
*
* @return modelID
*/
@SneakyThrows
protected String prepareSparseEncodingModel() {
String requestBody = Files.readString(
Path.of(classLoader.getResource("processor/UploadSparseEncodingModelRequestBody.json").toURI())
);
String modelId = registerModelGroupAndUploadModel(requestBody);
loadModel(modelId);
return modelId;
}
/**
* Execute model inference on the provided query text
*
* @param modelId id of model to run inference
* @param queryText text to be transformed to a model
* @return text embedding
*/
@SuppressWarnings("unchecked")
@SneakyThrows
protected float[] runInference(final String modelId, final String queryText) {
Response inferenceResponse = makeRequest(
client(),
"POST",
String.format(LOCALE, "/_plugins/_ml/_predict/text_embedding/%s", modelId),
null,
toHttpEntity(String.format(LOCALE, "{\"text_docs\": [\"%s\"],\"target_response\": [\"sentence_embedding\"]}", queryText)),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> inferenceResJson = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(inferenceResponse.getEntity()),
false
);
Object inference_results = inferenceResJson.get("inference_results");
assertTrue(inference_results instanceof List);
List<Object> inferenceResultsAsMap = (List<Object>) inference_results;
assertEquals(1, inferenceResultsAsMap.size());
Map<String, Object> result = (Map<String, Object>) inferenceResultsAsMap.get(0);
List<Object> output = (List<Object>) result.get("output");
assertEquals(1, output.size());
Map<String, Object> map = (Map<String, Object>) output.get(0);
List<Number> data = ((List<Double>) map.get("data")).stream().map(Double::floatValue).collect(Collectors.toList());
return vectorAsListToArray(data);
}
protected void createIndexWithConfiguration(final String indexName, String indexConfiguration, final String pipelineName)
throws Exception {
if (StringUtils.isNotBlank(pipelineName)) {
indexConfiguration = String.format(LOCALE, indexConfiguration, pipelineName);
}
Response response = makeRequest(
client(),
"PUT",
indexName,
null,
toHttpEntity(indexConfiguration),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> node = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(response.getEntity()),
false
);
assertEquals("true", node.get("acknowledged").toString());
assertEquals(indexName, node.get("index").toString());
}
protected void createPipelineProcessor(final String modelId, final String pipelineName, final ProcessorType processorType)
throws Exception {
createPipelineProcessor(modelId, pipelineName, processorType, null);
}
protected void createPipelineProcessor(
final String modelId,
final String pipelineName,
final ProcessorType processorType,
final Integer batchSize
) throws Exception {
String requestBody = Files.readString(Path.of(classLoader.getResource(PIPELINE_CONFIGS_BY_TYPE.get(processorType)).toURI()));
createPipelineProcessor(requestBody, pipelineName, modelId, batchSize);
}
protected void createPipelineProcessor(
final String requestBody,
final String pipelineName,
final String modelId,
final Integer batchSize
) throws Exception {
Response pipelineCreateResponse = makeRequest(
client(),
"PUT",
"/_ingest/pipeline/" + pipelineName,
null,
toHttpEntity(String.format(LOCALE, requestBody, modelId, batchSize == null ? 1 : batchSize)),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> node = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(pipelineCreateResponse.getEntity()),
false
);
assertEquals("true", node.get("acknowledged").toString());
}
protected void createNeuralSparseTwoPhaseSearchProcessor(final String pipelineName) throws Exception {
createNeuralSparseTwoPhaseSearchProcessor(pipelineName, 0.4f, 5.0f, 10000);
}
protected void createNeuralSparseTwoPhaseSearchProcessor(
final String pipelineName,
float pruneRatio,
float expansionRate,
int maxWindowSize
) throws Exception {
String jsonTemplate = Files.readString(
Path.of(Objects.requireNonNull(classLoader.getResource("processor/NeuralSparseTwoPhaseProcessorConfiguration.json")).toURI())
);
String customizedJson = String.format(Locale.ROOT, jsonTemplate, pruneRatio, expansionRate, maxWindowSize);
Response pipelineCreateResponse = makeRequest(
client(),
"PUT",
"/_search/pipeline/" + pipelineName,
null,
toHttpEntity(customizedJson),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> node = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(pipelineCreateResponse.getEntity()),
false
);
assertEquals("true", node.get("acknowledged").toString());
}
protected void createSearchRequestProcessor(final String modelId, final String pipelineName) throws Exception {
Response pipelineCreateResponse = makeRequest(
client(),
"PUT",
"/_search/pipeline/" + pipelineName,
null,
toHttpEntity(
String.format(
LOCALE,
Files.readString(Path.of(classLoader.getResource("processor/SearchRequestPipelineConfiguration.json").toURI())),
modelId
)
),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> node = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(pipelineCreateResponse.getEntity()),
false
);
assertEquals("true", node.get("acknowledged").toString());
}
protected void createSearchPipelineViaConfig(String modelId, String pipelineName, String configPath) throws Exception {
Response pipelineCreateResponse = makeRequest(
client(),
"PUT",
"/_search/pipeline/" + pipelineName,
null,
toHttpEntity(String.format(LOCALE, Files.readString(Path.of(classLoader.getResource(configPath).toURI())), modelId)),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
Map<String, Object> node = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(pipelineCreateResponse.getEntity()),
false
);
assertEquals("true", node.get("acknowledged").toString());
}
protected void createIndexAlias(final String index, final String alias, final QueryBuilder filterBuilder) throws Exception {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
builder.startArray("actions");
builder.startObject();
builder.startObject("add");
builder.field("index", index);
builder.field("alias", alias);
// filter object
if (Objects.nonNull(filterBuilder)) {
builder.field("filter");
filterBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
}
builder.endObject();
builder.endObject();
builder.endArray();
builder.endObject();
Request request = new Request("POST", "/_aliases");
request.setJsonEntity(builder.toString());
Response response = client().performRequest(request);
assertEquals(request.getEndpoint() + ": failed", RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
}
@SneakyThrows
protected void deleteIndexAlias(final String index, final String alias) {
makeRequest(
client(),
"DELETE",
String.format(Locale.ROOT, "%s/_alias/%s", index, alias),
null,
null,
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
}
/**
* Get the number of documents in a particular index
*
* @param indexName name of index
* @return number of documents indexed to that index
*/
@SneakyThrows
protected int getDocCount(final String indexName) {
Request request = new Request("GET", "/" + indexName + "/_count");
Response response = client().performRequest(request);
assertEquals(request.getEndpoint() + ": failed", RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
String responseBody = EntityUtils.toString(response.getEntity());
Map<String, Object> responseMap = createParser(XContentType.JSON.xContent(), responseBody).map();
return (Integer) responseMap.get("count");
}
/**
* Get one doc by its id
* @param indexName index name
* @param id doc id
* @return map of the doc data
*/
@SneakyThrows
protected Map<String, Object> getDocById(final String indexName, final String id) {
Request request = new Request("GET", "/" + indexName + "/_doc/" + id);
Response response = client().performRequest(request);
assertEquals(request.getEndpoint() + ": failed", RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
String responseBody = EntityUtils.toString(response.getEntity());
return createParser(XContentType.JSON.xContent(), responseBody).map();
}
/**
* Execute a search request initialized from a neural query builder
*
* @param index Index to search against
* @param queryBuilder queryBuilder to produce source of query
* @param resultSize number of results to return in the search
* @return Search results represented as a map
*/
protected Map<String, Object> search(final String index, final QueryBuilder queryBuilder, final int resultSize) {
return search(index, queryBuilder, null, resultSize);
}
/**
* Execute a search request initialized from a neural query builder that can add a rescore query to the request
*
* @param index Index to search against
* @param queryBuilder queryBuilder to produce source of query
* @param rescorer used for rescorer query builder
* @param resultSize number of results to return in the search
* @return Search results represented as a map
*/
@SneakyThrows
protected Map<String, Object> search(
final String index,
final QueryBuilder queryBuilder,
final QueryBuilder rescorer,
final int resultSize
) {
return search(index, queryBuilder, rescorer, resultSize, Map.of());
}
/**
* Execute a search request initialized from a neural query builder that can add a rescore query to the request
*
* @param index Index to search against
* @param queryBuilder queryBuilder to produce source of query
* @param rescorer used for rescorer query builder
* @param resultSize number of results to return in the search
* @param requestParams additional request params for search
* @return Search results represented as a map
*/
@SneakyThrows
protected Map<String, Object> search(
final String index,
final QueryBuilder queryBuilder,
final QueryBuilder rescorer,
final int resultSize,
final Map<String, String> requestParams
) {
return search(index, queryBuilder, rescorer, resultSize, requestParams, null);
}
@SneakyThrows
protected Map<String, Object> search(
String index,
QueryBuilder queryBuilder,
QueryBuilder rescorer,
int resultSize,
Map<String, String> requestParams,
List<Object> aggs
) {
return search(index, queryBuilder, rescorer, resultSize, requestParams, aggs, null, null, false, null, 0);
}
@SneakyThrows
protected Map<String, Object> search(
String index,
QueryBuilder queryBuilder,
QueryBuilder rescorer,
int resultSize,
Map<String, String> requestParams,
List<Object> aggs,
QueryBuilder postFilterBuilder,
List<SortBuilder<?>> sortBuilders,
boolean trackScores,
List<Object> searchAfter,
int from
) {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
builder.field("from", from);
if (queryBuilder != null) {
builder.field("query");
queryBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
}
if (rescorer != null) {
builder.startObject("rescore").startObject("query").field("query_weight", 0.0f).field("rescore_query");
rescorer.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject().endObject();
}
if (Objects.nonNull(aggs)) {
builder.startObject("aggs");
for (Object agg : aggs) {
builder.value(agg);
}
builder.endObject();
}
if (Objects.nonNull(postFilterBuilder)) {
builder.field("post_filter");
postFilterBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
}
if (Objects.nonNull(sortBuilders) && !sortBuilders.isEmpty()) {
builder.startArray("sort");
for (SortBuilder sortBuilder : sortBuilders) {
sortBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
}
builder.endArray();
}
if (trackScores) {
builder.field("track_scores", trackScores);
}
if (searchAfter != null && !searchAfter.isEmpty()) {
builder.startArray("search_after");
for (Object searchAfterEntry : searchAfter) {
builder.value(searchAfterEntry);
}
builder.endArray();
}
builder.endObject();
Request request = new Request("GET", "/" + index + "/_search?timeout=1000s");
request.addParameter("size", Integer.toString(resultSize));
if (requestParams != null && !requestParams.isEmpty()) {
requestParams.forEach(request::addParameter);
}
request.setJsonEntity(builder.toString());
Response response = client().performRequest(request);
assertEquals(request.getEndpoint() + ": failed", RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
String responseBody = EntityUtils.toString(response.getEntity());
return XContentHelper.convertToMap(XContentType.JSON.xContent(), responseBody, false);
}
/**
* Add a set of knn vectors
*
* @param index Name of the index
* @param docId ID of document to be added
* @param vectorFieldNames List of vectir fields to be added
* @param vectors List of vectors corresponding to those fields
*/
protected void addKnnDoc(final String index, final String docId, final List<String> vectorFieldNames, final List<Object[]> vectors) {
addKnnDoc(index, docId, vectorFieldNames, vectors, Collections.emptyList(), Collections.emptyList());
}
@SneakyThrows
protected void addKnnDoc(
final String index,
final String docId,
final List<String> vectorFieldNames,
final List<Object[]> vectors,
final List<String> textFieldNames,
final List<String> texts
) {
addKnnDoc(index, docId, vectorFieldNames, vectors, textFieldNames, texts, Collections.emptyList(), Collections.emptyList());
}
@SneakyThrows
protected void addKnnDoc(
String index,
String docId,
List<String> vectorFieldNames,
List<Object[]> vectors,
List<String> textFieldNames,
List<String> texts,
List<String> nestedFieldNames,
List<Map<String, String>> nestedFields
) {
addKnnDoc(
index,
docId,
vectorFieldNames,
vectors,
textFieldNames,
texts,
nestedFieldNames,
nestedFields,
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList()
);
}
/**
* Add a set of knn vectors and text to an index
*
* @param index Name of the index
* @param docId ID of document to be added
* @param vectorFieldNames List of vectir fields to be added
* @param vectors List of vectors corresponding to those fields
* @param textFieldNames List of text fields to be added
* @param texts List of text corresponding to those fields
* @param nestedFieldNames List of nested fields to be added
* @param nestedFields List of fields and values corresponding to those fields
*/
@SneakyThrows
protected void addKnnDoc(
final String index,
final String docId,
final List<String> vectorFieldNames,
final List<Object[]> vectors,
final List<String> textFieldNames,
final List<String> texts,
final List<String> nestedFieldNames,
final List<Map<String, String>> nestedFields,
final List<String> integerFieldNames,
final List<Integer> integerFieldValues,
final List<String> keywordFieldNames,
final List<String> keywordFieldValues,
final List<String> dateFieldNames,
final List<String> dateFieldValues
) {
Request request = new Request("POST", "/" + index + "/_doc/" + docId + "?refresh=true");
XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
for (int i = 0; i < vectorFieldNames.size(); i++) {
builder.field(vectorFieldNames.get(i), vectors.get(i));
}
for (int i = 0; i < textFieldNames.size(); i++) {
builder.field(textFieldNames.get(i), texts.get(i));
}
for (int i = 0; i < nestedFieldNames.size(); i++) {
builder.field(nestedFieldNames.get(i));
builder.startObject();
Map<String, String> nestedValues = nestedFields.get(i);
for (Map.Entry<String, String> entry : nestedValues.entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
}
for (int i = 0; i < integerFieldNames.size(); i++) {
builder.field(integerFieldNames.get(i), integerFieldValues.get(i));
}
for (int i = 0; i < keywordFieldNames.size(); i++) {
builder.field(keywordFieldNames.get(i), keywordFieldValues.get(i));
}
for (int i = 0; i < dateFieldNames.size(); i++) {
builder.field(dateFieldNames.get(i), dateFieldValues.get(i));
}
builder.endObject();
request.setJsonEntity(builder.toString());
Response response = client().performRequest(request);
assertTrue(
request.getEndpoint() + ": failed",
SUCCESS_STATUSES.contains(RestStatus.fromCode(response.getStatusLine().getStatusCode()))
);
}
@SneakyThrows
protected void addSparseEncodingDoc(
final String index,
final String docId,
final List<String> fieldNames,
final List<Map<String, Float>> docs
) {
addSparseEncodingDoc(index, docId, fieldNames, docs, Collections.emptyList(), Collections.emptyList());
}
@SneakyThrows
protected void addSparseEncodingDoc(
final String index,
final String docId,
final List<String> fieldNames,
final List<Map<String, Float>> docs,
final List<String> textFieldNames,
final List<String> texts
) {
Request request = new Request("POST", "/" + index + "/_doc/" + docId + "?refresh=true");
XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
for (int i = 0; i < fieldNames.size(); i++) {
builder.field(fieldNames.get(i), docs.get(i));
}
for (int i = 0; i < textFieldNames.size(); i++) {
builder.field(textFieldNames.get(i), texts.get(i));
}
builder.endObject();
request.setJsonEntity(builder.toString());
Response response = client().performRequest(request);
assertEquals(request.getEndpoint() + ": failed", RestStatus.CREATED, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
}
protected void bulkAddDocuments(final String index, final String textField, final String pipeline, final List<Map<String, String>> docs)
throws IOException {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < docs.size(); ++i) {
String doc = String.format(
Locale.ROOT,
"{ \"index\": { \"_index\": \"%s\", \"_id\": \"%s\" } },\n" + "{ \"%s\": \"%s\"}",
index,
docs.get(i).get("id"),
textField,
docs.get(i).get("text")
);
builder.append(doc);
builder.append("\n");
}
Request request = new Request("POST", String.format(Locale.ROOT, "/_bulk?refresh=true&pipeline=%s", pipeline));
request.setJsonEntity(builder.toString());
Response response = client().performRequest(request);
assertEquals(request.getEndpoint() + ": failed", RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
}
@SneakyThrows
protected void bulkIngest(final String ingestBulkPayload, final String pipeline) {
Map<String, String> params = new HashMap<>();
params.put("refresh", "true");
if (Objects.nonNull(pipeline)) {
params.put("pipeline", pipeline);
}
Response response = makeRequest(
client(),
"POST",
"_bulk",
params,
toHttpEntity(ingestBulkPayload),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana"))
);
Map<String, Object> map = XContentHelper.convertToMap(
XContentType.JSON.xContent(),
EntityUtils.toString(response.getEntity()),
false
);
int failedDocCount = 0;
for (Object item : ((List) map.get("items"))) {
Map<String, Map<String, Object>> itemMap = (Map<String, Map<String, Object>>) item;
if (itemMap.get("index").get("error") != null) {
failedDocCount++;
}
}
assertEquals(0, failedDocCount);
assertEquals("_bulk failed", RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode()));
}
/**
* Parse the first returned hit from a search response as a map
*
* @param searchResponseAsMap Complete search response as a map
* @return Map of first internal hit from the search
*/
@SuppressWarnings("unchecked")
protected Map<String, Object> getFirstInnerHit(final Map<String, Object> searchResponseAsMap) {
Map<String, Object> hits1map = (Map<String, Object>) searchResponseAsMap.get("hits");
List<Object> hits2List = (List<Object>) hits1map.get("hits");
assertTrue(hits2List.size() > 0);
return (Map<String, Object>) hits2List.get(0);
}
/**
* Parse the total number of hits from the search
*
* @param searchResponseAsMap Complete search response as a map
* @return number of hits from the search
*/
@SuppressWarnings("unchecked")
protected int getHitCount(final Map<String, Object> searchResponseAsMap) {
Map<String, Object> hits1map = (Map<String, Object>) searchResponseAsMap.get("hits");
List<Object> hits1List = (List<Object>) hits1map.get("hits");
return hits1List.size();
}
/**
* Parse the total number of hits and retrive score from the search
*
* @param searchResponseAsMap Complete search response as a map
* @return number of scores list from the search
*/
@SuppressWarnings("unchecked")
protected List<Double> getNormalizationScoreList(final Map<String, Object> searchResponseAsMap) {
Map<String, Object> hits1map = (Map<String, Object>) searchResponseAsMap.get("hits");
List<Object> hitsList = (List<Object>) hits1map.get("hits");
List<Double> scores = new ArrayList<>();
for (Object hit : hitsList) {
Map<String, Object> searchHit = (Map<String, Object>) hit;
scores.add((Double) searchHit.get("_score"));
}
return scores;
}
protected List<Map<String, Object>> getListOfValues(Map<String, Object> searchResponseAsMap, String key) {
return (List<Map<String, Object>>) searchResponseAsMap.get(key);
}
/**
* Create a k-NN index from a list of KNNFieldConfigs
*
* @param indexName of index to be created
* @param knnFieldConfigs list of configs specifying field
*/
@SneakyThrows
protected void prepareKnnIndex(final String indexName, final List<KNNFieldConfig> knnFieldConfigs) {
prepareKnnIndex(indexName, knnFieldConfigs, 3);
}
@SneakyThrows
protected void prepareKnnIndex(final String indexName, final List<KNNFieldConfig> knnFieldConfigs, final int numOfShards) {
createIndexWithConfiguration(indexName, buildIndexConfiguration(knnFieldConfigs, numOfShards), "");
}
@SneakyThrows
protected void prepareSparseEncodingIndex(final String indexName, final List<String> sparseEncodingFieldNames) {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("mappings").startObject("properties");
for (String fieldName : sparseEncodingFieldNames) {
xContentBuilder.startObject(fieldName).field("type", "rank_features").endObject();
}
xContentBuilder.endObject().endObject().endObject();
String indexMappings = xContentBuilder.toString();
createIndexWithConfiguration(indexName, indexMappings, "");
}
/**
* Computes the expected distance between an indexVector and query text without using the neural query type.
*
* @param modelId ID of model to run inference
* @param indexVector vector to compute score against
* @param spaceType Space to measure distance
* @param queryText Text to produce query vector from
* @return Expected OpenSearch score for this indexVector
*/
protected float computeExpectedScore(
final String modelId,
final float[] indexVector,
final SpaceType spaceType,
final String queryText
) {
float[] queryVector = runInference(modelId, queryText);
return spaceType.getKnnVectorSimilarityFunction().compare(queryVector, indexVector);
}
protected Map<String, Object> getTaskQueryResponse(final String taskId) throws Exception {
Response taskQueryResponse = makeRequest(
client(),
"GET",
String.format(LOCALE, "_plugins/_ml/tasks/%s", taskId),
null,
toHttpEntity(""),
ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT))
);
return XContentHelper.convertToMap(XContentType.JSON.xContent(), EntityUtils.toString(taskQueryResponse.getEntity()), false);
}
protected boolean checkComplete(final Map<String, Object> node) {
Predicate<Map<String, Object>> predicate = x -> node.get("error") != null || "COMPLETED".equals(String.valueOf(node.get("state")));
return predicate.test(node);
}
@SneakyThrows
protected String buildIndexConfiguration(final List<KNNFieldConfig> knnFieldConfigs, final int numberOfShards) {
return buildIndexConfiguration(knnFieldConfigs, Collections.emptyList(), numberOfShards);
}
@SneakyThrows
protected String buildIndexConfiguration(
final List<KNNFieldConfig> knnFieldConfigs,
final List<String> nestedFields,
final int numberOfShards
) {
return buildIndexConfiguration(
knnFieldConfigs,
nestedFields,
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
numberOfShards
);
}
@SneakyThrows
protected String buildIndexConfiguration(