-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathSearchResourceIT.java
More file actions
2186 lines (1802 loc) · 81.5 KB
/
SearchResourceIT.java
File metadata and controls
2186 lines (1802 loc) · 81.5 KB
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
package org.openmetadata.it.tests;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.openmetadata.it.util.SdkClients;
import org.openmetadata.it.util.TestNamespace;
import org.openmetadata.it.util.TestNamespaceExtension;
import org.openmetadata.schema.api.data.CreateDatabaseSchema;
import org.openmetadata.schema.api.data.CreateTable;
import org.openmetadata.schema.api.data.CreateTopic;
import org.openmetadata.schema.entity.data.Database;
import org.openmetadata.schema.entity.data.DatabaseSchema;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.schema.entity.data.Topic;
import org.openmetadata.schema.entity.services.DatabaseService;
import org.openmetadata.schema.entity.services.MessagingService;
import org.openmetadata.schema.type.Column;
import org.openmetadata.schema.type.ColumnDataType;
import org.openmetadata.schema.type.Field;
import org.openmetadata.schema.type.FieldDataType;
import org.openmetadata.schema.type.MessageSchema;
import org.openmetadata.schema.type.SchemaType;
import org.openmetadata.sdk.client.OpenMetadataClient;
/**
* Integration tests for Search functionality using fluent API.
*
* <p>Tests search queries, entity type counts, aggregations, and search behavior.
*
* <p>Migrated from: org.openmetadata.service.resources.search.SearchResourceTest
*/
@Execution(ExecutionMode.CONCURRENT)
@ExtendWith(TestNamespaceExtension.class)
public class SearchResourceIT {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
// Shared entities for efficient table creation across multiple calls
private DatabaseService sharedDbService;
private Database sharedDatabase;
private DatabaseSchema sharedSchema;
// ===================================================================
// BASIC SEARCH TESTS
// ===================================================================
@Test
void testBasicSearch(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
// Use wildcard query which is safer than field expansion
String response = client.search().query("*").index("table_search_index").size(5).execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
@Test
void testSearchWithPagination(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
for (int i = 0; i < 5; i++) {
createTestTable(ns, "paginated_" + i);
}
// Fluent API with pagination
String response =
client.search().query("*").index("table_search_index").from(0).size(2).execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
@Test
void testSearchWithPageHelper(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
// Using page() helper method
String response = client.search().query("*").index("table_search_index").page(0, 10).execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
@Test
void testSearchWithSorting(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "sort_test");
// Fluent API with sorting
String response =
client
.search()
.query("*")
.index("table_search_index")
.size(10)
.sortBy("name.keyword", "asc")
.execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
@Test
void testSearchSortAscDesc(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
// Test sortAsc helper
String ascResponse =
client
.search()
.query("*")
.index("table_search_index")
.size(10)
.sortAsc("name.keyword")
.execute();
assertNotNull(ascResponse);
// Test sortDesc helper
String descResponse =
client
.search()
.query("*")
.index("table_search_index")
.size(10)
.sortDesc("name.keyword")
.execute();
assertNotNull(descResponse);
}
// ===================================================================
// ENTITY TYPE COUNTS TESTS
// ===================================================================
@Test
void testEntityTypeCountsWithQueryAll(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "counts_all");
// Fluent API for entity type counts
String response = client.search().entityTypeCounts().query("*").execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(
root.has("aggregations") || root.has("buckets") || root.size() > 0,
"Response should have count data");
}
@Test
void testEntityTypeCountsWithIndex(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "index_counts");
String response =
client.search().entityTypeCounts().query("*").index("table_search_index").execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertNotNull(root);
}
@Test
void testEntityTypeCountsWithQueryFilter(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
String queryFilter = "{\"query\":{\"bool\":{\"must\":[{\"term\":{\"deleted\":false}}]}}}";
String response =
client
.search()
.entityTypeCounts()
.query("*")
.index("dataAsset")
.queryFilter(queryFilter)
.execute();
assertNotNull(response);
}
// ===================================================================
// SEARCH WITH AGGREGATIONS TESTS
// ===================================================================
@Test
void testSearchWithIncludeAggregations(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "agg_test");
// Fluent API with includeAggregations()
String response =
client
.search()
.query("*")
.index("table_search_index")
.size(10)
.includeAggregations()
.execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
@Test
void testSearchWithoutAggregations(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
String response =
client
.search()
.query("*")
.index("table_search_index")
.size(10)
.includeAggregations(false)
.execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
// ===================================================================
// AGGREGATE TESTS
// ===================================================================
@Test
void testAggregateQuery(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "aggregate_test");
String response =
client.search().aggregate("*").index("table_search_index").field("owner.name").execute();
assertNotNull(response);
}
@Test
void testAggregateQueryWithQueryText(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "aggregate_querytext_test");
String response =
client
.search()
.aggregate("*")
.index("table_search_index")
.field("database.name")
.queryText("aggregate_querytext_test")
.execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("aggregations"), "Response should have aggregations");
}
@Test
void testAggregateQueryWithEmptyQueryText(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "aggregate_empty_qt");
String responseWithout =
client.search().aggregate("*").index("table_search_index").field("database.name").execute();
String responseWith =
client
.search()
.aggregate("*")
.index("table_search_index")
.field("database.name")
.queryText("")
.execute();
assertNotNull(responseWithout);
assertNotNull(responseWith);
}
// ===================================================================
// SPECIAL CHARACTER AND EDGE CASE TESTS
// ===================================================================
@Test
void testVeryLongQueryWithSpecialCharacters(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
// Queries with special characters should not throw exceptions
String response =
client.search().query("test-query_with.special").index("table_search_index").execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
@Test
void testSearchWithEmptyQuery(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
String response = client.search().query("").index("table_search_index").execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits") || root.has("error"), "Response should have hits or error");
}
@Test
void testSearchAcrossMultipleIndexes(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "multi_index");
createTestTopic(ns, "multi_index");
// Search using dataAsset index (covers multiple entity types)
String response = client.search().query("multi_index").index("dataAsset").execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
// ===================================================================
// CLAUSE EXPLOSION PREVENTION TESTS
// ===================================================================
@Test
void testLongTableNameWithManyColumnsDoesNotCauseClauseExplosion(TestNamespace ns)
throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
String longTableName = ns.prefix("int_snowplow_experiment_evaluation_detailed");
List<Column> manyColumns = createManyTableColumns(50);
Table table = createTestTableWithColumns(ns, longTableName, manyColumns);
assertNotNull(table);
String problematicQuery = "int_snowplow_experiment";
assertDoesNotThrow(
() -> {
String response =
client.search().query(problematicQuery).index("table_search_index").execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertFalse(
root.has("error") && root.get("error").asText().contains("too_many"),
"Should not have too_many_nested_clauses error");
});
}
@Test
void testTopicWithManySchemaFieldsDoesNotCauseClauseExplosion(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
String longTopicName = ns.prefix("snowplow_experiment_evaluation_events");
List<Field> manyFields = createManyTopicSchemaFields(50);
Topic topic = createTestTopicWithFields(ns, longTopicName, manyFields);
assertNotNull(topic);
String problematicQuery = "snowplow_experiment";
assertDoesNotThrow(
() -> {
String response =
client.search().query(problematicQuery).index("topic_search_index").execute();
assertNotNull(response);
});
}
/**
* Matrix test that reproduces the {@code dataAsset}-alias regression and pins the behavior of
* any fix across the query shapes users actually type.
*
* <p>The bug: composite config merges fuzzy fields from every asset type. The {@code name.ngram}
* analyzer splits on non-alphanumeric characters, so a long multi-segment identifier yields many
* sub-tokens that each expand into many ngrams, and each ngram becomes a fuzzy term (fuzziness=1,
* maxExpansions=10). Clause count crosses Lucene's 1024 limit; in ES 7/OS only the table shards
* overflow (silent drop); in ES 9 the whole query is rejected.
*
* <p>Every scenario must satisfy {@code _shards.failed == 0}. The {@code shouldFind} column pins
* whether the seeded table is expected in {@code hits.hits}. Failures from every row are
* collected and reported together rather than short-circuiting on the first one, so a single
* run surfaces the whole regression surface.
*/
@Test
void testDataAssetAliasSearchMatrix(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
// Use a production-realistic name length (~40 chars, 5-6 alnum sub-tokens) by bypassing
// ns.prefix() — that helper appends RUN_ID + classId + methodId which balloons the name
// to ~127 chars, and the sheer ngram cardinality of that long string exceeds
// OpenSearch's 1024 max_clause_count even with fuzziness=0 + max_expansions=1.
// Production names like kochi__expected_vessels__portcall_v1 are ~36 chars, which is
// the length we want to pin behavior against.
// Prefix the unique tag with a distinctive "xqz" marker. uniqueShortId() returns hex,
// and pure-hex prefixes share ngrams with every UUID/hash in a busy CI index, which can
// push our seeded table out of the top-N hits. "xqz" is rare in any real document and
// makes the first sub-token uniquely ours.
String uniq = "xqz" + ns.uniqueShortId().substring(0, 5);
String longName = uniq + "_lhr__incoming_flights__arrivals_schedule_v1";
Table table =
createTestTableWithColumns(
ns,
longName,
List.of(
new Column().withName("id").withDataType(ColumnDataType.BIGINT),
new Column()
.withName("name")
.withDataType(ColumnDataType.VARCHAR)
.withDataLength(255)));
String indexedName = table.getName();
// Wait for the table to appear in the table-only index using a real search call.
// Query by the first alphanumeric segment of the indexed name — it's short (3-5 chars,
// one alnum sub-token), so it won't itself trigger the clause-explosion path we're
// about to stress in the matrix below. We still verify the specific seeded table is the
// hit, so accidental matches on other docs with "lhr" in their name don't fool us.
String waitQuery = indexedName.split("_+")[0];
// 90s timeout: search indexing is async via change events and can lag noticeably under
// CI load, especially the first time the index is warmed in a fresh test container.
Awaitility.await()
.atMost(90, TimeUnit.SECONDS)
.pollInterval(500, TimeUnit.MILLISECONDS)
.until(
() -> {
String r =
client.search().query(waitQuery).index("table_search_index").size(25).execute();
JsonNode root = OBJECT_MAPPER.readTree(r);
for (JsonNode hit : root.path("hits").path("hits")) {
if (indexedName.equals(hit.path("_source").path("name").asText())) {
return true;
}
}
return false;
});
// Derive substrings from the seeded name. shouldFind reflects realistic user expectations
// given that `name` has fuzziness via FUZZY_FIELDS and `name.ngram` handles substrings.
String firstSegment = indexedName.split("_+")[0]; // the 8-char unique tag
int midLen = Math.min(15, indexedName.length());
String shortPrefix = indexedName.substring(0, Math.min(5, indexedName.length()));
String midPrefix = indexedName.substring(0, midLen);
String fullWithDots = indexedName.replace("_", ".");
String typoInSegment = indexedName.replaceFirst("incoming", "incaming"); // 1-char typo
String dropOneSegment = indexedName.replaceFirst("__arrivals_schedule_v1", "_v1");
String trailingSegment = "schedule_v1";
String middleSegment = "flights";
String firstTwoSegments = "lhr__incoming"; // exactly 2 alnum sub-tokens (boundary case)
String firstThreeSegments = "lhr__incoming_flights"; // exactly 3 — first to trip fuzz=0
String mixedSeparators = indexedName.replace("__", "-").replace("_", ".");
String withTrailingWhitespace = " " + indexedName + " ";
String withInternalWhitespace = indexedName.replace("__", " ");
String camelCaseChunk = "LhrIncomingFlightsArrivalsScheduleV1"; // single alnum sub-token, long
String slashSeparated = indexedName.replace("_", "/");
List<Scenario> scenarios =
List.of(
// --- the original repro and its immediate variants ---
new Scenario("exact full name (the repro)", indexedName, true),
new Scenario("short prefix (autocomplete early)", shortPrefix, true),
new Scenario("medium prefix (autocomplete mid-type)", midPrefix, true),
new Scenario("first segment alone", firstSegment, true),
new Scenario("middle segment alone", middleSegment, true),
new Scenario("trailing segment only", trailingSegment, true),
new Scenario("dotted variant (FQN-ish)", fullWithDots, true),
new Scenario("one-char typo inside a segment", typoInSegment, true),
new Scenario("dropped middle segments", dropOneSegment, true),
new Scenario("unrelated query", "totally_unrelated_zzzqqq_9999", false),
// --- boundary cases for the sub-token-count heuristic ---
// 2 sub-tokens → fuzziness=1 path still active; must not explode and must match
new Scenario("exactly 2 sub-tokens (fuzzy path active)", firstTwoSegments, true),
// 3 sub-tokens → first to flip to fuzziness=0; must not explode and must match
new Scenario("exactly 3 sub-tokens (fuzzy path off)", firstThreeSegments, true),
// --- separator variants: ngram tokenizer splits on ALL non-alnum the same way, so
// dots / dashes / slashes must all behave equivalently to underscores ---
new Scenario("mixed separators (- and .)", mixedSeparators, true),
new Scenario("slash-separated (path-like)", slashSeparated, true),
// --- whitespace handling: trim, and whitespace as a separator in the query ---
new Scenario("leading/trailing whitespace", withTrailingWhitespace, true),
new Scenario("whitespace-separated segments", withInternalWhitespace, true),
// --- single-alnum-token stress: long camelCase that is one 36-char sub-token ---
new Scenario("long camelCase single token", camelCaseChunk, false),
// --- edge-case query shape that must never throw or blow shards ---
new Scenario("only separators", "___", false));
List<String> failures = new ArrayList<>();
for (Scenario s : scenarios) {
evaluateScenario(client, s, indexedName, failures);
}
assertTrue(
failures.isEmpty(), "Matrix scenarios failed:\n - " + String.join("\n - ", failures));
}
private record Scenario(String description, String query, boolean shouldFind) {}
private void evaluateScenario(
OpenMetadataClient client, Scenario s, String seededName, List<String> failures) {
JsonNode root;
try {
String response =
client.search().query(s.query()).index("dataAsset").deleted(false).size(50).execute();
root = OBJECT_MAPPER.readTree(response);
} catch (Exception e) {
// A thrown exception means the whole search was rejected (e.g. ES 9 "too many clauses"
// blows the request). Treat that as a shard-level failure for reporting purposes.
failures.add(
s.description()
+ " [query=\""
+ s.query()
+ "\"]: request threw "
+ e.getClass().getSimpleName()
+ " — "
+ e.getMessage());
return;
}
int shardsFailed = root.path("_shards").path("failed").asInt(-1);
if (shardsFailed != 0) {
failures.add(
s.description()
+ " [query=\""
+ s.query()
+ "\"]: _shards.failed="
+ shardsFailed
+ ", failures="
+ root.path("_shards").path("failures").toString());
return;
}
boolean found = false;
for (JsonNode hit : root.path("hits").path("hits")) {
if (seededName.equals(hit.path("_source").path("name").asText())) {
found = true;
break;
}
}
if (found != s.shouldFind()) {
failures.add(
s.description()
+ " [query=\""
+ s.query()
+ "\"]: expected shouldFind="
+ s.shouldFind()
+ " but got found="
+ found);
}
}
/**
* Guards against over-correction of the clause-explosion fix. The fix disables fuzziness
* once the query analyzes to more than 2 sub-tokens; it must keep fuzziness on single-word
* queries so normal typo tolerance ({@code custmer} → {@code customer}) keeps working.
*/
@Test
void testSingleWordTypoStillMatchesViaFuzzy(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
Table table = createTestTable(ns, "customer_analytics");
String indexedName = table.getName();
String firstSeg = indexedName.split("_+")[0];
Awaitility.await()
.atMost(90, TimeUnit.SECONDS)
.pollInterval(500, TimeUnit.MILLISECONDS)
.until(
() -> {
String r =
client.search().query(firstSeg).index("table_search_index").size(25).execute();
JsonNode root = OBJECT_MAPPER.readTree(r);
for (JsonNode hit : root.path("hits").path("hits")) {
if (indexedName.equals(hit.path("_source").path("name").asText())) {
return true;
}
}
return false;
});
// "custmer" is a 1-char typo of "customer", 1 alnum sub-token → fuzziness path is active.
String typoQuery = "custmer";
String response =
client.search().query(typoQuery).index("dataAsset").deleted(false).size(25).execute();
JsonNode root = OBJECT_MAPPER.readTree(response);
assertEquals(
0,
root.path("_shards").path("failed").asInt(-1),
"single-word fuzzy query must not cause shard failures: "
+ root.path("_shards").path("failures").toString());
boolean found = false;
for (JsonNode hit : root.path("hits").path("hits")) {
if (indexedName.equals(hit.path("_source").path("name").asText())) {
found = true;
break;
}
}
assertTrue(
found,
"Single-word typo query \""
+ typoQuery
+ "\" must still match seeded table \""
+ indexedName
+ "\" via fuzzy path; regression would indicate the clause-explosion fix "
+ "over-corrected and killed normal typo tolerance.");
}
/**
* Pins the {@code name.keyword} exact-match boost for tables. This field was missing from
* the {@code table} asset config (unlike most other asset types), which meant typing a
* table's full name produced no exact-match boost. Regression guard: the seeded table must
* be the top hit (or strictly above any accidental substring matches) when the full name is
* queried.
*/
@Test
void testExactFullNameRanksSeededTableFirst(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
// Seed two tables so ranking is observable: the exact-match query must prefer `target`
// over the near-duplicate `decoy` that shares the same first segment. Use short unique
// tags (bypassing ns.prefix()) so the seeded names stay at production-realistic lengths
// and the exact-name query stays well under OpenSearch's default 1024-clause cap.
String uniq = "xqz" + ns.uniqueShortId().substring(0, 5);
String targetNameRaw = uniq + "_exact_rank_target_v1";
String decoyNameRaw = uniq + "_exact_rank_target_v1_extended_suffix";
List<Column> cols =
List.of(
new Column().withName("id").withDataType(ColumnDataType.BIGINT),
new Column().withName("name").withDataType(ColumnDataType.VARCHAR).withDataLength(255));
Table target = createTestTableWithColumns(ns, targetNameRaw, cols);
Table decoy = createTestTableWithColumns(ns, decoyNameRaw, cols);
String targetName = target.getName();
String decoyName = decoy.getName();
Awaitility.await()
.atMost(90, TimeUnit.SECONDS)
.pollInterval(500, TimeUnit.MILLISECONDS)
.until(
() -> {
String r =
client
.search()
.query(targetName.split("_+")[0])
.index("table_search_index")
.size(50)
.execute();
JsonNode root = OBJECT_MAPPER.readTree(r);
boolean sawTarget = false;
boolean sawDecoy = false;
for (JsonNode hit : root.path("hits").path("hits")) {
String n = hit.path("_source").path("name").asText();
if (targetName.equals(n)) sawTarget = true;
if (decoyName.equals(n)) sawDecoy = true;
}
return sawTarget && sawDecoy;
});
String response =
client.search().query(targetName).index("dataAsset").deleted(false).size(10).execute();
JsonNode root = OBJECT_MAPPER.readTree(response);
assertEquals(
0, root.path("_shards").path("failed").asInt(-1), "exact-name query must not fail shards");
JsonNode hits = root.path("hits").path("hits");
assertTrue(hits.size() > 0, "exact-name query must return at least one hit");
String topName = hits.get(0).path("_source").path("name").asText();
assertEquals(
targetName,
topName,
"Exact full-name query must rank the exact-match table first, not the decoy. "
+ "Got top hit \""
+ topName
+ "\" instead of \""
+ targetName
+ "\". This typically regresses when name.keyword exact-match is removed "
+ "from the table asset config.");
}
// ===================================================================
// SEARCH CONSISTENCY TESTS
// ===================================================================
@Test
void testSearchQueryConsistencyBetweenDataAssetAndTable(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
// Use wildcard query to avoid clause explosion with long entity names
String tableResponse = client.search().query("*").index("table_search_index").size(5).execute();
String dataAssetResponse = client.search().query("*").index("dataAsset").size(5).execute();
assertNotNull(tableResponse);
assertNotNull(dataAssetResponse);
JsonNode tableRoot = OBJECT_MAPPER.readTree(tableResponse);
JsonNode dataAssetRoot = OBJECT_MAPPER.readTree(dataAssetResponse);
assertTrue(tableRoot.has("hits"));
assertTrue(dataAssetRoot.has("hits"));
}
@Test
void testSearchPaginationConsistency(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
for (int i = 0; i < 10; i++) {
createTestTable(ns, "page_test_" + i);
}
// Get first page
String page1 =
client.search().query("page_test").index("table_search_index").page(0, 5).execute();
// Get second page
String page2 =
client.search().query("page_test").index("table_search_index").page(1, 5).execute();
assertNotNull(page1);
assertNotNull(page2);
JsonNode page1Root = OBJECT_MAPPER.readTree(page1);
JsonNode page2Root = OBJECT_MAPPER.readTree(page2);
assertTrue(page1Root.has("hits"));
assertTrue(page2Root.has("hits"));
}
// ===================================================================
// DELETED ENTITIES SEARCH TESTS
// ===================================================================
@Test
void testSearchDeletedEntities(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
Table table = createTestTable(ns, "deleted_search");
client.tables().delete(table.getId().toString());
// Fluent API with includeDeleted()
String response =
client
.search()
.query("deleted_search")
.index("table_search_index")
.includeDeleted()
.execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
@Test
void testSearchExcludeDeletedEntities(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
String response =
client.search().query("*").index("table_search_index").deleted(false).execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
// ===================================================================
// QUERY FILTER TESTS
// ===================================================================
@Test
void testSearchWithQueryFilter(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
createTestTable(ns, "filter_test");
String queryFilter = "{\"query\":{\"bool\":{\"must\":[{\"term\":{\"deleted\":false}}]}}}";
String response =
client
.search()
.query("*")
.index("table_search_index")
.queryFilter(queryFilter)
.size(10)
.execute();
assertNotNull(response);
JsonNode root = OBJECT_MAPPER.readTree(response);
assertTrue(root.has("hits"), "Response should have hits");
}
// ===================================================================
// HELPER METHODS
// ===================================================================
private Table createTestTable(TestNamespace ns, String baseName) {
// Lazily initialize shared entities once per test
initializeSharedDbEntities(ns);
CreateTable tableRequest = new CreateTable();
tableRequest.setName(ns.prefix(baseName));
tableRequest.setDatabaseSchema(sharedSchema.getFullyQualifiedName());
tableRequest.setColumns(
List.of(
new Column().withName("id").withDataType(ColumnDataType.BIGINT),
new Column()
.withName("name")
.withDataType(ColumnDataType.VARCHAR)
.withDataLength(255)));
return SdkClients.adminClient().tables().create(tableRequest);
}
private synchronized void initializeSharedDbEntities(TestNamespace ns) {
if (sharedDbService != null) {
return;
}
String shortId = ns.shortPrefix();
org.openmetadata.schema.services.connections.database.PostgresConnection conn =
org.openmetadata.sdk.fluent.DatabaseServices.postgresConnection()
.hostPort("localhost:5432")
.username("test")
.build();
sharedDbService =
org.openmetadata.sdk.fluent.DatabaseServices.builder()
.name("search_svc_" + shortId)
.connection(conn)
.description("Test service for search")
.create();
org.openmetadata.schema.api.data.CreateDatabase dbReq =
new org.openmetadata.schema.api.data.CreateDatabase();
dbReq.setName("search_db_" + shortId);
dbReq.setService(sharedDbService.getFullyQualifiedName());
sharedDatabase = SdkClients.adminClient().databases().create(dbReq);
CreateDatabaseSchema schemaReq = new CreateDatabaseSchema();
schemaReq.setName("search_schema_" + shortId);
schemaReq.setDatabase(sharedDatabase.getFullyQualifiedName());
sharedSchema = SdkClients.adminClient().databaseSchemas().create(schemaReq);
}
private Table createTestTableWithColumns(TestNamespace ns, String name, List<Column> columns) {
// Reuse shared entities for efficiency
initializeSharedDbEntities(ns);
CreateTable tableRequest = new CreateTable();
tableRequest.setName(name);
tableRequest.setDatabaseSchema(sharedSchema.getFullyQualifiedName());
tableRequest.setColumns(columns);
return SdkClients.adminClient().tables().create(tableRequest);
}
private Topic createTestTopic(TestNamespace ns, String baseName) {
String shortId = ns.shortPrefix();
org.openmetadata.schema.services.connections.messaging.KafkaConnection kafkaConn =
new org.openmetadata.schema.services.connections.messaging.KafkaConnection()
.withBootstrapServers("localhost:9092");
org.openmetadata.schema.api.services.CreateMessagingService msgSvcReq =
new org.openmetadata.schema.api.services.CreateMessagingService();
msgSvcReq.setName("search_msg_svc_" + shortId);
msgSvcReq.setServiceType(
org.openmetadata.schema.api.services.CreateMessagingService.MessagingServiceType.Kafka);
msgSvcReq.setConnection(
new org.openmetadata.schema.type.MessagingConnection().withConfig(kafkaConn));
MessagingService msgService = SdkClients.adminClient().messagingServices().create(msgSvcReq);
CreateTopic topicRequest = new CreateTopic();
topicRequest.setName(ns.prefix(baseName));
topicRequest.setService(msgService.getFullyQualifiedName());
topicRequest.setPartitions(1);
return SdkClients.adminClient().topics().create(topicRequest);
}
private Topic createTestTopicWithFields(TestNamespace ns, String name, List<Field> fields) {
String shortId = ns.shortPrefix();
org.openmetadata.schema.services.connections.messaging.KafkaConnection kafkaConn =
new org.openmetadata.schema.services.connections.messaging.KafkaConnection()
.withBootstrapServers("localhost:9092");
org.openmetadata.schema.api.services.CreateMessagingService msgSvcReq =
new org.openmetadata.schema.api.services.CreateMessagingService();
msgSvcReq.setName("many_field_msg_svc_" + shortId);
msgSvcReq.setServiceType(
org.openmetadata.schema.api.services.CreateMessagingService.MessagingServiceType.Kafka);
msgSvcReq.setConnection(
new org.openmetadata.schema.type.MessagingConnection().withConfig(kafkaConn));
MessagingService msgService = SdkClients.adminClient().messagingServices().create(msgSvcReq);
MessageSchema messageSchema =
new MessageSchema().withSchemaType(SchemaType.JSON).withSchemaFields(fields);
CreateTopic topicRequest = new CreateTopic();
topicRequest.setName(name);
topicRequest.setService(msgService.getFullyQualifiedName());
topicRequest.setPartitions(1);
topicRequest.setMessageSchema(messageSchema);
return SdkClients.adminClient().topics().create(topicRequest);
}
private List<Column> createManyTableColumns(int count) {
List<Column> columns = new ArrayList<>();
for (int i = 0; i < count; i++) {
columns.add(
new Column()
.withName("column_" + i + "_data_field")
.withDataType(ColumnDataType.VARCHAR)
.withDataLength(255));
}
return columns;
}
private List<Field> createManyTopicSchemaFields(int count) {
List<Field> fields = new ArrayList<>();
for (int i = 0; i < count; i++) {
fields.add(
new Field().withName("field_" + i + "_data_element").withDataType(FieldDataType.STRING));
}
return fields;
}
// ===================================================================
// ADVANCED SEARCH TESTS
// ===================================================================
@Test
void testSearchWithIncludeAggregationsParameter(TestNamespace ns) throws Exception {
OpenMetadataClient client = SdkClients.adminClient();
String query = "*";
String index = "table_search_index";
String resultWithAggs =
client.search().query(query).index(index).size(10).includeAggregations(true).execute();
assertNotNull(resultWithAggs);
JsonNode responseWithAggs = OBJECT_MAPPER.readTree(resultWithAggs);
assertTrue(
responseWithAggs.has("aggregations"),
"Response should contain aggregations when include_aggregations=true");
JsonNode aggregations = responseWithAggs.get("aggregations");
assertNotNull(aggregations, "Aggregations should not be null");
assertTrue(
aggregations.size() > 0, "Aggregations should contain at least one aggregation field");
String resultWithoutAggs =
client.search().query(query).index(index).size(10).includeAggregations(false).execute();
JsonNode responseWithoutAggs = OBJECT_MAPPER.readTree(resultWithoutAggs);
if (responseWithoutAggs.has("aggregations")) {
JsonNode aggsWithout = responseWithoutAggs.get("aggregations");
assertEquals(
0, aggsWithout.size(), "Aggregations should be empty when include_aggregations=false");
}