Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array values are preserved (#1300) #3095

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
Expand Up @@ -28,6 +28,9 @@ public enum Key {
/** PPL Settings. */
PPL_ENABLED("plugins.ppl.enabled"),

/** Query Settings. */
FIELD_TYPE_TOLERANCE("plugins.query.field_type_tolerance"),

/** Common Settings for SQL and PPL. */
QUERY_MEMORY_LIMIT("plugins.query.memory_limit"),
QUERY_SIZE_LIMIT("plugins.query.size_limit"),
Expand Down
10 changes: 5 additions & 5 deletions docs/user/beyond/partiql.rst
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,11 @@ Selecting top level for object fields, object fields of array value and nested f

os> SELECT city, accounts, projects FROM people;
fetched rows / total rows = 1/1
+-----------------------------------------------------+-----------+----------------------------------------------------------------------------------------------------------------+
| city | accounts | projects |
|-----------------------------------------------------+-----------+----------------------------------------------------------------------------------------------------------------|
| {'name': 'Seattle', 'location': {'latitude': 10.5}} | {'id': 1} | [{'name': 'AWS Redshift Spectrum querying'},{'name': 'AWS Redshift security'},{'name': 'AWS Aurora security'}] |
+-----------------------------------------------------+-----------+----------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------------+-----------------------+----------------------------------------------------------------------------------------------------------------+
| city | accounts | projects |
|-----------------------------------------------------+-----------------------+----------------------------------------------------------------------------------------------------------------|
| {'name': 'Seattle', 'location': {'latitude': 10.5}} | [{'id': 1},{'id': 2}] | [{'name': 'AWS Redshift Spectrum querying'},{'name': 'AWS Redshift security'},{'name': 'AWS Aurora security'}] |
+-----------------------------------------------------+-----------------------+----------------------------------------------------------------------------------------------------------------+

Example 2: Selecting Deeper Levels
----------------------------------
Expand Down
10 changes: 5 additions & 5 deletions docs/user/ppl/general/datatypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -385,8 +385,8 @@ Select deeper level for object fields of array value which returns the first ele

os> source = people | fields accounts, accounts.id;
fetched rows / total rows = 1/1
+-----------+-------------+
| accounts | accounts.id |
|-----------+-------------|
| {'id': 1} | 1 |
+-----------+-------------+
+-----------------------+-------------+
| accounts | accounts.id |
|-----------------------+-------------|
| [{'id': 1},{'id': 2}] | 1 |
+-----------------------+-------------+
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ public void testSelectNestedFieldItself() {
@Test
public void testSelectObjectFieldOfArrayValuesItself() {
JSONObject response = new JSONObject(query("SELECT accounts FROM %s"));

// Only the first element of the list of is returned.
verifyDataRows(response, rows(new JSONObject("{\"id\": 1}")));
verifyDataRows(response, rows(new JSONArray("[{\"id\":1},{\"id\":2}]")));
penghuo marked this conversation as resolved.
Show resolved Hide resolved
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ private Settings defaultSettings() {
new ImmutableMap.Builder<Key, Object>()
.put(Key.QUERY_SIZE_LIMIT, 200)
.put(Key.SQL_PAGINATION_API_SEARCH_AFTER, true)
.put(Key.FIELD_TYPE_TOLERANCE, false)
dai-chen marked this conversation as resolved.
Show resolved Hide resolved
.build();

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ public void test_nested_in_where_as_predicate_expression_with_multiple_condition
+ " nested(message.dayOfWeek) >= 4";
JSONObject result = executeJdbcRequest(query);
assertEquals(2, result.getInt("total"));
verifyDataRows(result, rows("c", "ab", 4), rows("zz", "aa", 6));
verifyDataRows(result, rows("c", "ab", 4), rows("zz", new JSONArray(List.of("aa", "bb")), 6));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ private Settings defaultSettings() {
.put(Key.QUERY_SIZE_LIMIT, 200)
.put(Key.SQL_CURSOR_KEEP_ALIVE, TimeValue.timeValueMinutes(1))
.put(Key.SQL_PAGINATION_API_SEARCH_AFTER, true)
.put(Key.FIELD_TYPE_TOLERANCE, true)
.build();

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ public class OpenSearchExprValueFactory {
/** The Mapping of Field and ExprType. */
private final Map<String, OpenSearchDataType> typeMapping;

private final boolean fieldTypeTolerance;
penghuo marked this conversation as resolved.
Show resolved Hide resolved

/**
* Extend existing mapping by new data without overwrite. Called from aggregation only {@see
* AggregationQueryBuilder#buildTypeMapping}.
Expand Down Expand Up @@ -140,8 +142,10 @@ public void extendTypeMapping(Map<String, OpenSearchDataType> typeMapping) {
.build();

/** Constructor of OpenSearchExprValueFactory. */
public OpenSearchExprValueFactory(Map<String, OpenSearchDataType> typeMapping) {
public OpenSearchExprValueFactory(
Map<String, OpenSearchDataType> typeMapping, boolean fieldTypeTolerance) {
this.typeMapping = OpenSearchDataType.traverseAndFlatten(typeMapping);
this.fieldTypeTolerance = fieldTypeTolerance;
}

/**
Expand All @@ -164,7 +168,7 @@ public ExprValue construct(String jsonString, boolean supportArrays) {
new OpenSearchJsonContent(OBJECT_MAPPER.readTree(jsonString)),
TOP_PATH,
Optional.of(STRUCT),
supportArrays);
fieldTypeTolerance || supportArrays);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm thinking should we use fieldTypeTolerance directly in parseArray (not sure parseGeopoint)? Because I think supportArrays has its own meaning? Unless we change it and rename the argument?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also applies to geopoints and anything else that could be in an array. If fieldTypeTolerance is not also applied to parseGeopoint, then an array of geopoints would get reduced to only the first element.

} catch (JsonProcessingException e) {
throw new IllegalStateException(String.format("invalid json: %s.", jsonString), e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ public OpenSearchQueryRequest(
* @param engine OpenSearchSqlEngine to get node-specific context.
* @throws IOException thrown if reading from input {@code in} fails.
*/
public OpenSearchQueryRequest(StreamInput in, OpenSearchStorageEngine engine) throws IOException {
public OpenSearchQueryRequest(
StreamInput in, OpenSearchStorageEngine engine, boolean fieldTypeTolerance)
throws IOException {
// Deserialize the SearchSourceBuilder from the string representation
String sourceBuilderString = in.readString();

Expand All @@ -151,7 +153,8 @@ public OpenSearchQueryRequest(StreamInput in, OpenSearchStorageEngine engine) th
}

OpenSearchIndex index = (OpenSearchIndex) engine.getTable(null, indexName.toString());
exprValueFactory = new OpenSearchExprValueFactory(index.getFieldOpenSearchTypes());
exprValueFactory =
new OpenSearchExprValueFactory(index.getFieldOpenSearchTypes(), fieldTypeTolerance);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic should similar to OpenSearchScrollRequest right? If yes, fieldTypeTolerance should not associate with OpenSearchQueryRequest.

    OpenSearchIndex index = (OpenSearchIndex) engine.getTable(null, indexName.toString());
    exprValueFactory =
        new OpenSearchExprValueFactory(
            index.getFieldOpenSearchTypes(), index.isFieldTypeTolerance());

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe another option is to create OpenSearchExprValueFactory in request builder and pass it to request? In case factory needs more settings passed in future?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated.

}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ private OpenSearchRequest buildRequestWithPit(
int size = requestedTotalSize;
FetchSourceContext fetchSource = this.sourceBuilder.fetchSource();
List<String> includes = fetchSource != null ? Arrays.asList(fetchSource.includes()) : List.of();
boolean fieldTypeTolerance = settings.getSettingValue(Settings.Key.FIELD_TYPE_TOLERANCE);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unused field, remove it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed.


if (pageSize == null) {
if (startFrom + size > maxResultWindow) {
Expand Down Expand Up @@ -141,6 +142,7 @@ private OpenSearchRequest buildRequestWithScroll(
int size = requestedTotalSize;
FetchSourceContext fetchSource = this.sourceBuilder.fetchSource();
List<String> includes = fetchSource != null ? Arrays.asList(fetchSource.includes()) : List.of();
boolean fieldTypeTolerance = settings.getSettingValue(Settings.Key.FIELD_TYPE_TOLERANCE);

if (pageSize == null) {
if (startFrom + size > maxResultWindow) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ public OpenSearchScrollRequest(StreamInput in, OpenSearchStorageEngine engine)
includes = in.readStringList();
indexName = new IndexName(in);
OpenSearchIndex index = (OpenSearchIndex) engine.getTable(null, indexName.toString());
exprValueFactory = new OpenSearchExprValueFactory(index.getFieldOpenSearchTypes());
exprValueFactory =
new OpenSearchExprValueFactory(
index.getFieldOpenSearchTypes(), index.isFieldTypeTolerance());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,13 @@ public class OpenSearchSettings extends Settings {
Setting.Property.NodeScope,
Setting.Property.Dynamic);

public static final Setting<?> FIELD_TYPE_TOLERANCE_SETTING =
Setting.boolSetting(
Key.FIELD_TYPE_TOLERANCE.getKeyValue(),
true,
Setting.Property.NodeScope,
Setting.Property.Dynamic);

/** Construct OpenSearchSetting. The OpenSearchSetting must be singleton. */
@SuppressWarnings("unchecked")
public OpenSearchSettings(ClusterSettings clusterSettings) {
Expand Down Expand Up @@ -372,13 +379,19 @@ public OpenSearchSettings(ClusterSettings clusterSettings) {
clusterSettings,
Key.SESSION_INACTIVITY_TIMEOUT_MILLIS,
SESSION_INACTIVITY_TIMEOUT_MILLIS_SETTING,
new Updater((Key.SESSION_INACTIVITY_TIMEOUT_MILLIS)));
new Updater(Key.SESSION_INACTIVITY_TIMEOUT_MILLIS));
register(
settingBuilder,
clusterSettings,
Key.STREAMING_JOB_HOUSEKEEPER_INTERVAL,
STREAMING_JOB_HOUSEKEEPER_INTERVAL_SETTING,
new Updater((Key.STREAMING_JOB_HOUSEKEEPER_INTERVAL)));
new Updater(Key.STREAMING_JOB_HOUSEKEEPER_INTERVAL));
register(
settingBuilder,
clusterSettings,
Key.FIELD_TYPE_TOLERANCE,
FIELD_TYPE_TOLERANCE_SETTING,
new Updater(Key.FIELD_TYPE_TOLERANCE));
defaultSettings = settingBuilder.build();
}

Expand Down Expand Up @@ -455,6 +468,7 @@ public static List<Setting<?>> pluginSettings() {
.add(DATASOURCES_LIMIT_SETTING)
.add(SESSION_INACTIVITY_TIMEOUT_MILLIS_SETTING)
.add(STREAMING_JOB_HOUSEKEEPER_INTERVAL_SETTING)
.add(FIELD_TYPE_TOLERANCE_SETTING)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ public TableScanBuilder createScanBuilder() {
requestBuilder ->
new OpenSearchIndexScan(
client,
settings.getSettingValue(Settings.Key.FIELD_TYPE_TOLERANCE),
requestBuilder.getMaxResponseSize(),
requestBuilder.build(indexName, getMaxResultWindow(), cursorKeepAlive, client));
return new OpenSearchIndexScanBuilder(builder, createScanOperator);
Expand All @@ -177,7 +178,12 @@ private OpenSearchExprValueFactory createExprValueFactory() {
Map<String, OpenSearchDataType> allFields = new HashMap<>();
getReservedFieldTypes().forEach((k, v) -> allFields.put(k, OpenSearchDataType.of(v)));
allFields.putAll(getFieldOpenSearchTypes());
return new OpenSearchExprValueFactory(allFields);
return new OpenSearchExprValueFactory(
allFields, settings.getSettingValue(Settings.Key.FIELD_TYPE_TOLERANCE));
}

public boolean isFieldTypeTolerance() {
return settings.getSettingValue(Settings.Key.FIELD_TYPE_TOLERANCE);
}

@VisibleForTesting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,18 @@ public class OpenSearchIndexScan extends TableScanOperator implements Serializab
/** Search response for current batch. */
private Iterator<ExprValue> iterator;

private Settings pluginSettings;
private boolean fieldTypeTolerance;

/** Creates index scan based on a provided OpenSearchRequestBuilder. */
public OpenSearchIndexScan(
OpenSearchClient client, int maxResponseSize, OpenSearchRequest request) {
OpenSearchClient client,
boolean fieldTypeTolerance,
int maxResponseSize,
OpenSearchRequest request) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we could keep original constructor which means fieldTypeTolerance=true, it could avoid unnecessary UT chagne.

Copy link
Collaborator

@Swiddis Swiddis Oct 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. I'm also curious if it even needs to be a parameter since nearly every refactor hardcodes it to true and the false case isn't even tested. What's the use case where we don't want this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed back, since this change is not actually needed.

this.client = client;
this.maxResponseSize = maxResponseSize;
this.request = request;
this.fieldTypeTolerance = fieldTypeTolerance;
}

@Override
Expand Down Expand Up @@ -129,9 +133,10 @@ public void readExternal(ObjectInput in) throws IOException {
boolean pointInTimeEnabled =
Boolean.parseBoolean(
client.meta().get(Settings.Key.SQL_PAGINATION_API_SEARCH_AFTER.getKeyValue()));
fieldTypeTolerance = in.readBoolean();
try (BytesStreamInput bsi = new BytesStreamInput(requestStream)) {
if (pointInTimeEnabled) {
request = new OpenSearchQueryRequest(bsi, engine);
request = new OpenSearchQueryRequest(bsi, engine, fieldTypeTolerance);
} else {
request = new OpenSearchScrollRequest(bsi, engine);
}
Expand All @@ -157,6 +162,7 @@ public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(reqOut.size());
out.write(reqAsBytes, 0, reqOut.size());

out.writeBoolean(fieldTypeTolerance);
out.writeInt(maxResponseSize);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ private OpenSearchExprValueFactory buildValueFactory(Set<ReferenceExpression> fi
Map<String, OpenSearchDataType> typeEnv =
fields.stream()
.collect(toMap(ReferenceExpression::getAttr, e -> OpenSearchDataType.of(e.type())));
return new OpenSearchExprValueFactory(typeEnv);
return new OpenSearchExprValueFactory(typeEnv, false);
}

private Environment<Expression, ExprValue> buildValueEnv(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,6 @@ void search() {
new SearchHits(
new SearchHit[] {searchHit}, new TotalHits(1L, TotalHits.Relation.EQUAL_TO), 1.0F));
when(searchHit.getSourceAsString()).thenReturn("{\"id\", 1}");
when(searchHit.getInnerHits()).thenReturn(null);
when(factory.construct(any(), anyBoolean())).thenReturn(exprTupleValue);

// Mock second scroll request followed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,6 @@ void search() throws IOException {
new SearchHits(
new SearchHit[] {searchHit}, new TotalHits(1L, TotalHits.Relation.EQUAL_TO), 1.0F));
when(searchHit.getSourceAsString()).thenReturn("{\"id\", 1}");
when(searchHit.getInnerHits()).thenReturn(null);
when(factory.construct(any(), anyBoolean())).thenReturn(exprTupleValue);

// Mock second scroll request followed
Expand Down
Loading
Loading