You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by "lnbest0707-uber (via GitHub)" <gi...@apache.org> on 2024/04/03 19:35:49 UTC
[PR] Upstream fork/schema transformer [pinot]
lnbest0707-uber opened a new pull request, #12788:
URL: https://github.com/apache/pinot/pull/12788
tags: `feature`, `refactor`, `release-notes`
This adds an evolved version of ShemaConformingTransformerV2, it evolves from the existing one with following new features:
Refactored code with better readability and extensibility
Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time. And it only allows primitive type fields to be the value.
Extract flattened key-value pairs as mergedTextIndex for better text searching.
Add shingle index tokenization functionality for extremely large text fields.
Add flexibility to map json extracted field name to meaningful user specified column name
Improve serialization logics to handle nested json fields
Enforce graceful handling on extracted String type column. Will convert collection or array to String if column type is singleField.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "chenboat (via GitHub)" <gi...@apache.org>.
chenboat commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552463445
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
Review Comment:
Change to SchemaConformingTransformerConfigV2?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "jackluo923 (via GitHub)" <gi...@apache.org>.
jackluo923 commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552815667
##########
pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/SchemaConformingTransformerV2Config.java:
##########
@@ -0,0 +1,237 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.config.table.ingestion;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.spi.config.BaseJsonConfig;
+
+public class SchemaConformingTransformerV2Config extends BaseJsonConfig {
+ @JsonPropertyDescription("Enable indexable extras")
+ private boolean _enableIndexableExtras = true;
+
+ @JsonPropertyDescription("Name of the field that should contain extra fields that are not part of the schema.")
+ private String _indexableExtrasField = "json_data";
+
+ @JsonPropertyDescription("Enable unindexable extras")
+ private boolean _enableUnindexableExtras = true;
+
+ @JsonPropertyDescription(
+ "Like indexableExtrasField except it only contains fields with the suffix in unindexableFieldSuffix.")
+ private String _unindexableExtrasField = "json_data_no_idx";
+
+ @JsonPropertyDescription("The suffix of fields that must be stored in unindexableExtrasField")
+ private String _unindexableFieldSuffix = "_noindex";
+
+ @JsonPropertyDescription("Array of flattened (dot-delimited) object paths to drop")
+ private Set<String> _fieldPathsToDrop = new HashSet<>();
+
+ @JsonPropertyDescription("Map from customized meaningful column name to json key path")
+ private Map<String, String> _columnNameToJsonKeyPathMap = new HashMap<>();
+
+ @JsonPropertyDescription("mergedTextIndex field")
+ private String _mergedTextIndexField = "__mergedTextIndex";
+
+ @JsonPropertyDescription("mergedTextIndex token max length")
+ private int _mergedTextIndexTokenMaxLength = 32766;
+
+ @JsonPropertyDescription(
+ "Recall that merged text index token is in the format of <value:key>. "
+ + "The mergedTextIndex shingling overlap length refers to the "
+ + "maximum search length of the value that will yield results with "
+ + "100% accuracy. If the value is null, shingle index will be turned off "
+ + "and the value will be truncated such that the token is equal to "
+ + "_mergedTextIndexTokenMaxLength"
+ )
+ private @Nullable Integer _mergedTextIndexShinglingOverlapLength = null;
+
+ @JsonPropertyDescription("mergedTextIndex binary token detection minimum length")
+ private Integer _mergedTextIndexBinaryTokenDetectionMinLength = 512;
+
+ @JsonPropertyDescription("Array of paths to exclude from merged text index.")
+ private Set<String> _mergedTextIndexPathToExclude = new HashSet<>();
+
+ // TODO: set default value from CLPRewriter once it open sourced
+ @JsonPropertyDescription("Array of suffix to exclude from merged text index.")
+ private List<String> _mergedTextIndexSuffixToExclude = Arrays.asList("_logtype", "_dictionaryVars", "_encodedVars");
+
+ @JsonPropertyDescription("Dedicated fields to double ingest into json_data column")
+ private Set<String> _fieldsToDoubleIngest = new HashSet<>();
+
+ @JsonCreator
+ public SchemaConformingTransformerV2Config(
+ @JsonProperty("enableIndexableExtras") @Nullable Boolean enableIndexableExtras,
+ @JsonProperty("indexableExtrasField") String indexableExtrasField,
+ @JsonProperty("enableUnindexableExtras") @Nullable Boolean enableUnindexableExtras,
+ @JsonProperty("unindexableExtrasField") @Nullable String unindexableExtrasField,
+ @JsonProperty("unindexableFieldSuffix") @Nullable String unindexableFieldSuffix,
+ @JsonProperty("fieldPathsToDrop") @Nullable Set<String> fieldPathsToDrop,
+ @JsonProperty("mergedTextIndexField") @Nullable String mergedTextIndexField,
+ @JsonProperty("mergedTextIndexTokenMaxLength") @Nullable Integer mergedTextIndexTokenMaxLength,
+ @JsonProperty("mergedTextIndexShinglingOverlapLength") @Nullable Integer mergedTextIndexShinglingOverlapLength,
+ @JsonProperty("mergedTextIndexBinaryTokenDetectionMinLength")
+ @Nullable Integer mergedTextIndexBinaryTokenDetectionMinLength,
+ @JsonProperty("mergedTextIndexPathToExclude") @Nullable Set<String> mergedTextIndexPathToExclude,
+ @JsonProperty("fieldsToDoubleIngest") @Nullable Set<String> fieldsToDoubleIngest
+ ) {
+ setEnableIndexableExtras(enableIndexableExtras);
+ setIndexableExtrasField(indexableExtrasField);
+ setEnableUnindexableExtras(enableUnindexableExtras);
+ setUnindexableExtrasField(unindexableExtrasField);
+ setUnindexableFieldSuffix(unindexableFieldSuffix);
+ setFieldPathsToDrop(fieldPathsToDrop);
+
+ setMergedTextIndexField(mergedTextIndexField);
+ setMergedTextIndexTokenMaxLength(mergedTextIndexTokenMaxLength);
+ setMergedTextIndexShinglingTokenOverlapLength(mergedTextIndexShinglingOverlapLength);
+ setMergedTextIndexBinaryTokenDetectionMinLength(mergedTextIndexBinaryTokenDetectionMinLength);
+ setMergedTextIndexPathToExclude(mergedTextIndexPathToExclude);
+ setFieldsToDoubleIngest(fieldsToDoubleIngest);
+ }
+
+ public SchemaConformingTransformerV2Config setEnableIndexableExtras(Boolean enableIndexableExtras) {
+ _enableIndexableExtras = enableIndexableExtras == null ? _enableUnindexableExtras : enableIndexableExtras;
+ return this;
+ }
+
+ public String getIndexableExtrasField() {
+ return _enableIndexableExtras ? _indexableExtrasField : null;
+ }
+
+ public SchemaConformingTransformerV2Config setIndexableExtrasField(String indexableExtrasField) {
+ _indexableExtrasField = (null == indexableExtrasField) ? _indexableExtrasField : indexableExtrasField;
+ return this;
+ }
+
+ public SchemaConformingTransformerV2Config setEnableUnindexableExtras(Boolean enableUnindexableExtras) {
+ _enableUnindexableExtras = enableUnindexableExtras == null ? _enableUnindexableExtras : enableUnindexableExtras;
Review Comment:
Can we standardize the order and formatting of the operands in the condition of the ternary operator? Currently, sometimes null is in the front, sometimes it is in the back. Sometimes there's brackets, sometimes it is missing.
##########
pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/SchemaConformingTransformerV2Config.java:
##########
@@ -0,0 +1,237 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.config.table.ingestion;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.spi.config.BaseJsonConfig;
+
+public class SchemaConformingTransformerV2Config extends BaseJsonConfig {
+ @JsonPropertyDescription("Enable indexable extras")
+ private boolean _enableIndexableExtras = true;
+
+ @JsonPropertyDescription("Name of the field that should contain extra fields that are not part of the schema.")
+ private String _indexableExtrasField = "json_data";
+
+ @JsonPropertyDescription("Enable unindexable extras")
+ private boolean _enableUnindexableExtras = true;
+
+ @JsonPropertyDescription(
+ "Like indexableExtrasField except it only contains fields with the suffix in unindexableFieldSuffix.")
+ private String _unindexableExtrasField = "json_data_no_idx";
+
+ @JsonPropertyDescription("The suffix of fields that must be stored in unindexableExtrasField")
+ private String _unindexableFieldSuffix = "_noindex";
+
+ @JsonPropertyDescription("Array of flattened (dot-delimited) object paths to drop")
+ private Set<String> _fieldPathsToDrop = new HashSet<>();
+
+ @JsonPropertyDescription("Map from customized meaningful column name to json key path")
+ private Map<String, String> _columnNameToJsonKeyPathMap = new HashMap<>();
+
+ @JsonPropertyDescription("mergedTextIndex field")
+ private String _mergedTextIndexField = "__mergedTextIndex";
+
+ @JsonPropertyDescription("mergedTextIndex token max length")
+ private int _mergedTextIndexTokenMaxLength = 32766;
+
+ @JsonPropertyDescription(
+ "Recall that merged text index token is in the format of <value:key>. "
+ + "The mergedTextIndex shingling overlap length refers to the "
+ + "maximum search length of the value that will yield results with "
+ + "100% accuracy. If the value is null, shingle index will be turned off "
+ + "and the value will be truncated such that the token is equal to "
+ + "_mergedTextIndexTokenMaxLength"
+ )
+ private @Nullable Integer _mergedTextIndexShinglingOverlapLength = null;
+
+ @JsonPropertyDescription("mergedTextIndex binary token detection minimum length")
+ private Integer _mergedTextIndexBinaryTokenDetectionMinLength = 512;
+
+ @JsonPropertyDescription("Array of paths to exclude from merged text index.")
+ private Set<String> _mergedTextIndexPathToExclude = new HashSet<>();
+
+ // TODO: set default value from CLPRewriter once it open sourced
+ @JsonPropertyDescription("Array of suffix to exclude from merged text index.")
+ private List<String> _mergedTextIndexSuffixToExclude = Arrays.asList("_logtype", "_dictionaryVars", "_encodedVars");
+
+ @JsonPropertyDescription("Dedicated fields to double ingest into json_data column")
+ private Set<String> _fieldsToDoubleIngest = new HashSet<>();
+
+ @JsonCreator
+ public SchemaConformingTransformerV2Config(
+ @JsonProperty("enableIndexableExtras") @Nullable Boolean enableIndexableExtras,
+ @JsonProperty("indexableExtrasField") String indexableExtrasField,
+ @JsonProperty("enableUnindexableExtras") @Nullable Boolean enableUnindexableExtras,
+ @JsonProperty("unindexableExtrasField") @Nullable String unindexableExtrasField,
+ @JsonProperty("unindexableFieldSuffix") @Nullable String unindexableFieldSuffix,
+ @JsonProperty("fieldPathsToDrop") @Nullable Set<String> fieldPathsToDrop,
+ @JsonProperty("mergedTextIndexField") @Nullable String mergedTextIndexField,
+ @JsonProperty("mergedTextIndexTokenMaxLength") @Nullable Integer mergedTextIndexTokenMaxLength,
+ @JsonProperty("mergedTextIndexShinglingOverlapLength") @Nullable Integer mergedTextIndexShinglingOverlapLength,
+ @JsonProperty("mergedTextIndexBinaryTokenDetectionMinLength")
+ @Nullable Integer mergedTextIndexBinaryTokenDetectionMinLength,
+ @JsonProperty("mergedTextIndexPathToExclude") @Nullable Set<String> mergedTextIndexPathToExclude,
+ @JsonProperty("fieldsToDoubleIngest") @Nullable Set<String> fieldsToDoubleIngest
+ ) {
+ setEnableIndexableExtras(enableIndexableExtras);
+ setIndexableExtrasField(indexableExtrasField);
+ setEnableUnindexableExtras(enableUnindexableExtras);
+ setUnindexableExtrasField(unindexableExtrasField);
+ setUnindexableFieldSuffix(unindexableFieldSuffix);
+ setFieldPathsToDrop(fieldPathsToDrop);
+
+ setMergedTextIndexField(mergedTextIndexField);
+ setMergedTextIndexTokenMaxLength(mergedTextIndexTokenMaxLength);
+ setMergedTextIndexShinglingTokenOverlapLength(mergedTextIndexShinglingOverlapLength);
+ setMergedTextIndexBinaryTokenDetectionMinLength(mergedTextIndexBinaryTokenDetectionMinLength);
+ setMergedTextIndexPathToExclude(mergedTextIndexPathToExclude);
+ setFieldsToDoubleIngest(fieldsToDoubleIngest);
+ }
+
+ public SchemaConformingTransformerV2Config setEnableIndexableExtras(Boolean enableIndexableExtras) {
+ _enableIndexableExtras = enableIndexableExtras == null ? _enableUnindexableExtras : enableIndexableExtras;
+ return this;
+ }
+
+ public String getIndexableExtrasField() {
+ return _enableIndexableExtras ? _indexableExtrasField : null;
+ }
+
+ public SchemaConformingTransformerV2Config setIndexableExtrasField(String indexableExtrasField) {
+ _indexableExtrasField = (null == indexableExtrasField) ? _indexableExtrasField : indexableExtrasField;
+ return this;
+ }
+
+ public SchemaConformingTransformerV2Config setEnableUnindexableExtras(Boolean enableUnindexableExtras) {
+ _enableUnindexableExtras = enableUnindexableExtras == null ? _enableUnindexableExtras : enableUnindexableExtras;
+ return this;
+ }
+
+ public String getUnindexableExtrasField() {
+ return _enableUnindexableExtras ? _unindexableExtrasField : null;
+ }
+
+ public SchemaConformingTransformerV2Config setUnindexableExtrasField(String unindexableExtrasField) {
+ _unindexableExtrasField = (null == unindexableExtrasField) ? _unindexableExtrasField : unindexableExtrasField;
+ return this;
+ }
+
+ public String getUnindexableFieldSuffix() {
+ return _unindexableFieldSuffix;
+ }
+
+ public SchemaConformingTransformerV2Config setUnindexableFieldSuffix(String unindexableFieldSuffix) {
+ _unindexableFieldSuffix = (null == unindexableFieldSuffix) ? _unindexableFieldSuffix : unindexableFieldSuffix;
+ return this;
+ }
+
+ public Set<String> getFieldPathsToDrop() {
+ return _fieldPathsToDrop;
+ }
+
+ public SchemaConformingTransformerV2Config setFieldPathsToDrop(Set<String> fieldPathsToDrop) {
+ _fieldPathsToDrop = (null == fieldPathsToDrop) ? _fieldPathsToDrop : fieldPathsToDrop;
+ return this;
+ }
+
+ public Map<String, String> getColumnNameToJsonKeyPathMap() {
+ return _columnNameToJsonKeyPathMap;
+ }
+
+ public SchemaConformingTransformerV2Config setColumnNameToJsonKeyPathMap(
+ Map<String, String> columnNameToJsonKeyPathMap) {
+ _columnNameToJsonKeyPathMap = (null == columnNameToJsonKeyPathMap)
+ ? _columnNameToJsonKeyPathMap : columnNameToJsonKeyPathMap;
+ return this;
+ }
+
+ public String getMergedTextIndexField() {
+ return _mergedTextIndexField;
+ }
+
+ public SchemaConformingTransformerV2Config setMergedTextIndexField(String mergedTextIndexField) {
+ _mergedTextIndexField = (null == mergedTextIndexField) ? _mergedTextIndexField : mergedTextIndexField;
+ return this;
+ }
+
+ public Integer getMergedTextIndexTokenMaxLength() {
+ return _mergedTextIndexTokenMaxLength;
+ }
+
+ public SchemaConformingTransformerV2Config setMergedTextIndexTokenMaxLength(
+ Integer mergedTextIndexTokenMaxLength
+ ) {
+ _mergedTextIndexTokenMaxLength = (null == mergedTextIndexTokenMaxLength)
+ ? _mergedTextIndexTokenMaxLength : mergedTextIndexTokenMaxLength;
+ return this;
+ }
+
+ public Integer getMergedTextIndexShinglingOverlapLength() {
+ return _mergedTextIndexShinglingOverlapLength;
+ }
+
+ public SchemaConformingTransformerV2Config setMergedTextIndexShinglingTokenOverlapLength(
+ Integer mergedTextIndexShinglingOverlapLength) {
+ _mergedTextIndexShinglingOverlapLength = mergedTextIndexShinglingOverlapLength;
Review Comment:
Can you double check what is the side-effect of passing a `null` Integer object and whether we need to check for null value?
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
Review Comment:
Perhaps rephrase the first sentence to improve readability. "... the record accordingly to build the output record." part is a bit confusing.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
Review Comment:
Consistent ternary operator formatting
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
Review Comment:
value not instance of `Map` does not always correspond to `leaf node`. It could be an array, or array containing maps. Either define what a "leaf node" refers to or mention something about array
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
+ if (!isIndexable) {
+ extraFieldsContainer.addUnindexableEntry(key, value);
+ } else {
+ if (null != currentNode && currentNode.isColumn()) {
+ // In schema
+ outputRecord.putValue(currentNode.getColumnName(), currentNode.getValue(value));
+ if (_transformerConfig.getFieldsToDoubleIngest().contains(keyJsonPath)) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ }
+ mergedTextIndexMap.put(keyJsonPath, value);
+ } else {
+ // Out of schema
+ if (storeIndexableExtras) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ mergedTextIndexMap.put(keyJsonPath, value);
+ }
+ }
+ }
+ return extraFieldsContainer;
+ }
+ // Traverse the subtree
+ Map<String, Object> valueAsMap = (Map<String, Object>) value;
+ for (Map.Entry<String, Object> entry : valueAsMap.entrySet()) {
+ jsonPath.addLast(entry.getKey());
+ ExtraFieldsContainer childContainer =
+ processField(currentNode, jsonPath, entry.getValue(), isIndexable, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(key, childContainer);
+ jsonPath.removeLast();
+ }
+ return extraFieldsContainer;
+ }
+
+ /**
+ * Generate an index token based on the provided key-value pair.
+ * The index token follows this format: "val:key".
+ * @param kv used to generate text index tokens
+ * @param indexTokens a list to store the generated index tokens
+ * @param mergedTextIndexTokenMaxLength which we enforce via truncation during token generation
+ */
+ public void generateTextIndexToken(Map.Entry<String, Object> kv, List<String> indexTokens,
+ Integer mergedTextIndexTokenMaxLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+
+ if (key.length() + 1 > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.error("The provided key's length is too long, text index token cannot be truncated");
+ return;
+ }
+
+ // Truncate the value to ensure the generated index token is less or equal to mergedTextIndexTokenMaxLength
+ // The value length should be the mergedTextIndexTokenMaxLength minus ":" character (length 1) minus key length
+ int valueTruncationLength = mergedTextIndexTokenMaxLength - 1 - key.length();
+ if (val.length() > valueTruncationLength) {
+ _realtimeMergedTextIndexTruncatedTokenSizeMeter = _serverMetrics
+ .addMeteredTableValue(_tableName, ServerMeter.REALTIME_MERGED_TEXT_IDX_TRUNCATED_TOKEN_SIZE,
+ key.length() + 1 + val.length(), _realtimeMergedTextIndexTruncatedTokenSizeMeter);
+ val = val.substring(0, valueTruncationLength);
+ }
+
+ _mergedTextIndexTokenBytesCount += key.length() + 1 + val.length();
+ _mergedTextIndexTokenCount += 1;
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+
+ indexTokens.add(val + ":" + key);
+ }
+
+ /**
+ * Implement shingling for the merged text index based on the provided key-value pair.
+ * Each shingled index token retains the format of a standard index token: "val:key". However, "val" now denotes a
+ * sliding window of characters on the value. The total length of each shingled index token
+ * (key length + shingled value length + 1)must be less than or equal to shingleIndexMaxLength. The starting index
+ * of the sliding window for the value is increased by shinglingOverlapLength for every new shingled token.
+ * All shingle index tokens, except for the last one, should have the maximum possible length. If the minimum token
+ * length (shingling overlap length + key length + 1) exceeds the maximum Lucene token size
+ * (MAXIMUM_LUCENE_TOKEN_SIZE), shingling is disabled, and the value is truncated to match the maximum Lucene token
+ * size. If shingleIndexMaxLength is lower than the required minimum token length and also lower than the maximum
+ * Lucene token size, shingleIndexMaxLength is adjusted to match the maximum Lucene token size.
+ *
+ * Note that the most important parameter, the shingleIndexOverlapLength, is the maximum search length that will yield
+ * results with 100% accuracy.
+ *
+ * Example: key-> "key", value-> "0123456789ABCDEF", max length: 10, shingling overlap length: 3
+ * Generated tokens:
+ * 012345:key
+ * 345678:key
+ * 6789AB:key
+ * 9ABCDE:key
+ * CDEF:key
+ * Any query with a length of 7 will yield no results, such as "0123456" or "6789ABC".
+ * Any query with a length of 3 will yield results with 100% accuracy (i.e. is always guaranteed to be searchable).
+ * Any query with a length between 4 and 6 (inclusive) has indeterminate accuracy.
+ * E.g. for queries with length 5, "12345", "789AB" will hit, while "23456" will miss.
+ *
+ * @param kv used to generate shingle text index tokens
+ * @param shingleIndexTokens a list to store the generated shingle index tokens
+ * @param shingleIndexMaxLength the maximum length of each shingle index token. Needs to be greater than the
+ * length of the key and shingleIndexOverlapLength + 1, and must be lower or equal
+ * to MAXIMUM_LUCENE_TOKEN_SIZE.
+ * @param shingleIndexOverlapLength the number of characters in the kv-pair's value shared by two adjacent shingle
+ * index tokens. If null, the overlap length will be defaulted to half of the max
+ * token length.
+ */
+ public void generateShingleTextIndexToken(Map.Entry<String, Object> kv, List<String> shingleIndexTokens,
+ int shingleIndexMaxLength, int shingleIndexOverlapLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+ final int valLength = val.length();
+ final int tokenSuffixLength = key.length() + 1;
+ final int minTokenLength = tokenSuffixLength + shingleIndexOverlapLength + 1;
+
+ if (shingleIndexOverlapLength >= valLength) {
+ if (_logger.isDebugEnabled()) {
+ _logger.warn("The shingleIndexOverlapLength " + shingleIndexOverlapLength + " is longer than the value length "
+ + valLength + ". Shingling will not be applied since only one token will be generated.");
+ }
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ if (minTokenLength > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.debug("The minimum token length " + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + ") exceeds "
+ + "the limit of maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ". Value will be truncated and "
+ + "shingling will not be applied.");
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ // This logging becomes expensive if user accidentally sets a very low shingleIndexMaxLength
+ if (shingleIndexMaxLength < minTokenLength) {
+ _logger.debug("The shingleIndexMaxLength " + shingleIndexMaxLength + " is smaller than the minimum token length "
+ + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + "). Increasing the shingleIndexMaxLength to "
+ + "maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ".");
+ shingleIndexMaxLength = MAXIMUM_LUCENE_TOKEN_SIZE;
+ }
+
+ // Shingle window slide length is the index position on the value which we shall advance on every iteration.
+ // We ensure shingleIndexMaxLength >= minTokenLength so that shingleWindowSlideLength >= 1.
+ int shingleWindowSlideLength = shingleIndexMaxLength - shingleIndexOverlapLength - tokenSuffixLength;
+
+ // Generate shingle index tokens
+ // When starting_idx + shingleIndexOverlapLength >= valLength, there are no new characters to capture, then we stop
+ // the shingle token generation loop.
+ // We ensure that shingleIndexOverlapLength < valLength so that this loop will be entered at lease once.
+ for (int i = 0; i + shingleIndexOverlapLength < valLength; i += shingleWindowSlideLength) {
+ String tokenValStr = val.substring(i, Math.min(i + shingleIndexMaxLength - tokenSuffixLength, valLength));
+ String shingleIndexToken = tokenValStr + ":" + key;
+ shingleIndexTokens.add(shingleIndexToken);
+ _mergedTextIndexTokenBytesCount += shingleIndexToken.length();
+ ++_mergedTextIndexTokenCount;
+ }
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+ }
+
+ /**
+ * Converts (if necessary) and adds the given extras field to the output record
+ */
+ private void putExtrasField(String fieldName, DataType fieldType, Map<String, Object> field,
+ GenericRow outputRecord) {
+ if (null == field) {
+ return;
+ }
+
+ switch (fieldType) {
+ case JSON:
+ outputRecord.putValue(fieldName, field);
+ break;
+ case STRING:
+ try {
+ outputRecord.putValue(fieldName, JsonUtils.objectToString(field));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to convert '" + fieldName + "' to string", e);
+ }
+ break;
+ default:
+ throw new UnsupportedOperationException("Cannot convert '" + fieldName + "' to " + fieldType.name());
+ }
+ }
+
+ private List<String> getLuceneTokensFromMergedTextIndexMap(Map<String, Object> mergedTextIndexMap) {
Review Comment:
Again, perhaps change the terminology from `tokens` to `terms`
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
+ if (!isIndexable) {
+ extraFieldsContainer.addUnindexableEntry(key, value);
+ } else {
+ if (null != currentNode && currentNode.isColumn()) {
+ // In schema
+ outputRecord.putValue(currentNode.getColumnName(), currentNode.getValue(value));
+ if (_transformerConfig.getFieldsToDoubleIngest().contains(keyJsonPath)) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ }
+ mergedTextIndexMap.put(keyJsonPath, value);
+ } else {
+ // Out of schema
+ if (storeIndexableExtras) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ mergedTextIndexMap.put(keyJsonPath, value);
+ }
+ }
+ }
+ return extraFieldsContainer;
+ }
+ // Traverse the subtree
+ Map<String, Object> valueAsMap = (Map<String, Object>) value;
+ for (Map.Entry<String, Object> entry : valueAsMap.entrySet()) {
+ jsonPath.addLast(entry.getKey());
+ ExtraFieldsContainer childContainer =
+ processField(currentNode, jsonPath, entry.getValue(), isIndexable, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(key, childContainer);
+ jsonPath.removeLast();
+ }
+ return extraFieldsContainer;
+ }
+
+ /**
+ * Generate an index token based on the provided key-value pair.
+ * The index token follows this format: "val:key".
+ * @param kv used to generate text index tokens
+ * @param indexTokens a list to store the generated index tokens
+ * @param mergedTextIndexTokenMaxLength which we enforce via truncation during token generation
+ */
+ public void generateTextIndexToken(Map.Entry<String, Object> kv, List<String> indexTokens,
+ Integer mergedTextIndexTokenMaxLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+
+ if (key.length() + 1 > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.error("The provided key's length is too long, text index token cannot be truncated");
+ return;
+ }
+
+ // Truncate the value to ensure the generated index token is less or equal to mergedTextIndexTokenMaxLength
+ // The value length should be the mergedTextIndexTokenMaxLength minus ":" character (length 1) minus key length
+ int valueTruncationLength = mergedTextIndexTokenMaxLength - 1 - key.length();
+ if (val.length() > valueTruncationLength) {
+ _realtimeMergedTextIndexTruncatedTokenSizeMeter = _serverMetrics
+ .addMeteredTableValue(_tableName, ServerMeter.REALTIME_MERGED_TEXT_IDX_TRUNCATED_TOKEN_SIZE,
+ key.length() + 1 + val.length(), _realtimeMergedTextIndexTruncatedTokenSizeMeter);
+ val = val.substring(0, valueTruncationLength);
+ }
+
+ _mergedTextIndexTokenBytesCount += key.length() + 1 + val.length();
+ _mergedTextIndexTokenCount += 1;
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+
+ indexTokens.add(val + ":" + key);
+ }
+
+ /**
+ * Implement shingling for the merged text index based on the provided key-value pair.
+ * Each shingled index token retains the format of a standard index token: "val:key". However, "val" now denotes a
+ * sliding window of characters on the value. The total length of each shingled index token
+ * (key length + shingled value length + 1)must be less than or equal to shingleIndexMaxLength. The starting index
+ * of the sliding window for the value is increased by shinglingOverlapLength for every new shingled token.
+ * All shingle index tokens, except for the last one, should have the maximum possible length. If the minimum token
+ * length (shingling overlap length + key length + 1) exceeds the maximum Lucene token size
+ * (MAXIMUM_LUCENE_TOKEN_SIZE), shingling is disabled, and the value is truncated to match the maximum Lucene token
+ * size. If shingleIndexMaxLength is lower than the required minimum token length and also lower than the maximum
+ * Lucene token size, shingleIndexMaxLength is adjusted to match the maximum Lucene token size.
+ *
+ * Note that the most important parameter, the shingleIndexOverlapLength, is the maximum search length that will yield
+ * results with 100% accuracy.
+ *
+ * Example: key-> "key", value-> "0123456789ABCDEF", max length: 10, shingling overlap length: 3
+ * Generated tokens:
+ * 012345:key
+ * 345678:key
+ * 6789AB:key
+ * 9ABCDE:key
+ * CDEF:key
+ * Any query with a length of 7 will yield no results, such as "0123456" or "6789ABC".
+ * Any query with a length of 3 will yield results with 100% accuracy (i.e. is always guaranteed to be searchable).
+ * Any query with a length between 4 and 6 (inclusive) has indeterminate accuracy.
+ * E.g. for queries with length 5, "12345", "789AB" will hit, while "23456" will miss.
+ *
+ * @param kv used to generate shingle text index tokens
+ * @param shingleIndexTokens a list to store the generated shingle index tokens
+ * @param shingleIndexMaxLength the maximum length of each shingle index token. Needs to be greater than the
+ * length of the key and shingleIndexOverlapLength + 1, and must be lower or equal
+ * to MAXIMUM_LUCENE_TOKEN_SIZE.
+ * @param shingleIndexOverlapLength the number of characters in the kv-pair's value shared by two adjacent shingle
+ * index tokens. If null, the overlap length will be defaulted to half of the max
+ * token length.
+ */
+ public void generateShingleTextIndexToken(Map.Entry<String, Object> kv, List<String> shingleIndexTokens,
+ int shingleIndexMaxLength, int shingleIndexOverlapLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+ final int valLength = val.length();
+ final int tokenSuffixLength = key.length() + 1;
+ final int minTokenLength = tokenSuffixLength + shingleIndexOverlapLength + 1;
+
+ if (shingleIndexOverlapLength >= valLength) {
+ if (_logger.isDebugEnabled()) {
+ _logger.warn("The shingleIndexOverlapLength " + shingleIndexOverlapLength + " is longer than the value length "
+ + valLength + ". Shingling will not be applied since only one token will be generated.");
+ }
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ if (minTokenLength > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.debug("The minimum token length " + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + ") exceeds "
+ + "the limit of maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ". Value will be truncated and "
+ + "shingling will not be applied.");
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ // This logging becomes expensive if user accidentally sets a very low shingleIndexMaxLength
+ if (shingleIndexMaxLength < minTokenLength) {
+ _logger.debug("The shingleIndexMaxLength " + shingleIndexMaxLength + " is smaller than the minimum token length "
+ + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + "). Increasing the shingleIndexMaxLength to "
+ + "maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ".");
+ shingleIndexMaxLength = MAXIMUM_LUCENE_TOKEN_SIZE;
+ }
+
+ // Shingle window slide length is the index position on the value which we shall advance on every iteration.
+ // We ensure shingleIndexMaxLength >= minTokenLength so that shingleWindowSlideLength >= 1.
+ int shingleWindowSlideLength = shingleIndexMaxLength - shingleIndexOverlapLength - tokenSuffixLength;
+
+ // Generate shingle index tokens
+ // When starting_idx + shingleIndexOverlapLength >= valLength, there are no new characters to capture, then we stop
+ // the shingle token generation loop.
+ // We ensure that shingleIndexOverlapLength < valLength so that this loop will be entered at lease once.
+ for (int i = 0; i + shingleIndexOverlapLength < valLength; i += shingleWindowSlideLength) {
+ String tokenValStr = val.substring(i, Math.min(i + shingleIndexMaxLength - tokenSuffixLength, valLength));
+ String shingleIndexToken = tokenValStr + ":" + key;
+ shingleIndexTokens.add(shingleIndexToken);
+ _mergedTextIndexTokenBytesCount += shingleIndexToken.length();
+ ++_mergedTextIndexTokenCount;
+ }
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+ }
+
+ /**
+ * Converts (if necessary) and adds the given extras field to the output record
+ */
+ private void putExtrasField(String fieldName, DataType fieldType, Map<String, Object> field,
+ GenericRow outputRecord) {
+ if (null == field) {
+ return;
+ }
+
+ switch (fieldType) {
+ case JSON:
+ outputRecord.putValue(fieldName, field);
+ break;
+ case STRING:
+ try {
+ outputRecord.putValue(fieldName, JsonUtils.objectToString(field));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to convert '" + fieldName + "' to string", e);
+ }
+ break;
+ default:
+ throw new UnsupportedOperationException("Cannot convert '" + fieldName + "' to " + fieldType.name());
+ }
+ }
+
+ private List<String> getLuceneTokensFromMergedTextIndexMap(Map<String, Object> mergedTextIndexMap) {
+ final Integer mergedTextIndexTokenMaxLength = _transformerConfig.getMergedTextIndexTokenMaxLength();
+ final @Nullable
+ Integer mergedTextIndexShinglingOverlapLength = _transformerConfig.getMergedTextIndexShinglingOverlapLength();
+ List<String> luceneTokens = new ArrayList<>();
+ mergedTextIndexMap.entrySet().stream().filter(kv -> null != kv.getKey() && null != kv.getValue())
+ .filter(kv -> !_transformerConfig.getMergedTextIndexPathToExclude().contains(kv.getKey())).filter(
+ kv -> !base64ValueFilter(kv.getValue().toString().getBytes(),
+ _transformerConfig.getMergedTextIndexBinaryTokenDetectionMinLength())).filter(
+ kv -> _transformerConfig.getMergedTextIndexSuffixToExclude().stream()
+ .anyMatch(suffix -> !kv.getKey().endsWith(suffix))).forEach(kv -> {
+ if (null == mergedTextIndexShinglingOverlapLength) {
+ generateTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength);
+ } else {
+ generateShingleTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength,
+ mergedTextIndexShinglingOverlapLength);
+ }
+ });
+ return luceneTokens;
+ }
+}
+
+/**
+ * SchemaTreeNode represents the tree node when we construct the schema tree. The node could be either leaf node or
+ * non-leaf node. Both types of node could hold the volumn as a column in the schema.
+ * For example, the schema with columns a, b, c, d.e, d.f, x.y, x.y.z, x.y.w will have the following tree structure:
+ * root -- a*
+ * -- b*
+ * -- c*
+ * -- d -- e*
+ * -- f*
+ * -- x* -- y* -- z*
+ * -- w*
+ * where node with "*" could represent a valid column in the schema.
+ */
+class SchemaTreeNode {
+ private boolean _isColumn;
Review Comment:
Nit: should probably be consistent and use either `field` or `column`.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
Review Comment:
Can we use Lucene's terminology? i.e. use `document` rather than `token`. Perhaps refactor the code in all the places that have this behavior.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
Review Comment:
1. "column" -> "name of the column"?
2. to be precise, value is not always leaf node, i.e. when the node contains an array
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
Review Comment:
ternary operator formatting consistency
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
Review Comment:
Perhaps mention how arrays are processed
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
+ if (!isIndexable) {
+ extraFieldsContainer.addUnindexableEntry(key, value);
+ } else {
+ if (null != currentNode && currentNode.isColumn()) {
+ // In schema
+ outputRecord.putValue(currentNode.getColumnName(), currentNode.getValue(value));
+ if (_transformerConfig.getFieldsToDoubleIngest().contains(keyJsonPath)) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ }
+ mergedTextIndexMap.put(keyJsonPath, value);
+ } else {
+ // Out of schema
+ if (storeIndexableExtras) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ mergedTextIndexMap.put(keyJsonPath, value);
+ }
+ }
+ }
+ return extraFieldsContainer;
+ }
+ // Traverse the subtree
+ Map<String, Object> valueAsMap = (Map<String, Object>) value;
+ for (Map.Entry<String, Object> entry : valueAsMap.entrySet()) {
+ jsonPath.addLast(entry.getKey());
+ ExtraFieldsContainer childContainer =
+ processField(currentNode, jsonPath, entry.getValue(), isIndexable, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(key, childContainer);
+ jsonPath.removeLast();
+ }
+ return extraFieldsContainer;
+ }
+
+ /**
+ * Generate an index token based on the provided key-value pair.
+ * The index token follows this format: "val:key".
+ * @param kv used to generate text index tokens
+ * @param indexTokens a list to store the generated index tokens
+ * @param mergedTextIndexTokenMaxLength which we enforce via truncation during token generation
+ */
+ public void generateTextIndexToken(Map.Entry<String, Object> kv, List<String> indexTokens,
+ Integer mergedTextIndexTokenMaxLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+
+ if (key.length() + 1 > MAXIMUM_LUCENE_TOKEN_SIZE) {
Review Comment:
To be precise, "LUCENE TOKEN SIZE" is number of bytes and there could be UTF8 variable length characters. So `key.length() + 1`, which refers to # of characters, could overflow and cause indexing issues. If we want to make this check perfect, it's probably a good idea to encode the string first.
Note that his is a minor issue and to fix it properly, it requires changes in many places within this transformer.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
+ if (!isIndexable) {
+ extraFieldsContainer.addUnindexableEntry(key, value);
+ } else {
+ if (null != currentNode && currentNode.isColumn()) {
+ // In schema
+ outputRecord.putValue(currentNode.getColumnName(), currentNode.getValue(value));
+ if (_transformerConfig.getFieldsToDoubleIngest().contains(keyJsonPath)) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ }
+ mergedTextIndexMap.put(keyJsonPath, value);
+ } else {
+ // Out of schema
+ if (storeIndexableExtras) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ mergedTextIndexMap.put(keyJsonPath, value);
+ }
+ }
+ }
+ return extraFieldsContainer;
+ }
+ // Traverse the subtree
+ Map<String, Object> valueAsMap = (Map<String, Object>) value;
+ for (Map.Entry<String, Object> entry : valueAsMap.entrySet()) {
+ jsonPath.addLast(entry.getKey());
+ ExtraFieldsContainer childContainer =
+ processField(currentNode, jsonPath, entry.getValue(), isIndexable, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(key, childContainer);
+ jsonPath.removeLast();
+ }
+ return extraFieldsContainer;
+ }
+
+ /**
+ * Generate an index token based on the provided key-value pair.
+ * The index token follows this format: "val:key".
+ * @param kv used to generate text index tokens
+ * @param indexTokens a list to store the generated index tokens
+ * @param mergedTextIndexTokenMaxLength which we enforce via truncation during token generation
+ */
+ public void generateTextIndexToken(Map.Entry<String, Object> kv, List<String> indexTokens,
+ Integer mergedTextIndexTokenMaxLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+
+ if (key.length() + 1 > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.error("The provided key's length is too long, text index token cannot be truncated");
+ return;
+ }
+
+ // Truncate the value to ensure the generated index token is less or equal to mergedTextIndexTokenMaxLength
+ // The value length should be the mergedTextIndexTokenMaxLength minus ":" character (length 1) minus key length
+ int valueTruncationLength = mergedTextIndexTokenMaxLength - 1 - key.length();
+ if (val.length() > valueTruncationLength) {
+ _realtimeMergedTextIndexTruncatedTokenSizeMeter = _serverMetrics
+ .addMeteredTableValue(_tableName, ServerMeter.REALTIME_MERGED_TEXT_IDX_TRUNCATED_TOKEN_SIZE,
+ key.length() + 1 + val.length(), _realtimeMergedTextIndexTruncatedTokenSizeMeter);
+ val = val.substring(0, valueTruncationLength);
+ }
+
+ _mergedTextIndexTokenBytesCount += key.length() + 1 + val.length();
+ _mergedTextIndexTokenCount += 1;
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+
+ indexTokens.add(val + ":" + key);
+ }
+
+ /**
+ * Implement shingling for the merged text index based on the provided key-value pair.
+ * Each shingled index token retains the format of a standard index token: "val:key". However, "val" now denotes a
+ * sliding window of characters on the value. The total length of each shingled index token
+ * (key length + shingled value length + 1)must be less than or equal to shingleIndexMaxLength. The starting index
+ * of the sliding window for the value is increased by shinglingOverlapLength for every new shingled token.
+ * All shingle index tokens, except for the last one, should have the maximum possible length. If the minimum token
+ * length (shingling overlap length + key length + 1) exceeds the maximum Lucene token size
+ * (MAXIMUM_LUCENE_TOKEN_SIZE), shingling is disabled, and the value is truncated to match the maximum Lucene token
+ * size. If shingleIndexMaxLength is lower than the required minimum token length and also lower than the maximum
+ * Lucene token size, shingleIndexMaxLength is adjusted to match the maximum Lucene token size.
+ *
+ * Note that the most important parameter, the shingleIndexOverlapLength, is the maximum search length that will yield
+ * results with 100% accuracy.
+ *
+ * Example: key-> "key", value-> "0123456789ABCDEF", max length: 10, shingling overlap length: 3
+ * Generated tokens:
+ * 012345:key
+ * 345678:key
+ * 6789AB:key
+ * 9ABCDE:key
+ * CDEF:key
+ * Any query with a length of 7 will yield no results, such as "0123456" or "6789ABC".
+ * Any query with a length of 3 will yield results with 100% accuracy (i.e. is always guaranteed to be searchable).
+ * Any query with a length between 4 and 6 (inclusive) has indeterminate accuracy.
+ * E.g. for queries with length 5, "12345", "789AB" will hit, while "23456" will miss.
+ *
+ * @param kv used to generate shingle text index tokens
+ * @param shingleIndexTokens a list to store the generated shingle index tokens
+ * @param shingleIndexMaxLength the maximum length of each shingle index token. Needs to be greater than the
+ * length of the key and shingleIndexOverlapLength + 1, and must be lower or equal
+ * to MAXIMUM_LUCENE_TOKEN_SIZE.
+ * @param shingleIndexOverlapLength the number of characters in the kv-pair's value shared by two adjacent shingle
+ * index tokens. If null, the overlap length will be defaulted to half of the max
+ * token length.
+ */
+ public void generateShingleTextIndexToken(Map.Entry<String, Object> kv, List<String> shingleIndexTokens,
+ int shingleIndexMaxLength, int shingleIndexOverlapLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+ final int valLength = val.length();
+ final int tokenSuffixLength = key.length() + 1;
+ final int minTokenLength = tokenSuffixLength + shingleIndexOverlapLength + 1;
+
+ if (shingleIndexOverlapLength >= valLength) {
+ if (_logger.isDebugEnabled()) {
+ _logger.warn("The shingleIndexOverlapLength " + shingleIndexOverlapLength + " is longer than the value length "
+ + valLength + ". Shingling will not be applied since only one token will be generated.");
+ }
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ if (minTokenLength > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.debug("The minimum token length " + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + ") exceeds "
+ + "the limit of maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ". Value will be truncated and "
+ + "shingling will not be applied.");
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ // This logging becomes expensive if user accidentally sets a very low shingleIndexMaxLength
+ if (shingleIndexMaxLength < minTokenLength) {
+ _logger.debug("The shingleIndexMaxLength " + shingleIndexMaxLength + " is smaller than the minimum token length "
+ + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + "). Increasing the shingleIndexMaxLength to "
+ + "maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ".");
+ shingleIndexMaxLength = MAXIMUM_LUCENE_TOKEN_SIZE;
+ }
+
+ // Shingle window slide length is the index position on the value which we shall advance on every iteration.
+ // We ensure shingleIndexMaxLength >= minTokenLength so that shingleWindowSlideLength >= 1.
+ int shingleWindowSlideLength = shingleIndexMaxLength - shingleIndexOverlapLength - tokenSuffixLength;
+
+ // Generate shingle index tokens
+ // When starting_idx + shingleIndexOverlapLength >= valLength, there are no new characters to capture, then we stop
+ // the shingle token generation loop.
+ // We ensure that shingleIndexOverlapLength < valLength so that this loop will be entered at lease once.
+ for (int i = 0; i + shingleIndexOverlapLength < valLength; i += shingleWindowSlideLength) {
+ String tokenValStr = val.substring(i, Math.min(i + shingleIndexMaxLength - tokenSuffixLength, valLength));
+ String shingleIndexToken = tokenValStr + ":" + key;
+ shingleIndexTokens.add(shingleIndexToken);
+ _mergedTextIndexTokenBytesCount += shingleIndexToken.length();
+ ++_mergedTextIndexTokenCount;
+ }
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+ }
+
+ /**
+ * Converts (if necessary) and adds the given extras field to the output record
+ */
+ private void putExtrasField(String fieldName, DataType fieldType, Map<String, Object> field,
+ GenericRow outputRecord) {
+ if (null == field) {
+ return;
+ }
+
+ switch (fieldType) {
+ case JSON:
+ outputRecord.putValue(fieldName, field);
+ break;
+ case STRING:
+ try {
+ outputRecord.putValue(fieldName, JsonUtils.objectToString(field));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to convert '" + fieldName + "' to string", e);
+ }
+ break;
+ default:
+ throw new UnsupportedOperationException("Cannot convert '" + fieldName + "' to " + fieldType.name());
+ }
+ }
+
+ private List<String> getLuceneTokensFromMergedTextIndexMap(Map<String, Object> mergedTextIndexMap) {
+ final Integer mergedTextIndexTokenMaxLength = _transformerConfig.getMergedTextIndexTokenMaxLength();
+ final @Nullable
+ Integer mergedTextIndexShinglingOverlapLength = _transformerConfig.getMergedTextIndexShinglingOverlapLength();
+ List<String> luceneTokens = new ArrayList<>();
+ mergedTextIndexMap.entrySet().stream().filter(kv -> null != kv.getKey() && null != kv.getValue())
+ .filter(kv -> !_transformerConfig.getMergedTextIndexPathToExclude().contains(kv.getKey())).filter(
+ kv -> !base64ValueFilter(kv.getValue().toString().getBytes(),
+ _transformerConfig.getMergedTextIndexBinaryTokenDetectionMinLength())).filter(
+ kv -> _transformerConfig.getMergedTextIndexSuffixToExclude().stream()
+ .anyMatch(suffix -> !kv.getKey().endsWith(suffix))).forEach(kv -> {
+ if (null == mergedTextIndexShinglingOverlapLength) {
+ generateTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength);
+ } else {
+ generateShingleTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength,
+ mergedTextIndexShinglingOverlapLength);
+ }
+ });
+ return luceneTokens;
+ }
+}
+
+/**
+ * SchemaTreeNode represents the tree node when we construct the schema tree. The node could be either leaf node or
+ * non-leaf node. Both types of node could hold the volumn as a column in the schema.
+ * For example, the schema with columns a, b, c, d.e, d.f, x.y, x.y.z, x.y.w will have the following tree structure:
+ * root -- a*
+ * -- b*
+ * -- c*
+ * -- d -- e*
+ * -- f*
+ * -- x* -- y* -- z*
+ * -- w*
+ * where node with "*" could represent a valid column in the schema.
+ */
+class SchemaTreeNode {
+ private boolean _isColumn;
+ private Map<String, SchemaTreeNode> _children;
+ // Taking the example of key "x.y.z", the keyName will be "z" and the parentPath will be "x.y"
+ // Root node would have keyName as "" and parentPath as null
+ // Root node's children will have keyName as the first level key and parentPath as ""
+ @Nonnull
+ private String _keyName;
+ @Nullable
+ private String _columnName;
+ @Nullable
+ private String _parentPath;
+ private FieldSpec _fieldSpec;
+
+ public SchemaTreeNode(String keyName, String parentPath, Schema schema) {
+ _keyName = keyName;
+ _parentPath = parentPath;
+ _fieldSpec = schema.getFieldSpecFor(getJsonKeyPath());
+ _children = new HashMap<>();
+ }
+
+ public boolean isColumn() {
+ return _isColumn;
+ }
+
+ public void setColumn(String columnName) {
+ if (columnName == null) {
+ _columnName = getJsonKeyPath();
+ } else {
+ _columnName = columnName;
+ }
+ _isColumn = true;
+ }
+
+ public boolean hasChild(String key) {
+ return _children.containsKey(key);
+ }
+
+ /**
+ * If does not have the child node, add a child node to the current node and return the child node.
+ * If the child node already exists, return the existing child node.
+ * @param key
+ * @return
+ */
+ public SchemaTreeNode getAndCreateChild(String key, Schema schema) {
+ SchemaTreeNode child = _children.get(key);
+ if (child == null) {
+ child = new SchemaTreeNode(key, getJsonKeyPath(), schema);
+ _children.put(key, child);
+ }
+ return child;
+ }
+
+ public SchemaTreeNode getChild(String key) {
+ return _children.get(key);
+ }
+
+ public String getKeyName() {
+ return _keyName;
+ }
+
+ public String getColumnName() {
+ return _columnName;
+ }
+
+ public Object getValue(Object value) {
+ // If the field is a single value string field, but value is an array of collection, serialize it
Review Comment:
Can we also add some more details regarding the problem of letting downstream `DataTypeTransformer` doing the serialization? Specifically, it treats arrays as multi-variable "column" rather than serializing it to string despite the column type being string typed single-variable column. That is why we want to serialize objects here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1554763002
##########
pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/SchemaConformingTransformerV2Config.java:
##########
@@ -0,0 +1,237 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.config.table.ingestion;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.spi.config.BaseJsonConfig;
+
+public class SchemaConformingTransformerV2Config extends BaseJsonConfig {
+ @JsonPropertyDescription("Enable indexable extras")
+ private boolean _enableIndexableExtras = true;
+
+ @JsonPropertyDescription("Name of the field that should contain extra fields that are not part of the schema.")
+ private String _indexableExtrasField = "json_data";
+
+ @JsonPropertyDescription("Enable unindexable extras")
+ private boolean _enableUnindexableExtras = true;
+
+ @JsonPropertyDescription(
+ "Like indexableExtrasField except it only contains fields with the suffix in unindexableFieldSuffix.")
+ private String _unindexableExtrasField = "json_data_no_idx";
+
+ @JsonPropertyDescription("The suffix of fields that must be stored in unindexableExtrasField")
+ private String _unindexableFieldSuffix = "_noindex";
+
+ @JsonPropertyDescription("Array of flattened (dot-delimited) object paths to drop")
+ private Set<String> _fieldPathsToDrop = new HashSet<>();
+
+ @JsonPropertyDescription("Map from customized meaningful column name to json key path")
+ private Map<String, String> _columnNameToJsonKeyPathMap = new HashMap<>();
+
+ @JsonPropertyDescription("mergedTextIndex field")
+ private String _mergedTextIndexField = "__mergedTextIndex";
+
+ @JsonPropertyDescription("mergedTextIndex token max length")
+ private int _mergedTextIndexTokenMaxLength = 32766;
+
+ @JsonPropertyDescription(
+ "Recall that merged text index token is in the format of <value:key>. "
+ + "The mergedTextIndex shingling overlap length refers to the "
+ + "maximum search length of the value that will yield results with "
+ + "100% accuracy. If the value is null, shingle index will be turned off "
+ + "and the value will be truncated such that the token is equal to "
+ + "_mergedTextIndexTokenMaxLength"
+ )
+ private @Nullable Integer _mergedTextIndexShinglingOverlapLength = null;
+
+ @JsonPropertyDescription("mergedTextIndex binary token detection minimum length")
+ private Integer _mergedTextIndexBinaryTokenDetectionMinLength = 512;
+
+ @JsonPropertyDescription("Array of paths to exclude from merged text index.")
+ private Set<String> _mergedTextIndexPathToExclude = new HashSet<>();
+
+ // TODO: set default value from CLPRewriter once it open sourced
+ @JsonPropertyDescription("Array of suffix to exclude from merged text index.")
+ private List<String> _mergedTextIndexSuffixToExclude = Arrays.asList("_logtype", "_dictionaryVars", "_encodedVars");
+
+ @JsonPropertyDescription("Dedicated fields to double ingest into json_data column")
+ private Set<String> _fieldsToDoubleIngest = new HashSet<>();
+
+ @JsonCreator
+ public SchemaConformingTransformerV2Config(
+ @JsonProperty("enableIndexableExtras") @Nullable Boolean enableIndexableExtras,
+ @JsonProperty("indexableExtrasField") String indexableExtrasField,
+ @JsonProperty("enableUnindexableExtras") @Nullable Boolean enableUnindexableExtras,
+ @JsonProperty("unindexableExtrasField") @Nullable String unindexableExtrasField,
+ @JsonProperty("unindexableFieldSuffix") @Nullable String unindexableFieldSuffix,
+ @JsonProperty("fieldPathsToDrop") @Nullable Set<String> fieldPathsToDrop,
+ @JsonProperty("mergedTextIndexField") @Nullable String mergedTextIndexField,
+ @JsonProperty("mergedTextIndexTokenMaxLength") @Nullable Integer mergedTextIndexTokenMaxLength,
+ @JsonProperty("mergedTextIndexShinglingOverlapLength") @Nullable Integer mergedTextIndexShinglingOverlapLength,
+ @JsonProperty("mergedTextIndexBinaryTokenDetectionMinLength")
+ @Nullable Integer mergedTextIndexBinaryTokenDetectionMinLength,
+ @JsonProperty("mergedTextIndexPathToExclude") @Nullable Set<String> mergedTextIndexPathToExclude,
+ @JsonProperty("fieldsToDoubleIngest") @Nullable Set<String> fieldsToDoubleIngest
+ ) {
+ setEnableIndexableExtras(enableIndexableExtras);
+ setIndexableExtrasField(indexableExtrasField);
+ setEnableUnindexableExtras(enableUnindexableExtras);
+ setUnindexableExtrasField(unindexableExtrasField);
+ setUnindexableFieldSuffix(unindexableFieldSuffix);
+ setFieldPathsToDrop(fieldPathsToDrop);
+
+ setMergedTextIndexField(mergedTextIndexField);
+ setMergedTextIndexTokenMaxLength(mergedTextIndexTokenMaxLength);
+ setMergedTextIndexShinglingTokenOverlapLength(mergedTextIndexShinglingOverlapLength);
+ setMergedTextIndexBinaryTokenDetectionMinLength(mergedTextIndexBinaryTokenDetectionMinLength);
+ setMergedTextIndexPathToExclude(mergedTextIndexPathToExclude);
+ setFieldsToDoubleIngest(fieldsToDoubleIngest);
+ }
+
+ public SchemaConformingTransformerV2Config setEnableIndexableExtras(Boolean enableIndexableExtras) {
+ _enableIndexableExtras = enableIndexableExtras == null ? _enableUnindexableExtras : enableIndexableExtras;
+ return this;
+ }
+
+ public String getIndexableExtrasField() {
+ return _enableIndexableExtras ? _indexableExtrasField : null;
+ }
+
+ public SchemaConformingTransformerV2Config setIndexableExtrasField(String indexableExtrasField) {
+ _indexableExtrasField = (null == indexableExtrasField) ? _indexableExtrasField : indexableExtrasField;
+ return this;
+ }
+
+ public SchemaConformingTransformerV2Config setEnableUnindexableExtras(Boolean enableUnindexableExtras) {
+ _enableUnindexableExtras = enableUnindexableExtras == null ? _enableUnindexableExtras : enableUnindexableExtras;
+ return this;
+ }
+
+ public String getUnindexableExtrasField() {
+ return _enableUnindexableExtras ? _unindexableExtrasField : null;
+ }
+
+ public SchemaConformingTransformerV2Config setUnindexableExtrasField(String unindexableExtrasField) {
+ _unindexableExtrasField = (null == unindexableExtrasField) ? _unindexableExtrasField : unindexableExtrasField;
+ return this;
+ }
+
+ public String getUnindexableFieldSuffix() {
+ return _unindexableFieldSuffix;
+ }
+
+ public SchemaConformingTransformerV2Config setUnindexableFieldSuffix(String unindexableFieldSuffix) {
+ _unindexableFieldSuffix = (null == unindexableFieldSuffix) ? _unindexableFieldSuffix : unindexableFieldSuffix;
+ return this;
+ }
+
+ public Set<String> getFieldPathsToDrop() {
+ return _fieldPathsToDrop;
+ }
+
+ public SchemaConformingTransformerV2Config setFieldPathsToDrop(Set<String> fieldPathsToDrop) {
+ _fieldPathsToDrop = (null == fieldPathsToDrop) ? _fieldPathsToDrop : fieldPathsToDrop;
+ return this;
+ }
+
+ public Map<String, String> getColumnNameToJsonKeyPathMap() {
+ return _columnNameToJsonKeyPathMap;
+ }
+
+ public SchemaConformingTransformerV2Config setColumnNameToJsonKeyPathMap(
+ Map<String, String> columnNameToJsonKeyPathMap) {
+ _columnNameToJsonKeyPathMap = (null == columnNameToJsonKeyPathMap)
+ ? _columnNameToJsonKeyPathMap : columnNameToJsonKeyPathMap;
+ return this;
+ }
+
+ public String getMergedTextIndexField() {
+ return _mergedTextIndexField;
+ }
+
+ public SchemaConformingTransformerV2Config setMergedTextIndexField(String mergedTextIndexField) {
+ _mergedTextIndexField = (null == mergedTextIndexField) ? _mergedTextIndexField : mergedTextIndexField;
+ return this;
+ }
+
+ public Integer getMergedTextIndexTokenMaxLength() {
+ return _mergedTextIndexTokenMaxLength;
+ }
+
+ public SchemaConformingTransformerV2Config setMergedTextIndexTokenMaxLength(
+ Integer mergedTextIndexTokenMaxLength
+ ) {
+ _mergedTextIndexTokenMaxLength = (null == mergedTextIndexTokenMaxLength)
+ ? _mergedTextIndexTokenMaxLength : mergedTextIndexTokenMaxLength;
+ return this;
+ }
+
+ public Integer getMergedTextIndexShinglingOverlapLength() {
+ return _mergedTextIndexShinglingOverlapLength;
+ }
+
+ public SchemaConformingTransformerV2Config setMergedTextIndexShinglingTokenOverlapLength(
+ Integer mergedTextIndexShinglingOverlapLength) {
+ _mergedTextIndexShinglingOverlapLength = mergedTextIndexShinglingOverlapLength;
Review Comment:
We are treating `mergedTextIndexShinglingOverlapLength = null` as a special case in transformer, there should not be side effect as long as we check its null value during usage
`if (null == mergedTextIndexShinglingOverlapLength) {
generateTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength);
} else {
generateShingleTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength,
mergedTextIndexShinglingOverlapLength);
}`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552476272
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
Review Comment:
Thanks for reminding.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "chenboat (via GitHub)" <gi...@apache.org>.
chenboat commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552470210
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/Base64Utils.java:
##########
@@ -0,0 +1,44 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.utils;
+
+import org.apache.commons.codec.binary.Base64;
+
+/**
+ * Simple wrapper class over codec's Base64 implementation to handle Pinot-specific Base64 encoded binary data.
+ */
+public class Base64Utils extends Base64 {
+ public static boolean isBase64IgnoreWhiteSpace(byte[] arrayOctet) {
+ return isBase64(arrayOctet);
+ }
+
+ public static boolean isBase64IgnoreTrailingPeriods(byte[] arrayOctet) {
Review Comment:
Add unit test for this method.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "chenboat (via GitHub)" <gi...@apache.org>.
chenboat commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552462015
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/CompositeTransformer.java:
##########
@@ -78,7 +78,8 @@ public class CompositeTransformer implements RecordTransformer {
*/
public static List<RecordTransformer> getDefaultTransformers(TableConfig tableConfig, Schema schema) {
return Stream.of(new ExpressionTransformer(tableConfig, schema), new FilterTransformer(tableConfig),
- new SchemaConformingTransformer(tableConfig, schema), new DataTypeTransformer(tableConfig, schema),
+ new SchemaConformingTransformer(tableConfig, schema),
+ new SchemaConformingTransformerV2(tableConfig, schema), new DataTypeTransformer(tableConfig, schema),
Review Comment:
update the javadoc for this new transformer too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1554800911
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
Review Comment:
renamed to documents, please check. Plus two configurations names in setting has to be changed, `mergedTextIndexDocumentMaxLength` and `mergedTextIndexBinaryDocumentDetectionMinLength` changed from Token to Document
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "jackluo923 (via GitHub)" <gi...@apache.org>.
jackluo923 commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1556445579
##########
pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/SchemaConformingTransformerV2Config.java:
##########
@@ -0,0 +1,253 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.config.table.ingestion;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.spi.config.BaseJsonConfig;
+
+public class SchemaConformingTransformerV2Config extends BaseJsonConfig {
+ @JsonPropertyDescription("Enable indexable extras")
+ private boolean _enableIndexableExtras = true;
+
+ @JsonPropertyDescription("Name of the field that should contain extra fields that are not part of the schema.")
+ private String _indexableExtrasField = "json_data";
+
+ @JsonPropertyDescription("Enable unindexable extras")
+ private boolean _enableUnindexableExtras = true;
+
+ @JsonPropertyDescription(
+ "Like indexableExtrasField except it only contains fields with the suffix in unindexableFieldSuffix.")
+ private String _unindexableExtrasField = "json_data_no_idx";
+
+ @JsonPropertyDescription("The suffix of fields that must be stored in unindexableExtrasField")
+ private String _unindexableFieldSuffix = "_noindex";
+
+ @JsonPropertyDescription("Array of flattened (dot-delimited) object paths to drop")
+ private Set<String> _fieldPathsToDrop = new HashSet<>();
+
+ @JsonPropertyDescription("Array of flattened (dot-delimited) object paths not to traverse further and keep same as "
+ + "input. This will also skip building mergedTextIndex for the field.")
+ private Set<String> _fieldPathsToPreserveInput = new HashSet<>();
+
+ @JsonPropertyDescription("Map from customized meaningful column name to json key path")
+ private Map<String, String> _columnNameToJsonKeyPathMap = new HashMap<>();
+
+ @JsonPropertyDescription("mergedTextIndex field")
+ private String _mergedTextIndexField = "__mergedTextIndex";
+
+ @JsonPropertyDescription("mergedTextIndex document max length")
+ private int _mergedTextIndexDocumentMaxLength = 32766;
Review Comment:
If we want to be 100% precise, we should change this parameter to `_mergedTextIndexDocumentMaxLength` to `_mergedTextIndexDocumentMaxSize` as 32766 refers to number of bytes rather than number of characters. We also should change the implementation for the check by decoding the string to bytes, etc.
We could simply remove this feature as well because it's not necessary for us because in production, we use a custom analyzer which already enforces this limit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1558107343
##########
pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/SchemaConformingTransformerV2Config.java:
##########
@@ -0,0 +1,253 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.config.table.ingestion;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.spi.config.BaseJsonConfig;
+
+public class SchemaConformingTransformerV2Config extends BaseJsonConfig {
+ @JsonPropertyDescription("Enable indexable extras")
+ private boolean _enableIndexableExtras = true;
+
+ @JsonPropertyDescription("Name of the field that should contain extra fields that are not part of the schema.")
+ private String _indexableExtrasField = "json_data";
+
+ @JsonPropertyDescription("Enable unindexable extras")
+ private boolean _enableUnindexableExtras = true;
+
+ @JsonPropertyDescription(
+ "Like indexableExtrasField except it only contains fields with the suffix in unindexableFieldSuffix.")
+ private String _unindexableExtrasField = "json_data_no_idx";
+
+ @JsonPropertyDescription("The suffix of fields that must be stored in unindexableExtrasField")
+ private String _unindexableFieldSuffix = "_noindex";
+
+ @JsonPropertyDescription("Array of flattened (dot-delimited) object paths to drop")
+ private Set<String> _fieldPathsToDrop = new HashSet<>();
+
+ @JsonPropertyDescription("Array of flattened (dot-delimited) object paths not to traverse further and keep same as "
+ + "input. This will also skip building mergedTextIndex for the field.")
+ private Set<String> _fieldPathsToPreserveInput = new HashSet<>();
+
+ @JsonPropertyDescription("Map from customized meaningful column name to json key path")
+ private Map<String, String> _columnNameToJsonKeyPathMap = new HashMap<>();
+
+ @JsonPropertyDescription("mergedTextIndex field")
+ private String _mergedTextIndexField = "__mergedTextIndex";
+
+ @JsonPropertyDescription("mergedTextIndex document max length")
+ private int _mergedTextIndexDocumentMaxLength = 32766;
Review Comment:
Thanks for the insight. This would be a relatively big change, will handle in future patch, thanks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on PR #12788:
URL: https://github.com/apache/pinot/pull/12788#issuecomment-2045820585
Some extreme column name corner case checks would be taken care in future patch, e.g., column name with `a.`, input data with `{"a": {"b":1}, "a.b":2, "a.":3, "a.b.":4}`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "chenboat (via GitHub)" <gi...@apache.org>.
chenboat merged PR #12788:
URL: https://github.com/apache/pinot/pull/12788
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552487729
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
Review Comment:
The Deque object represents multiple paths by revising itself in place with add/remove. But at each single moment, it could only represent one single path. Queue(a, b, c) is representing path a.b.c which is a single path instead of 3 paths.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1554805805
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
+ if (!isIndexable) {
+ extraFieldsContainer.addUnindexableEntry(key, value);
+ } else {
+ if (null != currentNode && currentNode.isColumn()) {
+ // In schema
+ outputRecord.putValue(currentNode.getColumnName(), currentNode.getValue(value));
+ if (_transformerConfig.getFieldsToDoubleIngest().contains(keyJsonPath)) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ }
+ mergedTextIndexMap.put(keyJsonPath, value);
+ } else {
+ // Out of schema
+ if (storeIndexableExtras) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ mergedTextIndexMap.put(keyJsonPath, value);
+ }
+ }
+ }
+ return extraFieldsContainer;
+ }
+ // Traverse the subtree
+ Map<String, Object> valueAsMap = (Map<String, Object>) value;
+ for (Map.Entry<String, Object> entry : valueAsMap.entrySet()) {
+ jsonPath.addLast(entry.getKey());
+ ExtraFieldsContainer childContainer =
+ processField(currentNode, jsonPath, entry.getValue(), isIndexable, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(key, childContainer);
+ jsonPath.removeLast();
+ }
+ return extraFieldsContainer;
+ }
+
+ /**
+ * Generate an index token based on the provided key-value pair.
+ * The index token follows this format: "val:key".
+ * @param kv used to generate text index tokens
+ * @param indexTokens a list to store the generated index tokens
+ * @param mergedTextIndexTokenMaxLength which we enforce via truncation during token generation
+ */
+ public void generateTextIndexToken(Map.Entry<String, Object> kv, List<String> indexTokens,
+ Integer mergedTextIndexTokenMaxLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+
+ if (key.length() + 1 > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.error("The provided key's length is too long, text index token cannot be truncated");
+ return;
+ }
+
+ // Truncate the value to ensure the generated index token is less or equal to mergedTextIndexTokenMaxLength
+ // The value length should be the mergedTextIndexTokenMaxLength minus ":" character (length 1) minus key length
+ int valueTruncationLength = mergedTextIndexTokenMaxLength - 1 - key.length();
+ if (val.length() > valueTruncationLength) {
+ _realtimeMergedTextIndexTruncatedTokenSizeMeter = _serverMetrics
+ .addMeteredTableValue(_tableName, ServerMeter.REALTIME_MERGED_TEXT_IDX_TRUNCATED_TOKEN_SIZE,
+ key.length() + 1 + val.length(), _realtimeMergedTextIndexTruncatedTokenSizeMeter);
+ val = val.substring(0, valueTruncationLength);
+ }
+
+ _mergedTextIndexTokenBytesCount += key.length() + 1 + val.length();
+ _mergedTextIndexTokenCount += 1;
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+
+ indexTokens.add(val + ":" + key);
+ }
+
+ /**
+ * Implement shingling for the merged text index based on the provided key-value pair.
+ * Each shingled index token retains the format of a standard index token: "val:key". However, "val" now denotes a
+ * sliding window of characters on the value. The total length of each shingled index token
+ * (key length + shingled value length + 1)must be less than or equal to shingleIndexMaxLength. The starting index
+ * of the sliding window for the value is increased by shinglingOverlapLength for every new shingled token.
+ * All shingle index tokens, except for the last one, should have the maximum possible length. If the minimum token
+ * length (shingling overlap length + key length + 1) exceeds the maximum Lucene token size
+ * (MAXIMUM_LUCENE_TOKEN_SIZE), shingling is disabled, and the value is truncated to match the maximum Lucene token
+ * size. If shingleIndexMaxLength is lower than the required minimum token length and also lower than the maximum
+ * Lucene token size, shingleIndexMaxLength is adjusted to match the maximum Lucene token size.
+ *
+ * Note that the most important parameter, the shingleIndexOverlapLength, is the maximum search length that will yield
+ * results with 100% accuracy.
+ *
+ * Example: key-> "key", value-> "0123456789ABCDEF", max length: 10, shingling overlap length: 3
+ * Generated tokens:
+ * 012345:key
+ * 345678:key
+ * 6789AB:key
+ * 9ABCDE:key
+ * CDEF:key
+ * Any query with a length of 7 will yield no results, such as "0123456" or "6789ABC".
+ * Any query with a length of 3 will yield results with 100% accuracy (i.e. is always guaranteed to be searchable).
+ * Any query with a length between 4 and 6 (inclusive) has indeterminate accuracy.
+ * E.g. for queries with length 5, "12345", "789AB" will hit, while "23456" will miss.
+ *
+ * @param kv used to generate shingle text index tokens
+ * @param shingleIndexTokens a list to store the generated shingle index tokens
+ * @param shingleIndexMaxLength the maximum length of each shingle index token. Needs to be greater than the
+ * length of the key and shingleIndexOverlapLength + 1, and must be lower or equal
+ * to MAXIMUM_LUCENE_TOKEN_SIZE.
+ * @param shingleIndexOverlapLength the number of characters in the kv-pair's value shared by two adjacent shingle
+ * index tokens. If null, the overlap length will be defaulted to half of the max
+ * token length.
+ */
+ public void generateShingleTextIndexToken(Map.Entry<String, Object> kv, List<String> shingleIndexTokens,
+ int shingleIndexMaxLength, int shingleIndexOverlapLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+ final int valLength = val.length();
+ final int tokenSuffixLength = key.length() + 1;
+ final int minTokenLength = tokenSuffixLength + shingleIndexOverlapLength + 1;
+
+ if (shingleIndexOverlapLength >= valLength) {
+ if (_logger.isDebugEnabled()) {
+ _logger.warn("The shingleIndexOverlapLength " + shingleIndexOverlapLength + " is longer than the value length "
+ + valLength + ". Shingling will not be applied since only one token will be generated.");
+ }
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ if (minTokenLength > MAXIMUM_LUCENE_TOKEN_SIZE) {
+ _logger.debug("The minimum token length " + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + ") exceeds "
+ + "the limit of maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ". Value will be truncated and "
+ + "shingling will not be applied.");
+ generateTextIndexToken(kv, shingleIndexTokens, shingleIndexMaxLength);
+ return;
+ }
+
+ // This logging becomes expensive if user accidentally sets a very low shingleIndexMaxLength
+ if (shingleIndexMaxLength < minTokenLength) {
+ _logger.debug("The shingleIndexMaxLength " + shingleIndexMaxLength + " is smaller than the minimum token length "
+ + minTokenLength + " (" + MIN_TOKEN_LENGTH_DESCRIPTION + "). Increasing the shingleIndexMaxLength to "
+ + "maximum Lucene token size " + MAXIMUM_LUCENE_TOKEN_SIZE + ".");
+ shingleIndexMaxLength = MAXIMUM_LUCENE_TOKEN_SIZE;
+ }
+
+ // Shingle window slide length is the index position on the value which we shall advance on every iteration.
+ // We ensure shingleIndexMaxLength >= minTokenLength so that shingleWindowSlideLength >= 1.
+ int shingleWindowSlideLength = shingleIndexMaxLength - shingleIndexOverlapLength - tokenSuffixLength;
+
+ // Generate shingle index tokens
+ // When starting_idx + shingleIndexOverlapLength >= valLength, there are no new characters to capture, then we stop
+ // the shingle token generation loop.
+ // We ensure that shingleIndexOverlapLength < valLength so that this loop will be entered at lease once.
+ for (int i = 0; i + shingleIndexOverlapLength < valLength; i += shingleWindowSlideLength) {
+ String tokenValStr = val.substring(i, Math.min(i + shingleIndexMaxLength - tokenSuffixLength, valLength));
+ String shingleIndexToken = tokenValStr + ":" + key;
+ shingleIndexTokens.add(shingleIndexToken);
+ _mergedTextIndexTokenBytesCount += shingleIndexToken.length();
+ ++_mergedTextIndexTokenCount;
+ }
+ _serverMetrics.setValueOfTableGauge(_tableName, ServerGauge.REALTIME_MERGED_TEXT_IDX_TOKEN_AVG_LEN,
+ _mergedTextIndexTokenBytesCount / _mergedTextIndexTokenCount);
+ }
+
+ /**
+ * Converts (if necessary) and adds the given extras field to the output record
+ */
+ private void putExtrasField(String fieldName, DataType fieldType, Map<String, Object> field,
+ GenericRow outputRecord) {
+ if (null == field) {
+ return;
+ }
+
+ switch (fieldType) {
+ case JSON:
+ outputRecord.putValue(fieldName, field);
+ break;
+ case STRING:
+ try {
+ outputRecord.putValue(fieldName, JsonUtils.objectToString(field));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to convert '" + fieldName + "' to string", e);
+ }
+ break;
+ default:
+ throw new UnsupportedOperationException("Cannot convert '" + fieldName + "' to " + fieldType.name());
+ }
+ }
+
+ private List<String> getLuceneTokensFromMergedTextIndexMap(Map<String, Object> mergedTextIndexMap) {
+ final Integer mergedTextIndexTokenMaxLength = _transformerConfig.getMergedTextIndexTokenMaxLength();
+ final @Nullable
+ Integer mergedTextIndexShinglingOverlapLength = _transformerConfig.getMergedTextIndexShinglingOverlapLength();
+ List<String> luceneTokens = new ArrayList<>();
+ mergedTextIndexMap.entrySet().stream().filter(kv -> null != kv.getKey() && null != kv.getValue())
+ .filter(kv -> !_transformerConfig.getMergedTextIndexPathToExclude().contains(kv.getKey())).filter(
+ kv -> !base64ValueFilter(kv.getValue().toString().getBytes(),
+ _transformerConfig.getMergedTextIndexBinaryTokenDetectionMinLength())).filter(
+ kv -> _transformerConfig.getMergedTextIndexSuffixToExclude().stream()
+ .anyMatch(suffix -> !kv.getKey().endsWith(suffix))).forEach(kv -> {
+ if (null == mergedTextIndexShinglingOverlapLength) {
+ generateTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength);
+ } else {
+ generateShingleTextIndexToken(kv, luceneTokens, mergedTextIndexTokenMaxLength,
+ mergedTextIndexShinglingOverlapLength);
+ }
+ });
+ return luceneTokens;
+ }
+}
+
+/**
+ * SchemaTreeNode represents the tree node when we construct the schema tree. The node could be either leaf node or
+ * non-leaf node. Both types of node could hold the volumn as a column in the schema.
+ * For example, the schema with columns a, b, c, d.e, d.f, x.y, x.y.z, x.y.w will have the following tree structure:
+ * root -- a*
+ * -- b*
+ * -- c*
+ * -- d -- e*
+ * -- f*
+ * -- x* -- y* -- z*
+ * -- w*
+ * where node with "*" could represent a valid column in the schema.
+ */
+class SchemaTreeNode {
+ private boolean _isColumn;
Review Comment:
These 2 terms are both used in Pinot documents, so I assume both as acceptable names. Keep them as is for now.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #12788:
URL: https://github.com/apache/pinot/pull/12788#issuecomment-2035530211
## [Codecov](https://app.codecov.io/gh/apache/pinot/pull/12788?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
Attention: Patch coverage is `57.30337%` with `152 lines` in your changes are missing coverage. Please review.
> Project coverage is 61.96%. Comparing base [(`59551e4`)](https://app.codecov.io/gh/apache/pinot/commit/59551e45224f1535c4863fd577622b37366ccc97?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) to head [(`f7c893a`)](https://app.codecov.io/gh/apache/pinot/pull/12788?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
> Report is 202 commits behind head on master.
| [Files](https://app.codecov.io/gh/apache/pinot/pull/12788?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...ingestion/SchemaConformingTransformerV2Config.java](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&filepath=pinot-spi%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fspi%2Fconfig%2Ftable%2Fingestion%2FSchemaConformingTransformerV2Config.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc3BpL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9zcGkvY29uZmlnL3RhYmxlL2luZ2VzdGlvbi9TY2hlbWFDb25mb3JtaW5nVHJhbnNmb3JtZXJWMkNvbmZpZy5qYXZh) | 0.00% | [72 Missing :warning: ](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...cordtransformer/SchemaConformingTransformerV2.java](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&filepath=pinot-segment-local%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Flocal%2Frecordtransformer%2FSchemaConformingTransformerV2.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1sb2NhbC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3Qvc2VnbWVudC9sb2NhbC9yZWNvcmR0cmFuc2Zvcm1lci9TY2hlbWFDb25mb3JtaW5nVHJhbnNmb3JtZXJWMi5qYXZh) | 73.20% | [37 Missing and 30 partials :warning: ](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...recordtransformer/SchemaConformingTransformer.java](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&filepath=pinot-segment-local%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Flocal%2Frecordtransformer%2FSchemaConformingTransformer.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1sb2NhbC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3Qvc2VnbWVudC9sb2NhbC9yZWNvcmR0cmFuc2Zvcm1lci9TY2hlbWFDb25mb3JtaW5nVHJhbnNmb3JtZXIuamF2YQ==) | 66.66% | [0 Missing and 4 partials :warning: ](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [.../apache/pinot/segment/local/utils/Base64Utils.java](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&filepath=pinot-segment-local%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Flocal%2Futils%2FBase64Utils.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1sb2NhbC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3Qvc2VnbWVudC9sb2NhbC91dGlscy9CYXNlNjRVdGlscy5qYXZh) | 70.00% | [2 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...ache/pinot/segment/local/utils/IngestionUtils.java](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&filepath=pinot-segment-local%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Flocal%2Futils%2FIngestionUtils.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1sb2NhbC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3Qvc2VnbWVudC9sb2NhbC91dGlscy9Jbmdlc3Rpb25VdGlscy5qYXZh) | 0.00% | [0 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...he/pinot/segment/local/utils/TableConfigUtils.java](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&filepath=pinot-segment-local%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Flocal%2Futils%2FTableConfigUtils.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1sb2NhbC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3Qvc2VnbWVudC9sb2NhbC91dGlscy9UYWJsZUNvbmZpZ1V0aWxzLmphdmE=) | 50.00% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...ot/spi/config/table/ingestion/IngestionConfig.java](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&filepath=pinot-spi%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fspi%2Fconfig%2Ftable%2Fingestion%2FIngestionConfig.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc3BpL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9zcGkvY29uZmlnL3RhYmxlL2luZ2VzdGlvbi9Jbmdlc3Rpb25Db25maWcuamF2YQ==) | 50.00% | [2 Missing :warning: ](https://app.codecov.io/gh/apache/pinot/pull/12788?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #12788 +/- ##
============================================
+ Coverage 61.75% 61.96% +0.21%
+ Complexity 207 198 -9
============================================
Files 2436 2464 +28
Lines 133233 135123 +1890
Branches 20636 20879 +243
============================================
+ Hits 82274 83726 +1452
- Misses 44911 45211 +300
- Partials 6048 6186 +138
```
| [Flag](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [custom-integration1](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `<0.01% <0.00%> (-0.01%)` | :arrow_down: |
| [integration](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `<0.01% <0.00%> (-0.01%)` | :arrow_down: |
| [integration1](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `<0.01% <0.00%> (-0.01%)` | :arrow_down: |
| [integration2](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `0.00% <0.00%> (ø)` | |
| [java-11](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `34.81% <1.12%> (-26.90%)` | :arrow_down: |
| [java-21](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `61.84% <57.30%> (+0.21%)` | :arrow_up: |
| [skip-bytebuffers-false](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `61.95% <57.30%> (+0.20%)` | :arrow_up: |
| [skip-bytebuffers-true](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `61.82% <57.30%> (+34.09%)` | :arrow_up: |
| [temurin](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `61.96% <57.30%> (+0.21%)` | :arrow_up: |
| [unittests](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `61.95% <57.30%> (+0.21%)` | :arrow_up: |
| [unittests1](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `46.54% <1.12%> (-0.35%)` | :arrow_down: |
| [unittests2](https://app.codecov.io/gh/apache/pinot/pull/12788/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `28.05% <56.17%> (+0.32%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/pinot/pull/12788?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1554802565
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
+ if (!isIndexable) {
+ extraFieldsContainer.addUnindexableEntry(key, value);
+ } else {
+ if (null != currentNode && currentNode.isColumn()) {
+ // In schema
+ outputRecord.putValue(currentNode.getColumnName(), currentNode.getValue(value));
+ if (_transformerConfig.getFieldsToDoubleIngest().contains(keyJsonPath)) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ }
+ mergedTextIndexMap.put(keyJsonPath, value);
+ } else {
+ // Out of schema
+ if (storeIndexableExtras) {
+ extraFieldsContainer.addIndexableEntry(key, value);
+ mergedTextIndexMap.put(keyJsonPath, value);
+ }
+ }
+ }
+ return extraFieldsContainer;
+ }
+ // Traverse the subtree
+ Map<String, Object> valueAsMap = (Map<String, Object>) value;
+ for (Map.Entry<String, Object> entry : valueAsMap.entrySet()) {
+ jsonPath.addLast(entry.getKey());
+ ExtraFieldsContainer childContainer =
+ processField(currentNode, jsonPath, entry.getValue(), isIndexable, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(key, childContainer);
+ jsonPath.removeLast();
+ }
+ return extraFieldsContainer;
+ }
+
+ /**
+ * Generate an index token based on the provided key-value pair.
+ * The index token follows this format: "val:key".
+ * @param kv used to generate text index tokens
+ * @param indexTokens a list to store the generated index tokens
+ * @param mergedTextIndexTokenMaxLength which we enforce via truncation during token generation
+ */
+ public void generateTextIndexToken(Map.Entry<String, Object> kv, List<String> indexTokens,
+ Integer mergedTextIndexTokenMaxLength) {
+ String key = kv.getKey();
+ String val;
+ // To avoid redundant leading and tailing '"', only convert to JSON string if the value is a list or an array
+ if (kv.getValue() instanceof Collection || kv.getValue() instanceof Object[]) {
+ try {
+ val = JsonUtils.objectToString(kv.getValue());
+ } catch (JsonProcessingException e) {
+ val = kv.getValue().toString();
+ }
+ } else {
+ val = kv.getValue().toString();
+ }
+
+ if (key.length() + 1 > MAXIMUM_LUCENE_TOKEN_SIZE) {
Review Comment:
Good point. Mark it as a TODO. Not resolve in this patch because the upstream Kafka event usually has size limit and usually could not reach that high.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "lnbest0707-uber (via GitHub)" <gi...@apache.org>.
lnbest0707-uber commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1554801974
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
+ * Taking example:
+ * {
+ * "a": 1,
+ * "b": {
+ * "c": 2,
+ * "d": 3,
+ * "d_noIdx": 4
+ * }
+ * "b_noIdx": {
+ * "c": 5,
+ * "d": 6,
+ * }
+ * }
+ * with column "a", "b", "b.c" in schema
+ * There are two types of output:
+ * - flattened keys with values, e.g.,
+ * - keyPath as column and value as leaf node, e.g., "a": 1, "b.c": 2. However, "b" is not a leaf node, so it would
+ * be skipped
+ * - __mergedTestIdx storing ["1:a", "2:b.c", "3:b.d"] as a string array
+ * - structured Json format, e.g.,
+ * - indexableFields/json_data: {"a": 1, "b": {"c": 2, "d": 3}}
+ * - unindexableFields/json_data_noIdx: {"b": {"d_noIdx": 4} ,"b_noIdx": {"c": 5, "d": 6}}
+ * Expected behavior:
+ * - If the current key is special, it would be added to the outputRecord and skip subtree
+ * - If the keyJsonPath is in fieldPathsToDrop, it and its subtree would be skipped
+ * - At leaf node (base case in recursion):
+ * - Parse keyPath and value and add as flattened result to outputRecord
+ * - Return structured fields as ExtraFieldsContainer
+ * - For non-leaf node
+ * - Construct ExtraFieldsContainer based on children's result and return
+ *
+ * @param parentNode The parent node in the schema tree which might or might not has a child with the given key. If
+ * parentNode is null, it means the current key is out of the schema tree.
+ * @param jsonPath The key json path split by "."
+ * @param value The value of the current field
+ * @param isIndexable Whether the current field is indexable
+ * @param outputRecord The output record updated during traverse
+ * @param mergedTextIndexMap The merged text index map updated during traverse
+ * @return ExtraFieldsContainer carries the indexable and unindexable fields of the current node as well as its
+ * subtree
+ */
+ private ExtraFieldsContainer processField(SchemaTreeNode parentNode, Deque<String> jsonPath, Object value,
+ boolean isIndexable, GenericRow outputRecord, Map<String, Object> mergedTextIndexMap) {
+ // Common variables
+ boolean storeIndexableExtras = _transformerConfig.getIndexableExtrasField() != null;
+ boolean storeUnindexableExtras = _transformerConfig.getUnindexableExtrasField() != null;
+ String key = jsonPath.peekLast();
+ ExtraFieldsContainer extraFieldsContainer = new ExtraFieldsContainer(storeUnindexableExtras);
+
+ // Base case
+ if (StreamDataDecoderImpl.isSpecialKeyType(key) || GenericRow.isSpecialKeyType(key)) {
+ outputRecord.putValue(key, value);
+ return extraFieldsContainer;
+ }
+
+ String keyJsonPath = String.join(".", jsonPath);
+ Set<String> fieldPathsToDrop = _transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop && fieldPathsToDrop.contains(keyJsonPath)) {
+ return extraFieldsContainer;
+ }
+
+ SchemaTreeNode currentNode = parentNode == null ? null : parentNode.getChild(key);
+ String unindexableFieldSuffix = _transformerConfig.getUnindexableFieldSuffix();
+ isIndexable = isIndexable && (null == unindexableFieldSuffix || !key.endsWith(unindexableFieldSuffix));
+ if (!(value instanceof Map)) {
+ // leaf node
Review Comment:
Added leaf node definition in method comments
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "chenboat (via GitHub)" <gi...@apache.org>.
chenboat commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552467947
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
+ ExtraFieldsContainer extraFieldsContainer =
+ new ExtraFieldsContainer(null != _transformerConfig.getUnindexableExtrasField());
+ for (Map.Entry<String, Object> recordEntry : record.getFieldToValueMap().entrySet()) {
+ String recordKey = recordEntry.getKey();
+ Object recordValue = recordEntry.getValue();
+ jsonPath.addLast(recordKey);
+ ExtraFieldsContainer currentFieldsContainer =
+ processField(_schemaTree, jsonPath, recordValue, true, outputRecord, mergedTextIndexMap);
+ extraFieldsContainer.addChild(currentFieldsContainer);
+ jsonPath.removeLast();
+ }
+ putExtrasField(_transformerConfig.getIndexableExtrasField(), _indexableExtrasFieldType,
+ extraFieldsContainer.getIndexableExtras(), outputRecord);
+ putExtrasField(_transformerConfig.getUnindexableExtrasField(), _unindexableExtrasFieldType,
+ extraFieldsContainer.getUnindexableExtras(), outputRecord);
+
+ // Generate merged text index
+ if (null != _mergedTextIndexFieldSpec && !mergedTextIndexMap.isEmpty()) {
+ List<String> luceneTokens = getLuceneTokensFromMergedTextIndexMap(mergedTextIndexMap);
+ if (_mergedTextIndexFieldSpec.isSingleValueField()) {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), String.join(" ", luceneTokens));
+ } else {
+ outputRecord.putValue(_transformerConfig.getMergedTextIndexField(), luceneTokens);
+ }
+ }
+ } catch (Exception e) {
+ if (!_continueOnError) {
+ throw e;
+ }
+ _logger.error("Couldn't transform record: {}", record.toString(), e);
+ outputRecord.putValue(GenericRow.INCOMPLETE_RECORD_KEY, true);
+ }
+
+ return outputRecord;
+ }
+
+ /**
+ * The class traverses the schema tree and the record accordingly to build the output record.
Review Comment:
The class --> the method
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Add SchemaConformingTransformerV2 to enhance text search abilities [pinot]
Posted by "chenboat (via GitHub)" <gi...@apache.org>.
chenboat commented on code in PR #12788:
URL: https://github.com/apache/pinot/pull/12788#discussion_r1552465348
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/recordtransformer/SchemaConformingTransformerV2.java:
##########
@@ -0,0 +1,715 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.recordtransformer;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMeter;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.segment.local.utils.Base64Utils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.SchemaConformingTransformerV2Config;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.metrics.PinotMeter;
+import org.apache.pinot.spi.stream.StreamDataDecoderImpl;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This transformer evolves from {@link SchemaConformingTransformer} and is designed to support extra cases for
+ * better text searching:
+ * - Support over-lapping schema fields, in which case it could support schema column "a" and "a.b" at the same time.
+ * And it only allows primitive type fields to be the value.
+ * - Extract flattened key-value pairs as mergedTextIndex for better text searching.
+ * - Add shingle index tokenization functionality for extremely large text fields.
+ * <p>
+ * For example, consider this record:
+ * <pre>
+ * {
+ * "a": 1,
+ * "b": "2",
+ * "c": {
+ * "d": 3,
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "y": 9,
+ * "z_noindex": 10
+ * }
+ * }
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * }
+ * </pre>
+ * And let's say the table's schema contains these fields:
+ * <ul>
+ * <li>a</li>
+ * <li>c</li>
+ * <li>c.d</li>
+ * </ul>
+ * <p>
+ * The record would be transformed into the following (refer to {@link SchemaConformingTransformerV2Config} for
+ * * default constant values):
+ * <pre>
+ * {
+ * "a": 1,
+ * "c": null,
+ * "c.d": 3,
+ * "json_data": {
+ * "b": "2",
+ * "c": {
+ * "x": {
+ * "y": 9
+ * }
+ * }
+ * }
+ * "json_data_no_idx": {
+ * "c": {
+ * "e_noindex": 4,
+ * "f_noindex": {
+ * "g": 5
+ * },
+ * "x": {
+ * "z_noindex": 10
+ * }
+ * },
+ * "h_noindex": "6",
+ * "i_noindex": {
+ * "j": 7,
+ * "k": 8
+ * }
+ * },
+ * "__mergedTextIndex": [
+ * "1:a", "2:b", "3:c.d", "9:c.x.y"
+ * ]
+ * }
+ * </pre>
+ * <p>
+ * The "__mergedTextIndex" could filter and manipulate the data based on the configuration in
+ * {@link SchemaConformingTransformerV2Config}.
+ */
+public class SchemaConformingTransformerV2 implements RecordTransformer {
+ private static final Logger _logger = LoggerFactory.getLogger(SchemaConformingTransformerV2.class);
+ private static final int MAXIMUM_LUCENE_TOKEN_SIZE = 32766;
+ private static final String MIN_TOKEN_LENGTH_DESCRIPTION =
+ "key length + `:` + shingle index overlap length + one non-overlap char";
+
+ private final boolean _continueOnError;
+ private final SchemaConformingTransformerV2Config _transformerConfig;
+ private final DataType _indexableExtrasFieldType;
+ private final DataType _unindexableExtrasFieldType;
+ private final DimensionFieldSpec _mergedTextIndexFieldSpec;
+ @Nullable
+ ServerMetrics _serverMetrics = null;
+ private SchemaTreeNode _schemaTree;
+ @Nullable
+ private PinotMeter _realtimeMergedTextIndexTruncatedTokenSizeMeter = null;
+ private String _tableName;
+ private long _mergedTextIndexTokenBytesCount = 0L;
+ private long _mergedTextIndexTokenCount = 0L;
+
+ public SchemaConformingTransformerV2(TableConfig tableConfig, Schema schema) {
+ if (null == tableConfig.getIngestionConfig() || null == tableConfig.getIngestionConfig()
+ .getSchemaConformingTransformerV2Config()) {
+ _continueOnError = false;
+ _transformerConfig = null;
+ _indexableExtrasFieldType = null;
+ _unindexableExtrasFieldType = null;
+ _mergedTextIndexFieldSpec = null;
+ return;
+ }
+
+ _continueOnError = tableConfig.getIngestionConfig().isContinueOnError();
+ _transformerConfig = tableConfig.getIngestionConfig().getSchemaConformingTransformerV2Config();
+ String indexableExtrasFieldName = _transformerConfig.getIndexableExtrasField();
+ _indexableExtrasFieldType =
+ indexableExtrasFieldName == null ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ indexableExtrasFieldName);
+ String unindexableExtrasFieldName = _transformerConfig.getUnindexableExtrasField();
+ _unindexableExtrasFieldType =
+ null == unindexableExtrasFieldName ? null : SchemaConformingTransformer.getAndValidateExtrasFieldType(schema,
+ unindexableExtrasFieldName);
+ _mergedTextIndexFieldSpec = schema.getDimensionSpec(_transformerConfig.getMergedTextIndexField());
+ _tableName = tableConfig.getTableName();
+ _schemaTree = validateSchemaAndCreateTree(schema, _transformerConfig);
+ _serverMetrics = ServerMetrics.get();
+ }
+
+ /**
+ * Validates the schema against the given transformer's configuration.
+ */
+ public static void validateSchema(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig) {
+ validateSchemaFieldNames(schema.getPhysicalColumnNames(), transformerConfig);
+
+ String indexableExtrasFieldName = transformerConfig.getIndexableExtrasField();
+ if (null != indexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+ String unindexableExtrasFieldName = transformerConfig.getUnindexableExtrasField();
+ if (null != unindexableExtrasFieldName) {
+ SchemaConformingTransformer.getAndValidateExtrasFieldType(schema, indexableExtrasFieldName);
+ }
+
+ validateSchemaAndCreateTree(schema, transformerConfig);
+ }
+
+ /**
+ * Heuristic filter to detect whether a byte array is longer than a specified length and contains only base64
+ * characters so that we treat it as encoded binary data.
+ * @param bytes array to check
+ * @param minLength byte array shorter than this length will not be treated as encoded binary data
+ * @return true if the input bytes is base64 encoded binary data by the heuristic above, false otherwise
+ */
+ public static boolean base64ValueFilter(final byte[] bytes, int minLength) {
+ return bytes.length >= minLength && Base64Utils.isBase64IgnoreTrailingPeriods(bytes);
+ }
+
+ /**
+ * Validates that none of the schema fields have names that conflict with the transformer's configuration.
+ */
+ private static void validateSchemaFieldNames(Set<String> schemaFields,
+ SchemaConformingTransformerV2Config transformerConfig) {
+ // Validate that none of the columns in the schema end with unindexableFieldSuffix
+ String unindexableFieldSuffix = transformerConfig.getUnindexableFieldSuffix();
+ if (null != unindexableFieldSuffix) {
+ for (String field : schemaFields) {
+ Preconditions.checkState(!field.endsWith(unindexableFieldSuffix), "Field '%s' has no-index suffix '%s'", field,
+ unindexableFieldSuffix);
+ }
+ }
+
+ // Validate that none of the columns in the schema end overlap with the fields in fieldPathsToDrop
+ Set<String> fieldPathsToDrop = transformerConfig.getFieldPathsToDrop();
+ if (null != fieldPathsToDrop) {
+ Set<String> fieldIntersection = new HashSet<>(schemaFields);
+ fieldIntersection.retainAll(fieldPathsToDrop);
+ Preconditions.checkState(fieldIntersection.isEmpty(), "Fields in schema overlap with fieldPathsToDrop");
+ }
+ }
+
+ /**
+ * Validates the schema with a SchemaConformingTransformerConfig instance and creates a tree representing the fields
+ * in the schema to be used when transforming input records. Refer to {@link SchemaTreeNode} for details.
+ * @throws IllegalArgumentException if schema validation fails in:
+ * <ul>
+ * <li>One of the fields in the schema has a name which when interpreted as a JSON path, corresponds to an object
+ * with an empty sub-key. E.g., the field name "a..b" corresponds to the JSON {"a": {"": {"b": ...}}}</li>
+ * </ul>
+ */
+ private static SchemaTreeNode validateSchemaAndCreateTree(@Nonnull Schema schema,
+ @Nonnull SchemaConformingTransformerV2Config transformerConfig)
+ throws IllegalArgumentException {
+ Set<String> schemaFields = schema.getPhysicalColumnNames();
+ Map<String, String> jsonKeyPathToColumnNameMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : transformerConfig.getColumnNameToJsonKeyPathMap().entrySet()) {
+ String columnName = entry.getKey();
+ String jsonKeyPath = entry.getValue();
+ schemaFields.remove(columnName);
+ schemaFields.add(jsonKeyPath);
+ jsonKeyPathToColumnNameMap.put(jsonKeyPath, columnName);
+ }
+
+ SchemaTreeNode rootNode = new SchemaTreeNode("", null, schema);
+ List<String> subKeys = new ArrayList<>();
+ for (String field : schemaFields) {
+ SchemaTreeNode currentNode = rootNode;
+ int keySeparatorIdx = field.indexOf(JsonUtils.KEY_SEPARATOR);
+ if (-1 == keySeparatorIdx) {
+ // Not a flattened key
+ currentNode = rootNode.getAndCreateChild(field, schema);
+ } else {
+ subKeys.clear();
+ SchemaConformingTransformer.getAndValidateSubKeys(field, keySeparatorIdx, subKeys);
+ for (String subKey : subKeys) {
+ SchemaTreeNode childNode = currentNode.getAndCreateChild(subKey, schema);
+ currentNode = childNode;
+ }
+ }
+ currentNode.setColumn(jsonKeyPathToColumnNameMap.get(field));
+ }
+
+ return rootNode;
+ }
+
+ @Override
+ public boolean isNoOp() {
+ return null == _transformerConfig;
+ }
+
+ @Nullable
+ @Override
+ public GenericRow transform(GenericRow record) {
+ GenericRow outputRecord = new GenericRow();
+ Map<String, Object> mergedTextIndexMap = new HashMap<>();
+
+ try {
+ Deque<String> jsonPath = new ArrayDeque<>();
Review Comment:
jsonPath --> jsonPaths since we have multiple paths.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org