Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
package org.openmetadata.it.tests;

import static org.junit.jupiter.api.Assertions.assertEquals;
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.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Random;
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.CreateDatabase;
import org.openmetadata.schema.api.data.CreateDatabaseSchema;
import org.openmetadata.schema.api.data.CreateTable;
import org.openmetadata.schema.entity.data.Database;
import org.openmetadata.schema.entity.data.DatabaseSchema;
import org.openmetadata.schema.entity.services.DatabaseService;
import org.openmetadata.schema.type.Column;
import org.openmetadata.schema.type.ColumnDataType;
import org.openmetadata.sdk.fluent.DatabaseServices;

/**
* The NLQ keyword fallback and {@code /search/aggregate?q=} must search the configured fields. A
* query_string without fields expands to every field in the mapping, and on OpenSearch's default
* max_clause_count (1024) a single long token is enough to fail the table shard: HTTP 500 on the
* table index, and silently dropped shards on the {@code dataAsset} alias.
*/
@Execution(ExecutionMode.CONCURRENT)
@ExtendWith(TestNamespaceExtension.class)
public class SearchFieldlessQueryIT {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final HttpClient HTTP_CLIENT =
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private static final List<String> INDEXES = List.of("table_search_index", "dataAsset");
// Longer runs exceed the keyword search's own clause budget on large indexes (#34380).
private static final List<Integer> TOKEN_LENGTHS = List.of(21, 40);
private static final String ALPHANUMERIC = "abcdefghijklmnopqrstuvwxyz0123456789";

@Test
void nlqFallbackHandlesLongTokensAndFindsTheTable(TestNamespace ns) throws Exception {
String token = randomToken(21);
String tableName = createIndexedTable(ns, token);

JsonNode found = getJson(nlqPath("table_search_index", token));
assertTrue(
found.path("hits").toString().contains(tableName),
"NLQ fallback should find the table by its token -> " + found.path("hits"));

for (String index : INDEXES) {
for (int length : TOKEN_LENGTHS) {
assertNoShardFailed(getJson(nlqPath(index, randomToken(length))));
}
}
}

@Test
void aggregateTextHandlesLongTokens(TestNamespace ns) throws Exception {
createIndexedTable(ns, randomToken(21));

for (String index : INDEXES) {
for (int length : TOKEN_LENGTHS) {
String path =
"/v1/search/aggregate?index="
+ encode(index)
+ "&field=entityType&size=10&q="
+ encode(randomToken(length));
assertNoShardFailed(getJson(path));
}
}
}

private static String createIndexedTable(TestNamespace ns, String token) {
String shortId = ns.shortPrefix();
DatabaseService service =
DatabaseServices.builder()
.name("fieldless_svc_" + shortId)
.connection(
DatabaseServices.postgresConnection()
.hostPort("localhost:5432")
.username("test")
.build())
.create();
Database database =
SdkClients.adminClient()
.databases()
.create(
new CreateDatabase()
.withName("fieldless_db_" + shortId)
.withService(service.getFullyQualifiedName()));
DatabaseSchema schema =
SdkClients.adminClient()
.databaseSchemas()
.create(
new CreateDatabaseSchema()
.withName("fieldless_schema_" + shortId)
.withDatabase(database.getFullyQualifiedName()));
String tableName = ns.prefix(token);
SdkClients.adminClient()
.tables()
.create(
new CreateTable()
.withName(tableName)
.withDatabaseSchema(schema.getFullyQualifiedName())
.withColumns(
List.of(new Column().withName("id").withDataType(ColumnDataType.BIGINT))));
awaitIndexed(tableName);
return tableName;
}

private static void awaitIndexed(String tableName) {
Awaitility.await()
.atMost(90, TimeUnit.SECONDS)
.pollInterval(500, TimeUnit.MILLISECONDS)
.until(
() ->
SdkClients.adminClient()
.search()
.query(tableName)
.index("table_search_index")
.size(10)
.execute()
.contains(tableName));
}

private static void assertNoShardFailed(JsonNode response) {
assertEquals(
0, response.path("_shards").path("failed").asInt(-1), "shards failed -> " + response);
}

private static JsonNode getJson(String path) throws Exception {
HttpRequest request =
HttpRequest.newBuilder()
.uri(URI.create(SdkClients.getServerUrl() + path))
.header("Authorization", "Bearer " + SdkClients.getAdminToken())
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode(), path + " -> " + response.body());
return OBJECT_MAPPER.readTree(response.body());
}

private static String nlqPath(String index, String query) {
return "/v1/search/nlq/query?index=" + encode(index) + "&size=10&q=" + encode(query);
}

/** Letters and digits only, seeded by length so a failure reproduces with the same input. */
private static String randomToken(int length) {
Random random = new Random(length);
StringBuilder token = new StringBuilder(length);
for (int i = 0; i < length; i++) {
token.append(ALPHANUMERIC.charAt(random.nextInt(ALPHANUMERIC.length())));
}
return token.toString();
}

private static String encode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,14 @@ public static boolean isColumnIndex(String indexName) {
};
}

/** Indexes whose free text is searched by the data-asset builder over the configured fields. */
public static boolean usesDataAssetSearchBuilder(String indexName) {
return isDataAssetIndex(indexName)
|| isColumnIndex(indexName)
|| SearchClient.GLOBAL_SEARCH_ALIAS.equals(indexName)
|| SearchClient.DATA_ASSET_SEARCH_ALIAS.equals(indexName);
}

public static boolean isServiceIndex(String indexName) {
return switch (indexName) {
case "api_service_search_index",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
public class ElasticSearchAggregationManager implements AggregationManagementClient {
private static final ContextMemorySearchVisibility MEMORY_VISIBILITY =
new ContextMemorySearchVisibility(new ElasticQueryBuilderFactory());
private static final String MATCH_ALL_TEXT = "*";

private final ElasticsearchClient client;
private final boolean isClientAvailable;
Expand Down Expand Up @@ -124,6 +125,27 @@ private Query restrictToOrgWideMemories(Query query) {
: Query.of(q -> q.bool(b -> b.must(query).filter(memoryFilter)));
}

/**
* A bare query_string searches every field in the mapping, which on large data-asset mappings can
* exceed the cluster's max_clause_count, so data-asset text goes through the configured fields
* instead. {@code *} and other indexes keep the bare query_string.
*/
private static Query plainTextQuery(String index, String text) {
String indexName = Entity.getSearchRepository().getIndexNameWithoutAlias(index);
if (!MATCH_ALL_TEXT.equals(text.trim()) && SearchUtils.usesDataAssetSearchBuilder(indexName)) {
return configuredFieldsQuery(index, text);
}
return Query.of(q -> q.queryString(qs -> qs.query(text)));
}

private static Query configuredFieldsQuery(String index, String text) {
SearchSettings searchSettings =
SettingsCache.getSetting(SettingsType.SEARCH_SETTINGS, SearchSettings.class);
return new ElasticSearchSourceBuilderFactory(searchSettings)
.getSearchSourceBuilderV2(index, text, 0, 0, false, false)
.query();
}

private String praseJsonQuery(String jsonQuery) throws JsonProcessingException {
JsonNode rootNode = mapper.readTree(jsonQuery);
String queryToProcess = jsonQuery;
Expand Down Expand Up @@ -162,19 +184,12 @@ public Response aggregate(AggregationRequest request) throws IOException {
throw new IOException("Failed to parse JSON query: " + e.getMessage(), e);
}
} else {
query = Query.of(q -> q.queryString(qs -> qs.query(request.getQuery())));
query = plainTextQuery(indexName, request.getQuery());
}
}

if (!CommonUtil.nullOrEmpty(request.getQueryText())) {
SearchSettings searchSettings =
SettingsCache.getSetting(SettingsType.SEARCH_SETTINGS, SearchSettings.class);
ElasticSearchSourceBuilderFactory searchBuilderFactory =
new ElasticSearchSourceBuilderFactory(searchSettings);
ElasticSearchRequestBuilder textQueryBuilder =
searchBuilderFactory.getSearchSourceBuilderV2(
indexName, request.getQueryText(), 0, 0, false, false);
Query textQuery = textQueryBuilder.query();
Query textQuery = configuredFieldsQuery(indexName, request.getQueryText());
if (textQuery != null) {
if (query != null) {
final Query finalQuery = query;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import es.co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import es.co.elastic.clients.elasticsearch._types.aggregations.StringTermsBucket;
import es.co.elastic.clients.elasticsearch._types.mapping.Property;
import es.co.elastic.clients.elasticsearch._types.query_dsl.Operator;
import es.co.elastic.clients.elasticsearch._types.query_dsl.Query;
import es.co.elastic.clients.elasticsearch.core.SearchRequest;
import es.co.elastic.clients.elasticsearch.core.SearchResponse;
Expand Down Expand Up @@ -1899,70 +1898,14 @@ private List<EntityHierarchy> buildDomainSearchHierarchy(
}

/**
* Fallback to basic query_string search when NLQ transformation fails or is unavailable.
* Uses the new Java API client for query execution.
* Answers an NLQ request that could not be translated with the regular keyword search, so it gets
* the configured fields, boosts, filters and clause budget of /search/query.
*/
private Response fallbackToBasicSearch(
org.openmetadata.schema.search.SearchRequest request, SubjectContext subjectContext) {
try {
LOG.debug("Falling back to basic query_string search for NLQ: {}", request.getQuery());

ElasticSearchRequestBuilder requestBuilder = new ElasticSearchRequestBuilder();

// Build basic query_string query using new API
Query queryStringQuery =
Query.of(
q -> q.queryString(qs -> qs.query(request.getQuery()).defaultOperator(Operator.And)));

requestBuilder.query(queryStringQuery);
requestBuilder.from(request.getFrom());
requestBuilder.size(request.getSize());

// Apply RBAC constraints using new API
if (SearchUtils.shouldApplyRbacConditions(subjectContext, rbacConditionEvaluator)) {
OMQueryBuilder rbacQueryBuilder = rbacConditionEvaluator.evaluateConditions(subjectContext);
if (rbacQueryBuilder != null) {
Query rbacQuery =
((org.openmetadata.service.search.elasticsearch.queries.ElasticQueryBuilder)
rbacQueryBuilder)
.buildV2();
Query existingQuery = requestBuilder.query();
if (existingQuery != null) {
Query combinedQuery =
Query.of(
qb ->
qb.bool(
b -> {
b.must(existingQuery);
b.filter(rbacQuery);
return b;
}));
requestBuilder.query(combinedQuery);
} else {
requestBuilder.query(rbacQuery);
}
}
}

applyContextMemoryVisibility(subjectContext, requestBuilder);

// Add aggregations for fallback NLQ search
addAggregationsToNLQQuery(requestBuilder, request.getIndex());

SearchRequest searchRequest = requestBuilder.build(request.getIndex());
Timer.Sample searchTimerSample = RequestLatencyContext.startSearchOperation();
SearchResponse<JsonData> searchResponse;
try {
searchResponse = client.search(searchRequest, JsonData.class);
} finally {
if (searchTimerSample != null) {
RequestLatencyContext.endSearchOperation(searchTimerSample);
}
}

return Response.status(Response.Status.OK)
.entity(serializeSearchResponse(searchResponse))
.build();
LOG.debug("Falling back to keyword search for NLQ: {}", request.getQuery());
return search(request, subjectContext);
} catch (Exception e) {
LOG.error("Error in fallback search: {}", e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
public class OpenSearchAggregationManager implements AggregationManagementClient {
private static final ContextMemorySearchVisibility MEMORY_VISIBILITY =
new ContextMemorySearchVisibility(new OpenSearchQueryBuilderFactory());
private static final String MATCH_ALL_TEXT = "*";

private final OpenSearchClient client;
private final boolean isClientAvailable;
Expand Down Expand Up @@ -123,6 +124,27 @@ private Query restrictToOrgWideMemories(Query query) {
: Query.of(q -> q.bool(b -> b.must(query).filter(memoryFilter)));
}

/**
* A bare query_string searches every field in the mapping, which on large data-asset mappings can
* exceed the cluster's max_clause_count, so data-asset text goes through the configured fields
* instead. {@code *} and other indexes keep the bare query_string.
*/
private static Query plainTextQuery(String index, String text) {
String indexName = Entity.getSearchRepository().getIndexNameWithoutAlias(index);
if (!MATCH_ALL_TEXT.equals(text.trim()) && SearchUtils.usesDataAssetSearchBuilder(indexName)) {
return configuredFieldsQuery(index, text);
}
return Query.of(q -> q.queryString(qs -> qs.query(text)));
}

private static Query configuredFieldsQuery(String index, String text) {
SearchSettings searchSettings =
SettingsCache.getSetting(SettingsType.SEARCH_SETTINGS, SearchSettings.class);
return new OpenSearchSourceBuilderFactory(searchSettings)
.getSearchSourceBuilderV2(index, text, 0, 0, false, false)
.query();
}

private String praseJsonQuery(String jsonQuery) throws JsonProcessingException {
JsonNode rootNode = mapper.readTree(jsonQuery);
String queryToProcess = jsonQuery;
Expand Down Expand Up @@ -161,19 +183,12 @@ public Response aggregate(AggregationRequest request) throws IOException {
throw new IOException("Failed to parse JSON query: " + e.getMessage(), e);
}
} else {
query = Query.of(q -> q.queryString(qs -> qs.query(request.getQuery())));
query = plainTextQuery(request.getIndex(), request.getQuery());
}
}

if (!CommonUtil.nullOrEmpty(request.getQueryText())) {
SearchSettings searchSettings =
SettingsCache.getSetting(SettingsType.SEARCH_SETTINGS, SearchSettings.class);
OpenSearchSourceBuilderFactory searchBuilderFactory =
new OpenSearchSourceBuilderFactory(searchSettings);
OpenSearchRequestBuilder textQueryBuilder =
searchBuilderFactory.getSearchSourceBuilderV2(
request.getIndex(), request.getQueryText(), 0, 0, false, false);
Query textQuery = textQueryBuilder.query();
Query textQuery = configuredFieldsQuery(request.getIndex(), request.getQueryText());
if (textQuery != null) {
if (query != null) {
final Query finalQuery = query;
Expand Down
Loading
Loading