You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by ja...@apache.org on 2020/02/22 01:27:08 UTC

[incubator-pinot] 01/01: update pinot upsert features to pinot common

This is an automated email from the ASF dual-hosted git repository.

jamesshao pushed a commit to branch upsert-rebase
in repository https://gitbox.apache.org/repos/asf/incubator-pinot.git

commit 230632af4a75952d64fa60720f460eff1caa7011
Author: james Shao <sj...@uber.com>
AuthorDate: Fri Feb 21 17:25:09 2020 -0800

    update pinot upsert features to pinot common
---
 .../apache/pinot/common/config/TableConfig.java    |  62 +++++++-
 .../pinot/common/config/TableNameBuilder.java      |  15 ++
 .../pinot/common/metrics/AbstractMetrics.java      |  11 +-
 .../apache/pinot/common/metrics/BrokerGauge.java   |   3 +-
 .../apache/pinot/common/metrics/BrokerMeter.java   |   3 +-
 .../apache/pinot/common/metrics/ServerMeter.java   |   5 +-
 .../restlet/resources/TableLowWaterMarksInfo.java  |  43 ++++++
 .../apache/pinot/common/utils/CommonConstants.java |  51 ++++++-
 .../apache/pinot/common/utils/LLCSegmentName.java  |  14 +-
 .../org/apache/pinot/common/utils/NetUtil.java     |  31 +++-
 .../java/org/apache/pinot/spi/data/FieldSpec.java  |   8 +
 .../java/org/apache/pinot/spi/data/Schema.java     | 167 ++++++++++++++++++++-
 pom.xml                                            |  21 +++
 13 files changed, 414 insertions(+), 20 deletions(-)

diff --git a/pinot-common/src/main/java/org/apache/pinot/common/config/TableConfig.java b/pinot-common/src/main/java/org/apache/pinot/common/config/TableConfig.java
index 59e95fe..d4f8303 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/config/TableConfig.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/config/TableConfig.java
@@ -22,28 +22,27 @@ import com.fasterxml.jackson.annotation.JsonPropertyDescription;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ArrayNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.google.common.base.Preconditions;
 import java.io.IOException;
-import java.lang.reflect.Type;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import javax.annotation.Nullable;
-import javax.validation.constraints.Null;
 import org.apache.helix.ZNRecord;
 import org.apache.pinot.common.assignment.InstancePartitionsType;
 import org.apache.pinot.common.config.instance.InstanceAssignmentConfig;
 import org.apache.pinot.common.utils.CommonConstants.Helix.TableType;
 import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.common.utils.CommonConstants.UpdateSemantic;
 
 
 @SuppressWarnings({"Duplicates", "unused"})
 public class TableConfig extends BaseJsonConfig {
   public static final String TABLE_NAME_KEY = "tableName";
   public static final String TABLE_TYPE_KEY = "tableType";
+  private static final String UPDATE_SEMANTIC_CONFIG_KEY = "updateSemantic";
   public static final String VALIDATION_CONFIG_KEY = "segmentsConfig";
   public static final String TENANT_CONFIG_KEY = "tenants";
   public static final String INDEXING_CONFIG_KEY = "tableIndexConfig";
@@ -76,6 +75,9 @@ public class TableConfig extends BaseJsonConfig {
 
   private List<FieldConfig> _fieldConfigList;
 
+  @JsonPropertyDescription(value = "The update semantic of the table, either append or upsert, default as append")
+  private UpdateSemantic _updateSemantic;
+
   /**
    * NOTE: DO NOT use this constructor, use builder instead. This constructor is for deserializer only.
    */
@@ -90,6 +92,15 @@ public class TableConfig extends BaseJsonConfig {
       @Nullable QuotaConfig quotaConfig, @Nullable TableTaskConfig taskConfig, @Nullable RoutingConfig routingConfig,
       @Nullable Map<InstancePartitionsType, InstanceAssignmentConfig> instanceAssignmentConfigMap,
       @Nullable List<FieldConfig> fieldConfigList) {
+      this(tableName, tableType, validationConfig, tenantConfig, indexingConfig, customConfig, quotaConfig, taskConfig,
+              routingConfig, instanceAssignmentConfigMap, fieldConfigList, UpdateSemantic.APPEND);
+  }
+
+  private TableConfig(String tableName, TableType tableType, SegmentsValidationAndRetentionConfig validationConfig,
+            TenantConfig tenantConfig, IndexingConfig indexingConfig, TableCustomConfig customConfig,
+            @Nullable QuotaConfig quotaConfig, @Nullable TableTaskConfig taskConfig, @Nullable RoutingConfig routingConfig,
+            @Nullable Map<InstancePartitionsType, InstanceAssignmentConfig> instanceAssignmentConfigMap,
+            @Nullable List<FieldConfig> fieldConfigList, @Nullable UpdateSemantic updateSemantic) {
     _tableName = TableNameBuilder.forType(tableType).tableNameWithType(tableName);
     _tableType = tableType;
     _validationConfig = validationConfig;
@@ -101,6 +112,7 @@ public class TableConfig extends BaseJsonConfig {
     _routingConfig = routingConfig;
     _instanceAssignmentConfigMap = instanceAssignmentConfigMap;
     _fieldConfigList = fieldConfigList;
+    _updateSemantic = updateSemantic;
   }
 
   public static TableConfig fromJsonString(String jsonString)
@@ -152,8 +164,15 @@ public class TableConfig extends BaseJsonConfig {
     List<FieldConfig> fieldConfigList = extractChildConfig(jsonConfig, FIELD_CONFIG_LIST_KEY,
         new TypeReference<List<FieldConfig>>() {});
 
+    // generate update schematic
+    UpdateSemantic updateSemantic = UpdateSemantic.DEFAULT_SEMANTIC;
+    if (jsonConfig.has(UPDATE_SEMANTIC_CONFIG_KEY)) {
+      updateSemantic = UpdateSemantic.getUpdateSemantic(jsonConfig.get(UPDATE_SEMANTIC_CONFIG_KEY).asText());
+    }
+
     return new TableConfig(tableName, tableType, validationConfig, tenantConfig, indexingConfig, customConfig,
-        quotaConfig, taskConfig, routingConfig, instanceAssignmentConfigMap, fieldConfigList);
+        quotaConfig, taskConfig, routingConfig, instanceAssignmentConfigMap, fieldConfigList, updateSemantic);
+
   }
 
   /**
@@ -225,6 +244,11 @@ public class TableConfig extends BaseJsonConfig {
       jsonConfig.put(FIELD_CONFIG_LIST_KEY, JsonUtils.objectToJsonNode(_fieldConfigList));
     }
 
+    if (_updateSemantic != null) {
+      jsonConfig.put(UPDATE_SEMANTIC_CONFIG_KEY, _updateSemantic.toString());
+    } else {
+      jsonConfig.put(UPDATE_SEMANTIC_CONFIG_KEY, UpdateSemantic.APPEND.toString());
+    }
     return jsonConfig;
   }
 
@@ -301,8 +325,10 @@ public class TableConfig extends BaseJsonConfig {
       fieldConfigList = JsonUtils.stringToObject(fieldConfigListString, new TypeReference<List<FieldConfig>>() {});
     }
 
+    UpdateSemantic updateSemantic = UpdateSemantic.getUpdateSemantic(simpleFields.get(UPDATE_SEMANTIC_CONFIG_KEY));
+
     return new TableConfig(tableName, tableType, validationConfig, tenantConfig, indexingConfig, customConfig,
-        quotaConfig, taskConfig, routingConfig, instanceAssignmentConfigMap, fieldConfigList);
+        quotaConfig, taskConfig, routingConfig, instanceAssignmentConfigMap, fieldConfigList, updateSemantic);
   }
 
   public ZNRecord toZNRecord()
@@ -337,6 +363,7 @@ public class TableConfig extends BaseJsonConfig {
     }
 
     ZNRecord znRecord = new ZNRecord(_tableName);
+    simpleFields.put(UPDATE_SEMANTIC_CONFIG_KEY, _updateSemantic.toString());
     znRecord.setSimpleFields(simpleFields);
     return znRecord;
   }
@@ -444,6 +471,18 @@ public class TableConfig extends BaseJsonConfig {
     return _fieldConfigList;
   }
 
+  public UpdateSemantic getUpdateSemantic() {
+    return _updateSemantic;
+  }
+
+  public void setUpdateSemantic(UpdateSemantic updateSemantic) {
+    _updateSemantic = updateSemantic;
+  }
+
+  public boolean isTableForUpsert() {
+    return _updateSemantic == UpdateSemantic.UPSERT;
+  }
+
   public static class Builder {
     private static final String DEFAULT_SEGMENT_PUSH_TYPE = "APPEND";
     private static final String REFRESH_SEGMENT_PUSH_TYPE = "REFRESH";
@@ -490,6 +529,8 @@ public class TableConfig extends BaseJsonConfig {
     private Map<InstancePartitionsType, InstanceAssignmentConfig> _instanceAssignmentConfigMap;
     private List<FieldConfig> _fieldConfigList;
 
+    private UpdateSemantic _updateSemantic;
+
     public Builder(TableType tableType) {
       _tableType = tableType;
     }
@@ -656,6 +697,11 @@ public class TableConfig extends BaseJsonConfig {
       return this;
     }
 
+    public Builder setUpdateSemantic(UpdateSemantic updateSemantic) {
+      _updateSemantic = updateSemantic;
+      return this;
+    }
+
     public TableConfig build() {
       // Validation config
       SegmentsValidationAndRetentionConfig validationConfig = new SegmentsValidationAndRetentionConfig();
@@ -693,8 +739,12 @@ public class TableConfig extends BaseJsonConfig {
         _customConfig = new TableCustomConfig(null);
       }
 
+      if (_updateSemantic == null) {
+        _updateSemantic = UpdateSemantic.DEFAULT_SEMANTIC;
+      }
+
       return new TableConfig(_tableName, _tableType, validationConfig, tenantConfig, indexingConfig, _customConfig,
-          _quotaConfig, _taskConfig, _routingConfig, _instanceAssignmentConfigMap, _fieldConfigList);
+          _quotaConfig, _taskConfig, _routingConfig, _instanceAssignmentConfigMap, _fieldConfigList, _updateSemantic);
     }
   }
 }
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/config/TableNameBuilder.java b/pinot-common/src/main/java/org/apache/pinot/common/config/TableNameBuilder.java
index 48be395..6746a79 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/config/TableNameBuilder.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/config/TableNameBuilder.java
@@ -132,4 +132,19 @@ public class TableNameBuilder {
   public static boolean isRealtimeTableResource(String resourceName) {
     return REALTIME.tableHasTypeSuffix(resourceName);
   }
+
+  /**
+   * ensure that table name ends with type info, if no, create one with the given type
+   * @param tableName the name of the table
+   * @param type the type of the table for it to fill in if the type info is missing
+   * @return the table type name with the type info
+   */
+  public static String ensureTableNameWithType(String tableName, TableType type) {
+    for (TableType tableType: TableType.values()) {
+      if (tableName.endsWith(TYPE_SUFFIX_SEPARATOR + tableType.toString())) {
+        return tableName;
+      }
+    }
+    return tableName + TYPE_SUFFIX_SEPARATOR + type.toString();
+  }
 }
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metrics/AbstractMetrics.java b/pinot-common/src/main/java/org/apache/pinot/common/metrics/AbstractMetrics.java
index bf4a853..c92bebc 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/metrics/AbstractMetrics.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/metrics/AbstractMetrics.java
@@ -21,16 +21,17 @@ package org.apache.pinot.common.metrics;
 import com.google.common.annotations.VisibleForTesting;
 import com.yammer.metrics.core.MetricName;
 import com.yammer.metrics.core.MetricsRegistry;
+import org.apache.pinot.common.Utils;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
 import java.util.Map;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
-import javax.annotation.Nullable;
-import org.apache.pinot.common.Utils;
-import org.apache.pinot.common.request.BrokerRequest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 
 /**
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerGauge.java b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerGauge.java
index a8b3797..2920b11 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerGauge.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerGauge.java
@@ -26,7 +26,8 @@ import org.apache.pinot.common.Utils;
  *
  */
 public enum BrokerGauge implements AbstractMetrics.Gauge {
-  QUERY_QUOTA_CAPACITY_UTILIZATION_RATE("tables", false), NETTY_CONNECTION_CONNECT_TIME_MS("nettyConnection", true);
+  QUERY_QUOTA_CAPACITY_UTILIZATION_RATE("tables", false), NETTY_CONNECTION_CONNECT_TIME_MS("nettyConnection", true),
+  TABLE_MIN_LOW_WATER_MARK("tables", false);
 
   private final String brokerGaugeName;
   private final String unit;
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
index 9e59fc8..b2f114b 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
@@ -98,7 +98,8 @@ public enum BrokerMeter implements AbstractMetrics.Meter {
   NETTY_CONNECTION_BYTES_SENT("nettyConnection", true),
   NETTY_CONNECTION_BYTES_RECEIVED("nettyConnection", true),
 
-  PROACTIVE_CLUSTER_CHANGE_CHECK("proactiveClusterChangeCheck", true);
+  PROACTIVE_CLUSTER_CHANGE_CHECK("proactiveClusterChangeCheck", true),
+  LOW_WATER_MARK_QUERY_FAILURES("failures", true);
 
   private final String brokerMeterName;
   private final String unit;
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java b/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java
index 3438415..8cc4e2c 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java
@@ -65,7 +65,10 @@ public enum ServerMeter implements AbstractMetrics.Meter {
   // Netty connection metrics
   NETTY_CONNECTION_BYTES_RECEIVED("nettyConnection", true),
   NETTY_CONNECTION_RESPONSES_SENT("nettyConnection", true),
-  NETTY_CONNECTION_BYTES_SENT("nettyConnection", true);
+  NETTY_CONNECTION_BYTES_SENT("nettyConnection", true),
+
+  // upsert related metrics
+  MESSAGE_PRODUCE_FAILED_COUNT("failedMessage", true);
 
   private final String meterName;
   private final String unit;
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/restlet/resources/TableLowWaterMarksInfo.java b/pinot-common/src/main/java/org/apache/pinot/common/restlet/resources/TableLowWaterMarksInfo.java
new file mode 100644
index 0000000..6f6aa18
--- /dev/null
+++ b/pinot-common/src/main/java/org/apache/pinot/common/restlet/resources/TableLowWaterMarksInfo.java
@@ -0,0 +1,43 @@
+/**
+ * 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.common.restlet.resources;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.codehaus.jackson.annotate.JsonIgnoreProperties;
+
+import java.util.Collections;
+import java.util.Map;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class TableLowWaterMarksInfo {
+    // A mapping from table name to the table's partiton -> low_water_mark mappings.
+    private Map<String, Map<Integer, Long>> tableLowWaterMarks;
+
+    public TableLowWaterMarksInfo(@JsonProperty("lowWaterMarks") Map<String, Map<Integer, Long>> tableLowWaterMarks) {
+        this.tableLowWaterMarks = tableLowWaterMarks;
+    }
+
+    public void setTableLowWaterMarks(Map<String, Map<Integer, Long>> tableLowWaterMarks) {
+        this.tableLowWaterMarks = tableLowWaterMarks;
+    }
+
+    public Map<String, Map<Integer, Long>> getTableLowWaterMarks() {
+        return Collections.unmodifiableMap(tableLowWaterMarks);
+    }
+}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/utils/CommonConstants.java b/pinot-common/src/main/java/org/apache/pinot/common/utils/CommonConstants.java
index e8938cf..a6f242c 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/utils/CommonConstants.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/utils/CommonConstants.java
@@ -18,9 +18,12 @@
  */
 package org.apache.pinot.common.utils;
 
-import java.io.File;
 import org.apache.pinot.common.response.BrokerResponseFactory;
 
+import org.apache.commons.lang.StringUtils;
+
+import java.io.File;
+
 
 public class CommonConstants {
 
@@ -36,9 +39,13 @@ public class CommonConstants {
     public static final String PREFIX_OF_BROKER_INSTANCE = "Broker_";
     public static final String PREFIX_OF_SERVER_INSTANCE = "Server_";
     public static final String PREFIX_OF_MINION_INSTANCE = "Minion_";
+    public static final String PREFIX_OF_KEY_COORDINATOR_INSTANCE = "KeyCoordinator_";
 
     public static final String BROKER_RESOURCE_INSTANCE = "brokerResource";
     public static final String LEAD_CONTROLLER_RESOURCE_NAME = "leadControllerResource";
+    public static final String KEY_COORDINATOR_MESSAGE_RESOURCE_NAME = "keyCoordinatorMessageResource";
+
+    public static final int KEY_COORDINATOR_MESSAGE_RESOURCE_REPLICA_COUNT = 1;
 
     public static final String LEAD_CONTROLLER_RESOURCE_ENABLED_KEY = "RESOURCE_ENABLED";
     public static final String ENABLE_CASE_INSENSITIVE_PQL_KEY = "enable.case.insensitive.pql";
@@ -167,12 +174,17 @@ public class CommonConstants {
     public static final double DEFAULT_BROKER_MIN_RESOURCE_PERCENT_FOR_START = 100.0;
     public static final String CONFIG_OF_ENABLE_QUERY_LIMIT_OVERRIDE = "pinot.broker.enable.query.limit.override";
 
+    public static final String CONFIG_OF_BROKER_POLLING_SERVER_LWMS_INTERVAL_MS = "pinot.broker.query.polling.server.lwms.interval.ms";
+    public static final String CONFIG_OF_BROKER_POLLING_SERVER_LWMS_SERVER_PORT = "pinot.broker.query.polling.server.lwms.port";
+    public static final String CONFIG_OF_BROKER_LWM_REWRITE_ENABLE = "pinot.broker.query.lwm.rewrite";
+    public static final boolean CONFIG_OF_BROKER_LWM_REWRITE_ENABLE_DEFAULT = true;
     public static class Request {
       public static final String PQL = "pql";
       public static final String SQL = "sql";
       public static final String TRACE = "trace";
       public static final String DEBUG_OPTIONS = "debugOptions";
       public static final String QUERY_OPTIONS = "queryOptions";
+      public static final String DISABLE_REWRITE = "disableRewrite";
 
       public static class QueryOptionKey {
         public static final String PRESERVE_TYPE = "preserveType";
@@ -294,6 +306,7 @@ public class CommonConstants {
   }
 
   public static class Minion {
+
     public static final String CONFIG_OF_METRICS_PREFIX = "pinot.minion.";
     public static final String METADATA_EVENT_OBSERVER_PREFIX = "metadata.event.notifier";
 
@@ -312,6 +325,23 @@ public class CommonConstants {
     public static final String PREFIX_OF_CONFIG_OF_PINOT_CRYPTER = "crypter";
   }
 
+  public static class Grigio {
+    // config for distributed grigio components
+    public static final String CONFIG_OF_METRICS_PREFIX_KEY = "metrics.prefix";
+    public static final String DEFAULT_METRICS_PREFIX = "pinot.grigio.";
+
+    // config for server related components
+    public static final String PINOT_UPSERT_SERVER_COMPONENT_PREFIX = "upsert.";
+  }
+
+  public static class Metric {
+    public static class Server {
+      public static final String CURRENT_NUMBER_OF_SEGMENTS = "currentNumberOfSegments";
+      public static final String CURRENT_NUMBER_OF_DOCUMENTS = "currentNumberOfDocuments";
+      public static final String NUMBER_OF_DELETED_SEGMENTS = "numberOfDeletedSegments";
+    }
+  }
+
   public static class Segment {
     public static class Realtime {
       public enum Status {
@@ -382,4 +412,23 @@ public class CommonConstants {
     @Deprecated
     public static final String TABLE_NAME = "segment.table.name";
   }
+
+  public enum UpdateSemantic {
+    APPEND,
+    UPSERT;
+
+    public static UpdateSemantic DEFAULT_SEMANTIC = APPEND;
+
+    public static UpdateSemantic getUpdateSemantic(String updateSemanticStr) {
+      if (StringUtils.isEmpty(updateSemanticStr)) {
+        return DEFAULT_SEMANTIC;
+      }
+      try {
+        return valueOf(updateSemanticStr.toUpperCase());
+      } catch (Exception ex) {
+        return DEFAULT_SEMANTIC;
+      }
+    }
+  }
+
 }
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/utils/LLCSegmentName.java b/pinot-common/src/main/java/org/apache/pinot/common/utils/LLCSegmentName.java
index 3596e26..03334e6 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/utils/LLCSegmentName.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/utils/LLCSegmentName.java
@@ -21,9 +21,13 @@ package org.apache.pinot.common.utils;
 import org.joda.time.DateTime;
 import org.joda.time.DateTimeZone;
 
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+
 
 public class LLCSegmentName extends SegmentName implements Comparable {
   private final static String DATE_FORMAT = "yyyyMMdd'T'HHmm'Z'";
+  private final static SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT);
   private final String _tableName;
   private final int _partitionId;
   private final int _sequenceNumber;
@@ -52,7 +56,7 @@ public class LLCSegmentName extends SegmentName implements Comparable {
     _sequenceNumber = sequenceNumber;
     // ISO8601 date: 20160120T1234Z
     DateTime dateTime = new DateTime(msSinceEpoch, DateTimeZone.UTC);
-    _creationTime = dateTime.toString("yyyyMMdd'T'HHmm'Z'");
+    _creationTime = dateTime.toString(DATE_FORMAT);
     _segmentName = tableName + SEPARATOR + partitionId + SEPARATOR + sequenceNumber + SEPARATOR + _creationTime;
   }
 
@@ -85,6 +89,14 @@ public class LLCSegmentName extends SegmentName implements Comparable {
     return _creationTime;
   }
 
+  public long getCreationTimeStamp() {
+    try {
+      return SIMPLE_DATE_FORMAT.parse(getCreationTime()).getTime();
+    } catch (ParseException e) {
+      throw new RuntimeException("failed to parse creation time " + getCreationTime(), e);
+    }
+  }
+
   @Override
   public String getSegmentName() {
     return _segmentName;
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/utils/NetUtil.java b/pinot-common/src/main/java/org/apache/pinot/common/utils/NetUtil.java
index 1ca89ae..5f2d2ac 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/utils/NetUtil.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/utils/NetUtil.java
@@ -18,13 +18,21 @@
  */
 package org.apache.pinot.common.utils;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import java.net.DatagramSocket;
 import java.net.InetAddress;
+import java.net.NetworkInterface;
 import java.net.SocketException;
 import java.net.UnknownHostException;
+import java.util.Enumeration;
 
 
 public class NetUtil {
+  private static final Logger LOGGER = LoggerFactory.getLogger(NetUtil.class);
+
+  private static final String LOCALHOST_NAME = "localhost";
   private static final String DUMMY_OUT_IP = "74.125.224.0";
 
   /**
@@ -48,8 +56,27 @@ public class NetUtil {
    */
   public static String getHostnameOrAddress() {
     try {
-      return InetAddress.getLocalHost().getCanonicalHostName();
-    } catch (UnknownHostException ignored) {
+      String hostName = InetAddress.getLocalHost().getCanonicalHostName();
+      if (!hostName.equalsIgnoreCase(LOCALHOST_NAME)) {
+        return hostName;
+      } else {
+        Enumeration<NetworkInterface> interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
+        while (interfaceEnumeration.hasMoreElements()) {
+          NetworkInterface networkInterface = interfaceEnumeration.nextElement();
+          if (networkInterface != null) {
+            Enumeration<InetAddress> networkAddressEnumeration = networkInterface.getInetAddresses();
+            while(networkAddressEnumeration.hasMoreElements()) {
+              InetAddress address = networkAddressEnumeration.nextElement();
+              if (address != null && !LOCALHOST_NAME.equalsIgnoreCase(address.getCanonicalHostName())) {
+                return address.getCanonicalHostName();
+              }
+            }
+          }
+        }
+        return LOCALHOST_NAME;
+      }
+    } catch (UnknownHostException | SocketException ignored) {
+      LOGGER.warn("failed to get host name", ignored);
       try {
         return getHostAddress();
       } catch (Exception e) {
diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/data/FieldSpec.java b/pinot-spi/src/main/java/org/apache/pinot/spi/data/FieldSpec.java
index a8b1bc3..cdd589c 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/data/FieldSpec.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/data/FieldSpec.java
@@ -24,6 +24,7 @@ import javax.annotation.Nullable;
 import org.apache.pinot.spi.utils.BytesUtils;
 import org.apache.pinot.spi.utils.EqualityUtils;
 import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.commons.lang.StringUtils;
 
 
 /**
@@ -119,6 +120,10 @@ public abstract class FieldSpec implements Comparable<FieldSpec> {
     return _isSingleValueField;
   }
 
+  public boolean isVirtualColumnField() {
+    return _virtualColumnProvider != null;
+  }
+
   // Required by JSON de-serializer. DO NOT REMOVE.
   public void setSingleValueField(boolean isSingleValueField) {
     _isSingleValueField = isSingleValueField;
@@ -255,6 +260,9 @@ public abstract class FieldSpec implements Comparable<FieldSpec> {
     if (!_isSingleValueField) {
       jsonObject.put("singleValueField", false);
     }
+    if (StringUtils.isNotEmpty(_virtualColumnProvider)) {
+      jsonObject.put("virtualColumnProvider", _virtualColumnProvider);
+    }
     if (_maxLength != DEFAULT_MAX_LENGTH) {
       jsonObject.put("maxLength", _maxLength);
     }
diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java b/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java
index a2d037c..3faf1bd 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.java
@@ -24,9 +24,17 @@ import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.node.ArrayNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.google.common.base.Preconditions;
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
@@ -39,8 +47,6 @@ import org.apache.pinot.spi.data.FieldSpec.DataType;
 import org.apache.pinot.spi.data.FieldSpec.FieldType;
 import org.apache.pinot.spi.utils.EqualityUtils;
 import org.apache.pinot.spi.utils.JsonUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 
 /**
@@ -59,6 +65,17 @@ public final class Schema {
   private static final Logger LOGGER = LoggerFactory.getLogger(Schema.class);
 
   private String _schemaName;
+
+  // upsert related config
+  private String _primaryKey;
+  private String _offsetKey;
+  private String _updateSemantic;
+  private static final String UPSERT_TABLE_CONFIG_KEY = "upsert";
+  @JsonIgnore
+  private DimensionFieldSpec _primaryKeyFieldSpec = null;
+  @JsonIgnore
+  private DimensionFieldSpec _offsetKeyFieldSpec = null;
+
   private final List<DimensionFieldSpec> _dimensionFieldSpecs = new ArrayList<>();
   private final List<MetricFieldSpec> _metricFieldSpecs = new ArrayList<>();
   private TimeFieldSpec _timeFieldSpec;
@@ -66,6 +83,7 @@ public final class Schema {
 
   // Json ignored fields
   private transient final Map<String, FieldSpec> _fieldSpecMap = new HashMap<>();
+  private transient final Map<String, FieldSpec> _physicalFieldSpecMap = new HashMap<>();
   private transient final List<String> _dimensionNames = new ArrayList<>();
   private transient final List<String> _metricNames = new ArrayList<>();
   private transient final List<String> _dateTimeNames = new ArrayList<>();
@@ -96,6 +114,68 @@ public final class Schema {
     _schemaName = schemaName;
   }
 
+  public String getPrimaryKey() {
+    return _primaryKey;
+  }
+
+  public void setPrimaryKey(@Nonnull String primaryKey) {
+    _primaryKey = primaryKey;
+  }
+
+  public String getOffsetKey() {
+    return _offsetKey;
+  }
+
+  public void setOffsetKey(@Nonnull String offsetKey) {
+    _offsetKey = offsetKey;
+  }
+
+  public String getUpdateSemantic() {
+    return _updateSemantic;
+  }
+
+  public void setUpdateSemantic(@Nonnull String updateSemantic) {
+    _updateSemantic = updateSemantic;
+  }
+
+  @JsonIgnore
+  public boolean isTableForUpsert() {
+    return UPSERT_TABLE_CONFIG_KEY.equalsIgnoreCase(_updateSemantic);
+  }
+
+  @JsonIgnore
+  public DimensionFieldSpec getPrimaryKeyFieldSpec() {
+    if (_primaryKeyFieldSpec == null) {
+      Preconditions.checkState(_dimensionFieldSpecs.size() > 0, "should have more than 1 dimensions");
+      Preconditions.checkState(StringUtils.isNotEmpty(_primaryKey), "primary key should not be empty");
+      for (DimensionFieldSpec dimensionFieldSpec : _dimensionFieldSpecs) {
+        if (dimensionFieldSpec._name.equals(_primaryKey)) {
+          _primaryKeyFieldSpec = dimensionFieldSpec;
+        }
+      }
+    }
+    return _primaryKeyFieldSpec;
+  }
+
+  @JsonIgnore
+  public DimensionFieldSpec getOffsetKeyFieldSpec() {
+    if (_offsetKeyFieldSpec == null) {
+      Preconditions.checkState(_dimensionFieldSpecs.size() > 0, "should have more than 1 dimensions");
+      Preconditions.checkState(StringUtils.isNotEmpty(_offsetKey), "offset key should not be empty");
+      for (DimensionFieldSpec dimensionFieldSpec : _dimensionFieldSpecs) {
+        if (dimensionFieldSpec._name.equals(_offsetKey)) {
+          _offsetKeyFieldSpec = dimensionFieldSpec;
+          Preconditions.checkState(_offsetKeyFieldSpec.isSingleValueField(), "offset key should be single value");
+          Preconditions.checkState(_offsetKeyFieldSpec.getDataType() == DataType.LONG, "offset key should be long type");
+        }
+      }
+    }
+    if (_offsetKeyFieldSpec == null) {
+      throw new RuntimeException("no dimension matches primary key name");
+    }
+    return _offsetKeyFieldSpec;
+  }
+
   public List<DimensionFieldSpec> getDimensionFieldSpecs() {
     return _dimensionFieldSpecs;
   }
@@ -191,6 +271,9 @@ public final class Schema {
     }
 
     _fieldSpecMap.put(columnName, fieldSpec);
+    if (!fieldSpec.isVirtualColumnField()) {
+      _physicalFieldSpecMap.put(columnName, fieldSpec);
+    }
   }
 
   @Deprecated
@@ -201,6 +284,9 @@ public final class Schema {
 
   public boolean removeField(String columnName) {
     FieldSpec existingFieldSpec = _fieldSpecMap.remove(columnName);
+    if (_physicalFieldSpecMap.containsKey(columnName)) {
+      _physicalFieldSpecMap.remove(columnName);
+    }
     if (existingFieldSpec != null) {
       FieldType fieldType = existingFieldSpec.getFieldType();
       switch (fieldType) {
@@ -261,6 +347,12 @@ public final class Schema {
     return _fieldSpecMap.values();
   }
 
+  @JsonIgnore
+  @Nonnull
+  public Collection<FieldSpec> getAllPhysicalFieldSpecs() {
+    return _physicalFieldSpecMap.values();
+  }
+
   public int size() {
     return _fieldSpecMap.size();
   }
@@ -328,6 +420,26 @@ public final class Schema {
   }
 
   /**
+    * method to be used when loading immutable realtime segment to get the hints for upsert schema metrics as
+   * they cannot be found with physical copy of data
+   */
+  @JsonIgnore
+  public void withSchemaHint(@Nullable Schema upsertSchema) {
+    if (upsertSchema == null || !upsertSchema.isTableForUpsert()) {
+      return;
+    } else {
+      this._updateSemantic = UPSERT_TABLE_CONFIG_KEY;
+      this._primaryKey = upsertSchema._primaryKey;
+      this._offsetKey = upsertSchema._offsetKey;
+      for (FieldSpec fieldSpec: upsertSchema.getAllFieldSpecs()) {
+        if (fieldSpec.isVirtualColumnField()) {
+          _fieldSpecMap.putIfAbsent(fieldSpec._name, fieldSpec);
+        }
+      }
+    }
+  }
+
+  /**
    * Returns a json representation of the schema.
    */
   public ObjectNode toJsonObject() {
@@ -357,6 +469,11 @@ public final class Schema {
       }
       jsonObject.set("dateTimeFieldSpecs", jsonArray);
     }
+    jsonObject.put("updateSemantic", _updateSemantic);
+    if (UPSERT_TABLE_CONFIG_KEY.equalsIgnoreCase(_updateSemantic)) {
+      jsonObject.put("primaryKey", _primaryKey);
+      jsonObject.put("offsetKey", _offsetKey);
+    }
     return jsonObject;
   }
 
@@ -650,4 +767,50 @@ public final class Schema {
     result = EqualityUtils.hashCodeOf(result, _dateTimeFieldSpecs);
     return result;
   }
+
+  public boolean isVirtualColumn(String columnName) {
+    return columnName.startsWith("$") || (getFieldSpecFor(columnName).getVirtualColumnProvider() != null
+        && !getFieldSpecFor(columnName).getVirtualColumnProvider().isEmpty());
+  }
+
+
+  @JsonIgnore
+  public static byte[] getByteArrayFromField(Object value, DimensionFieldSpec fieldSpec) {
+    switch (fieldSpec.getDataType()) {
+      case INT:
+        return ByteBuffer.allocate(4).putInt((int)value).array();
+      case LONG:
+        return ByteBuffer.allocate(8).putLong((long)value).array();
+      case FLOAT:
+        return ByteBuffer.allocate(4).putFloat((float)value).array();
+      case DOUBLE:
+        return ByteBuffer.allocate(8).putDouble((double)value).array();
+      case STRING:
+        return ((String) value).getBytes(StandardCharsets.UTF_8);
+      case BYTES:
+        return (byte[]) value;
+      default:
+        throw new RuntimeException("unrecognized field spec format" + fieldSpec.getDataType());
+    }
+  }
+
+  @JsonIgnore
+  public static Object getValueFromBytes(byte[] bytes, DimensionFieldSpec fieldSpec) {
+    switch (fieldSpec.getDataType()) {
+      case INT:
+        return ByteBuffer.wrap(bytes).asIntBuffer().get();
+      case LONG:
+        return ByteBuffer.wrap(bytes).asLongBuffer().get();
+      case FLOAT:
+        return ByteBuffer.wrap(bytes).asFloatBuffer().get();
+      case DOUBLE:
+        return ByteBuffer.wrap(bytes).asDoubleBuffer().get();
+      case STRING:
+        return new String(bytes, StandardCharsets.UTF_8);
+      case BYTES:
+        return bytes;
+      default:
+        throw new RuntimeException("unrecognized field spec format" + fieldSpec.getDataType());
+    }
+  }
 }
diff --git a/pom.xml b/pom.xml
index a8ef872..a6c187d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -131,6 +131,9 @@
     <snappy-java.version>1.1.1.7</snappy-java.version>
     <log4j.version>2.11.2</log4j.version>
 
+    <!-- dependency for upsert component -->
+    <rocks-db.version>5.13.4</rocks-db.version>
+
     <!-- Sets the VM argument line used when unit tests are run. -->
     <argLine>-Xms4g -Xmx4g -XX:MaxPermSize=512m -XX:MaxDirectMemorySize=10g</argLine>
 
@@ -678,6 +681,12 @@
         <groupId>org.webjars</groupId>
         <artifactId>swagger-ui</artifactId>
         <version>2.2.2</version>
+        <exclusions>
+          <exclusion>
+            <groupId>javax.ws.rs</groupId>
+            <artifactId>jsr311-api</artifactId>
+          </exclusion>
+        </exclusions>
       </dependency>
       <dependency>
         <groupId>com.clearspring.analytics</groupId>
@@ -919,6 +928,18 @@
         <artifactId>commons-logging</artifactId>
         <version>${commons-logging.version}</version>
       </dependency>
+      <!-- upsert related config -->
+      <dependency>
+        <groupId>com.github.tomakehurst</groupId>
+        <artifactId>wiremock-jre8</artifactId>
+        <version>2.22.0</version>
+        <scope>test</scope>
+      </dependency>
+      <dependency>
+        <groupId>org.rocksdb</groupId>
+        <artifactId>rocksdbjni</artifactId>
+        <version>${rocks-db.version}</version>
+      </dependency>
     </dependencies>
   </dependencyManagement>
   <build>


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org