You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kylin.apache.org by bi...@apache.org on 2017/01/17 14:45:34 UTC

[01/10] kylin git commit: minor, fix null_counter datatype in TableExtDesc [Forced Update!]

Repository: kylin
Updated Branches:
  refs/heads/KYLIN-2394 d011f7ac7 -> fe599e788 (forced update)


minor, fix null_counter datatype in TableExtDesc

Signed-off-by: shaofengshi <sh...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/4625b059
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/4625b059
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/4625b059

Branch: refs/heads/KYLIN-2394
Commit: 4625b059ba5f55e1b938483297c18884aa17f6da
Parents: 4bc31de
Author: Cheng Wang <ch...@kyligence.io>
Authored: Mon Jan 16 17:10:40 2017 +0800
Committer: shaofengshi <sh...@apache.org>
Committed: Mon Jan 16 17:18:05 2017 +0800

----------------------------------------------------------------------
 .../java/org/apache/kylin/metadata/model/TableExtDesc.java   | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/4625b059/core-metadata/src/main/java/org/apache/kylin/metadata/model/TableExtDesc.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/metadata/model/TableExtDesc.java b/core-metadata/src/main/java/org/apache/kylin/metadata/model/TableExtDesc.java
index 7ed3368..18fefc2 100644
--- a/core-metadata/src/main/java/org/apache/kylin/metadata/model/TableExtDesc.java
+++ b/core-metadata/src/main/java/org/apache/kylin/metadata/model/TableExtDesc.java
@@ -200,8 +200,8 @@ public class TableExtDesc extends RootPersistentEntity {
         private String minLengthValue;
 
         @JsonProperty("null_count")
-        private int nullCount;
-        
+        private long nullCount;
+
         @JsonProperty("cardinality")
         private long cardinality;
 
@@ -260,11 +260,11 @@ public class TableExtDesc extends RootPersistentEntity {
             this.minLengthValue = minLenValue;
         }
 
-        public int getNullCount() {
+        public long getNullCount() {
             return nullCount;
         }
 
-        public void setNullCount(int nullCount) {
+        public void setNullCount(long nullCount) {
             this.nullCount = nullCount;
         }
     }


[03/10] kylin git commit: KYLIN-2396 fix ci

Posted by bi...@apache.org.
KYLIN-2396 fix ci


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/e20e2b2e
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/e20e2b2e
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/e20e2b2e

Branch: refs/heads/KYLIN-2394
Commit: e20e2b2e82de5318edaf123b11d72267b7ef1ea1
Parents: 95d4412
Author: lidongsjtu <li...@apache.org>
Authored: Mon Jan 16 22:39:58 2017 +0800
Committer: lidongsjtu <li...@apache.org>
Committed: Mon Jan 16 22:39:58 2017 +0800

----------------------------------------------------------------------
 .../src/test/java/org/apache/kylin/query/ITKylinQueryTest.java     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/e20e2b2e/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
----------------------------------------------------------------------
diff --git a/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java b/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
index 02134d4..87ddcb8 100644
--- a/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
+++ b/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
@@ -400,6 +400,6 @@ public class ITKylinQueryTest extends KylinTestBase {
 
     @Test
     public void testPercentileQuery() throws Exception {
-        batchExecuteQuery("src/test/resources/query/sql_percentile");
+        batchExecuteQuery(getQueryFolderPrefix() + "src/test/resources/query/sql_percentile");
     }
 }


[06/10] kylin git commit: minor, fix findFristTable fact table filter in DataModelDesc

Posted by bi...@apache.org.
minor, fix findFristTable fact table filter in DataModelDesc


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/f1826704
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/f1826704
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/f1826704

Branch: refs/heads/KYLIN-2394
Commit: f18267043df55c2e8a6a378e126a4fafa302f3c8
Parents: 576d2dd
Author: Billy Liu <bi...@apache.org>
Authored: Tue Jan 17 13:38:39 2017 +0800
Committer: Billy Liu <bi...@apache.org>
Committed: Tue Jan 17 13:38:39 2017 +0800

----------------------------------------------------------------------
 .../java/org/apache/kylin/metadata/model/DataModelDesc.java   | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/f1826704/core-metadata/src/main/java/org/apache/kylin/metadata/model/DataModelDesc.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/metadata/model/DataModelDesc.java b/core-metadata/src/main/java/org/apache/kylin/metadata/model/DataModelDesc.java
index 571b196..cc599a4 100644
--- a/core-metadata/src/main/java/org/apache/kylin/metadata/model/DataModelDesc.java
+++ b/core-metadata/src/main/java/org/apache/kylin/metadata/model/DataModelDesc.java
@@ -273,11 +273,16 @@ public class DataModelDesc extends RootPersistentEntity {
         if (rootFactTableRef.getTableIdentity().equals(tableIdentity))
             return rootFactTableRef;
 
+        for (TableRef fact : factTableRefs) {
+            if (fact.getTableIdentity().equals(tableIdentity))
+                return fact;
+        }
+
         for (TableRef lookup : lookupTableRefs) {
             if (lookup.getTableIdentity().equals(tableIdentity))
                 return lookup;
         }
-        throw new IllegalArgumentException("Table not found by " + tableIdentity);
+        throw new IllegalArgumentException("Table not found by " + tableIdentity + " in model " + name);
     }
 
     public void init(KylinConfig config, Map<String, TableDesc> tables) {


[04/10] kylin git commit: KYLIN-2400 remove byte[] interface in dictionary

Posted by bi...@apache.org.
KYLIN-2400 remove byte[] interface in dictionary

Signed-off-by: Li Yang <li...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/e769bfa0
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/e769bfa0
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/e769bfa0

Branch: refs/heads/KYLIN-2394
Commit: e769bfa004e9d548c5a042f02765cc093ce70ec1
Parents: e20e2b2
Author: xiefan46 <95...@qq.com>
Authored: Mon Jan 9 19:11:39 2017 +0800
Committer: Li Yang <li...@apache.org>
Committed: Tue Jan 17 10:54:22 2017 +0800

----------------------------------------------------------------------
 .../apache/kylin/common/util/Dictionary.java    | 46 ++++----------------
 .../apache/kylin/dict/AppendTrieDictionary.java | 19 ++++----
 .../org/apache/kylin/dict/CacheDictionary.java  | 13 ++++--
 .../apache/kylin/dict/DateStrDictionary.java    | 33 --------------
 .../apache/kylin/dict/DictionaryGenerator.java  |  2 +-
 .../org/apache/kylin/dict/NumberDictionary.java | 30 +------------
 .../kylin/dict/NumberDictionaryBuilder.java     |  8 ----
 .../apache/kylin/dict/TimeStrDictionary.java    | 29 ------------
 .../org/apache/kylin/dict/TrieDictionary.java   |  7 ++-
 .../kylin/dict/TrieDictionaryBuilder.java       |  2 +-
 .../apache/kylin/dict/TrieDictionaryForest.java | 27 +++---------
 .../kylin/dict/TrieDictionaryForestBuilder.java |  2 +-
 .../kylin/dict/AppendTrieDictionaryTest.java    | 10 ++---
 .../kylin/dict/DateStrDictionaryTest.java       |  3 --
 .../MultipleDictionaryValueEnumeratorTest.java  | 14 ------
 .../apache/kylin/dict/NumberDictionaryTest.java |  4 +-
 .../kylin/dict/TimeStrDictionaryTest.java       |  9 +++-
 .../dict/TrieDictionaryForestBenchmark.java     | 14 ++----
 .../kylin/dict/TrieDictionaryForestTest.java    | 11 ++---
 .../apache/kylin/dict/TrieDictionaryTest.java   | 19 ++++----
 .../kylin/measure/bitmap/BitmapMeasureType.java | 11 +++--
 .../kylin/measure/raw/RawMeasureType.java       |  7 ++-
 .../storage/gtrecord/DictGridTableTest.java     |  3 +-
 .../engine/mr/steps/MergeCuboidMapper.java      | 11 ++---
 .../mr/steps/NumberDictionaryForestTest.java    | 17 +++-----
 25 files changed, 92 insertions(+), 259 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
----------------------------------------------------------------------
diff --git a/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java b/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
index 1e172bc..9d675f9 100644
--- a/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
+++ b/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
@@ -94,8 +94,13 @@ abstract public class Dictionary<T> implements Serializable {
     final public int getIdFromValue(T value, int roundingFlag) throws IllegalArgumentException {
         if (isNullObjectForm(value))
             return nullId();
-        else
-            return getIdFromValueImpl(value, roundingFlag);
+        else {
+            int id = getIdFromValueImpl(value, roundingFlag);
+            if(id == -1){
+                throw new IllegalArgumentException("Value : " + value + "no exists");
+            }
+            return id;
+        }
     }
 
     final public boolean containsValue(T value) throws IllegalArgumentException {
@@ -136,9 +141,7 @@ abstract public class Dictionary<T> implements Serializable {
      * Convenient form of
      * <code>getIdFromValueBytes(value, offset, len, 0)</code>
      */
-    final public int getIdFromValueBytes(byte[] value, int offset, int len) throws IllegalArgumentException {
-        return getIdFromValueBytes(value, offset, len, 0);
-    }
+
 
     /**
      * A lower level API, return ID integer from raw value bytes. In case of not found 
@@ -153,31 +156,6 @@ abstract public class Dictionary<T> implements Serializable {
      *             if value is not found in dictionary and rounding is off;
      *             or if rounding cannot find a smaller or bigger ID
      */
-    final public int getIdFromValueBytes(byte[] value, int offset, int len, int roundingFlag) throws IllegalArgumentException {
-        if (isNullByteForm(value, offset, len))
-            return nullId();
-        else {
-            int id = getIdFromValueBytesImpl(value, offset, len, roundingFlag);
-            if (id == -1)
-                throw new IllegalArgumentException("Value '" + Bytes.toString(value, offset, len) + "' (" + Bytes.toStringBinary(value, offset, len) + ") not exists!");
-            return id;
-        }
-    }
-
-    protected boolean isNullByteForm(byte[] value, int offset, int len) {
-        return value == null;
-    }
-
-    abstract protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag);
-
-    final public byte[] getValueBytesFromId(int id) {
-        if (isNullId(id))
-            return BytesUtil.EMPTY_BYTE_ARRAY;
-        else
-            return getValueBytesFromIdImpl(id);
-    }
-
-    abstract protected byte[] getValueBytesFromIdImpl(int id);
 
     /**
      * A lower level API, get byte values from ID, return the number of bytes
@@ -189,14 +167,6 @@ abstract public class Dictionary<T> implements Serializable {
      * @throws IllegalArgumentException
      *             if ID is not found in dictionary
      */
-    final public int getValueBytesFromId(int id, byte[] returnValue, int offset) throws IllegalArgumentException {
-        if (isNullId(id))
-            return -1;
-        else
-            return getValueBytesFromIdImpl(id, returnValue, offset);
-    }
-
-    abstract protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset);
 
     abstract public void dump(PrintStream out);
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java b/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
index b797167..3aef967 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
@@ -97,6 +97,8 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
         enableCache();
     }
 
+
+
     public void initParams(String baseDir, int baseId, int maxId, int maxValueLength, int nValues, BytesConverter bytesConverter) throws IOException {
         this.baseDir = baseDir;
         this.baseId = baseId;
@@ -1113,7 +1115,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
     }
 
     @Override
-    protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) {
+    protected int getIdFromValueBytesWithoutCache(byte[] value, int offset, int len, int roundingFlag) {
         if (dictSliceMap.isEmpty()) {
             return -1;
         }
@@ -1129,6 +1131,11 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
     }
 
     @Override
+    protected byte[] getValueBytesFromIdWithoutCache(int id) {
+        throw new UnsupportedOperationException("AppendTrieDictionary can't retrive value from id");
+    }
+
+    @Override
     public int getMinId() {
         return baseId;
     }
@@ -1149,16 +1156,6 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
     }
 
 
-    @Override
-    protected byte[] getValueBytesFromIdImpl(int id) {
-        throw new UnsupportedOperationException("AppendTrieDictionary can't retrive value from id");
-    }
-
-    @Override
-    protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset) {
-        throw new UnsupportedOperationException("AppendTrieDictionary can't retrive value from id");
-    }
-
     public void flushIndex(CachedTreeMap dictSliceMap, boolean keepAppend) throws IOException {
         try (FSDataOutputStream indexOut = dictSliceMap.openIndexOutput()) {
             indexOut.writeInt(baseId);

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/CacheDictionary.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/CacheDictionary.java b/core-dictionary/src/main/java/org/apache/kylin/dict/CacheDictionary.java
index b2bad53..156971d 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/CacheDictionary.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/CacheDictionary.java
@@ -52,13 +52,13 @@ public abstract class CacheDictionary<T> extends Dictionary<T> {
                 if (id != null)
                     return id.intValue();
                 byte[] valueBytes = bytesConvert.convertToBytes(value);
-                id = getIdFromValueBytes(valueBytes, 0, valueBytes.length, roundingFlag);
+                id = getIdFromValueBytesWithoutCache(valueBytes, 0, valueBytes.length, roundingFlag);
                 cache.put(value, id);
                 return id;
             }
         }
         byte[] valueBytes = bytesConvert.convertToBytes(value);
-        return getIdFromValueBytes(valueBytes, 0, valueBytes.length, roundingFlag);
+        return getIdFromValueBytesWithoutCache(valueBytes, 0, valueBytes.length, roundingFlag);
     }
 
     //id --> value
@@ -70,13 +70,13 @@ public abstract class CacheDictionary<T> extends Dictionary<T> {
                 int seq = calcSeqNoFromId(id);
                 if (cache[seq] != null)
                     return (T) cache[seq];
-                byte[] valueBytes = getValueBytesFromIdImpl(id);
+                byte[] valueBytes = getValueBytesFromIdWithoutCache(id);
                 T value = bytesConvert.convertFromBytes(valueBytes, 0, valueBytes.length);
                 cache[seq] = value;
                 return value;
             }
         }
-        byte[] valueBytes = getValueBytesFromIdImpl(id);
+        byte[] valueBytes = getValueBytesFromIdWithoutCache(id);
         return bytesConvert.convertFromBytes(valueBytes, 0, valueBytes.length);
     }
 
@@ -99,4 +99,9 @@ public abstract class CacheDictionary<T> extends Dictionary<T> {
         this.valueToIdCache = null;
         this.idToValueCache = null;
     }
+
+    abstract protected byte[] getValueBytesFromIdWithoutCache(int id);
+
+    abstract protected int getIdFromValueBytesWithoutCache(byte[] valueBytes, int offset, int length, int roundingFlag);
+
 }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/DateStrDictionary.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/DateStrDictionary.java b/core-dictionary/src/main/java/org/apache/kylin/dict/DateStrDictionary.java
index 29bbee2..56b4994 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/DateStrDictionary.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/DateStrDictionary.java
@@ -26,7 +26,6 @@ import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.IOException;
 import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
 import java.util.Date;
 
 import org.apache.commons.lang.StringUtils;
@@ -84,10 +83,6 @@ public class DateStrDictionary extends Dictionary<String> {
         return pattern.length();
     }
 
-    @Override
-    protected boolean isNullByteForm(byte[] value, int offset, int len) {
-        return value == null || len == 0;
-    }
 
     @Override
     final protected int getIdFromValueImpl(String value, int roundFlag) {
@@ -107,34 +102,6 @@ public class DateStrDictionary extends Dictionary<String> {
         return dateToString(new Date(millis), pattern);
     }
 
-    @Override
-    final protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) {
-        try {
-            return getIdFromValue(new String(value, offset, len, "ISO-8859-1"));
-        } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e); // never happen
-        }
-    }
-
-    @Override
-    final protected byte[] getValueBytesFromIdImpl(int id) {
-        String date = getValueFromId(id);
-        byte[] bytes;
-        try {
-            bytes = date.getBytes("ISO-8859-1");
-        } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e); // never happen
-        }
-        return bytes;
-    }
-
-    @Override
-    final protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset) {
-        byte[] bytes = getValueBytesFromIdImpl(id);
-        System.arraycopy(bytes, 0, returnValue, offset, bytes.length);
-        return bytes.length;
-    }
-
     private int calcIdFromSeqNo(int seq) {
         return seq < 0 ? seq : baseId + seq;
     }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java b/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
index 6f4f2c4..c23e7b5 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
@@ -227,7 +227,7 @@ public class DictionaryGenerator {
         @Override
         public void init(DictionaryInfo info, int baseId) throws IOException {
             this.baseId = baseId;
-            this.builder = new NumberDictionaryBuilder(new StringBytesConverter());
+            this.builder = new NumberDictionaryBuilder(new NumberDictionaryForestBuilder.Number2BytesConverter());
         }
         
         @Override

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionary.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionary.java b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionary.java
index 9458e9d..c55937d 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionary.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionary.java
@@ -175,37 +175,9 @@ public class NumberDictionary<T> extends TrieDictionary<T> {
     }
 
     @Override
-    protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) {
-        NumberBytesCodec codec = getCodec();
-        codec.encodeNumber(value, offset, len);
-        return super.getIdFromValueBytesImpl(codec.buf, codec.bufOffset, codec.bufLen, roundingFlag);
-    }
-
-    @Override
     protected boolean isNullObjectForm(T value) {
         return value == null || value.equals("");
     }
+    
 
-    @Override
-    protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset) {
-        NumberBytesCodec codec = getCodec();
-        codec.bufOffset = 0;
-        codec.bufLen = super.getValueBytesFromIdImpl(id, codec.buf, 0);
-        return codec.decodeNumber(returnValue, offset);
-    }
-
-
-    public static void main(String[] args) throws Exception {
-        NumberDictionaryBuilder<String> b = new NumberDictionaryBuilder<String>(new StringBytesConverter());
-        b.addValue("10");
-        b.addValue("100");
-        b.addValue("40");
-        b.addValue("7");
-        TrieDictionary<String> dict = b.build(0);
-
-        //dict.enableIdToValueBytesCache();
-        for (int i = 0; i <= dict.getMaxId(); i++) {
-            System.out.println(Bytes.toString(dict.getValueBytesFromId(i)));
-        }
-    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
index 68a05d4..b9e94414 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
@@ -18,7 +18,6 @@
 
 package org.apache.kylin.dict;
 
-import org.apache.kylin.common.util.Bytes;
 
 /**
  * Use <code>NumberDictionaryForestBuilder</code> instead.
@@ -28,18 +27,11 @@ import org.apache.kylin.common.util.Bytes;
 @Deprecated
 public class NumberDictionaryBuilder<T> extends TrieDictionaryBuilder<T> {
 
-    NumberDictionary.NumberBytesCodec codec = new NumberDictionary.NumberBytesCodec(NumberDictionary.MAX_DIGITS_BEFORE_DECIMAL_POINT);
 
     public NumberDictionaryBuilder(BytesConverter<T> bytesConverter) {
         super(bytesConverter);
     }
 
-    @Override
-    void addValue(byte[] value) {
-        codec.encodeNumber(value, 0, value.length);
-        byte[] copy = Bytes.copy(codec.buf, codec.bufOffset, codec.bufLen);
-        super.addValue(copy);
-    }
 
     public NumberDictionary<T> build(int baseId) {
         byte[] trieBytes = buildTrieBytes(baseId);

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/TimeStrDictionary.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/TimeStrDictionary.java b/core-dictionary/src/main/java/org/apache/kylin/dict/TimeStrDictionary.java
index eabc9f1..d075ce1 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/TimeStrDictionary.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/TimeStrDictionary.java
@@ -22,7 +22,6 @@ import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.IOException;
 import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
 
 import org.apache.kylin.common.util.DateFormat;
 import org.apache.kylin.common.util.Dictionary;
@@ -85,34 +84,6 @@ public class TimeStrDictionary extends Dictionary<String> {
     }
 
     @Override
-    final protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) {
-        try {
-            return getIdFromValue(new String(value, offset, len, "ISO-8859-1"));
-        } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e); // never happen
-        }
-    }
-
-    @Override
-    final protected byte[] getValueBytesFromIdImpl(int id) {
-        String date = getValueFromId(id);
-        byte[] bytes;
-        try {
-            bytes = date.getBytes("ISO-8859-1");
-        } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e); // never happen
-        }
-        return bytes;
-    }
-
-    @Override
-    final protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset) {
-        byte[] bytes = getValueBytesFromIdImpl(id);
-        System.arraycopy(bytes, 0, returnValue, offset, bytes.length);
-        return bytes.length;
-    }
-
-    @Override
     public void dump(PrintStream out) {
         out.println(this.toString());
     }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionary.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionary.java b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionary.java
index 8e7f5dc..9b84734 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionary.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionary.java
@@ -141,7 +141,7 @@ public class TrieDictionary<T> extends CacheDictionary<T> {
 
 
     @Override
-    protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) {
+    protected int getIdFromValueBytesWithoutCache(byte[] value, int offset, int len, int roundingFlag) {
         int seq = lookupSeqNoFromValue(headSize, value, offset, offset + len, roundingFlag);
         int id = calcIdFromSeqNo(seq);
         if (id < 0)
@@ -236,7 +236,7 @@ public class TrieDictionary<T> extends CacheDictionary<T> {
 
 
     @Override
-    protected byte[] getValueBytesFromIdImpl(int id) {
+    protected byte[] getValueBytesFromIdWithoutCache(int id) {
         byte[] buf = new byte[maxValueLength];
         int len = getValueBytesFromIdImpl(id, buf, 0);
 
@@ -249,7 +249,6 @@ public class TrieDictionary<T> extends CacheDictionary<T> {
         }
     }
 
-    @Override
     protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset) {
         int seq = calcSeqNoFromId(id);
         return lookupValueFromSeqNo(headSize, seq, returnValue, offset);
@@ -425,7 +424,7 @@ public class TrieDictionary<T> extends CacheDictionary<T> {
 
         //dict2.enableIdToValueBytesCache();
         for (int i = 0; i <= dict.getMaxId(); i++) {
-            System.out.println(Bytes.toString(dict.getValueBytesFromId(i)));
+            System.out.println(Bytes.toString(dict.getValueBytesFromIdWithoutCache(i)));
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryBuilder.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryBuilder.java b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryBuilder.java
index 598865b..102c49e 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryBuilder.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryBuilder.java
@@ -74,7 +74,7 @@ public class TrieDictionaryBuilder<T> {
     // ============================================================================
 
     private Node root;
-    private BytesConverter<T> bytesConverter;
+    protected BytesConverter<T> bytesConverter;
 
     public TrieDictionaryBuilder(BytesConverter<T> bytesConverter) {
         this.root = new Node(new byte[0], false);

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
index 69b4b9c..d1b5a99 100755
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
@@ -104,15 +104,7 @@ public class TrieDictionaryForest<T> extends CacheDictionary<T> {
     }
 
     @Override
-    protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) throws IllegalArgumentException {
-
-        int result = _getIdFromValueBytesImpl(value, offset, len, roundingFlag);
-        //logger.info("{} => {}, rounding {}", bytesConvert.convertFromBytes(value, offset, len), result, roundingFlag);
-        return result;
-    }
-
-    // id = tree_inner_offset + accumulate_offset + baseId
-    protected int _getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) throws IllegalArgumentException {
+    protected int getIdFromValueBytesWithoutCache(byte[] value, int offset, int len, int roundingFlag) throws IllegalArgumentException {
         int index;
         if (trees.size() == 1) {
             index = 0;
@@ -136,27 +128,20 @@ public class TrieDictionaryForest<T> extends CacheDictionary<T> {
             }
         }
         TrieDictionary<T> tree = trees.get(index);
-        int id = tree.getIdFromValueBytes(value, offset, len, roundingFlag);
+        int id = tree.getIdFromValueBytesWithoutCache(value, offset, len, roundingFlag);
+        if(id == -1)
+            throw new IllegalArgumentException("Value '" + Bytes.toString(value, offset, len) + "' (" + Bytes.toStringBinary(value, offset, len) + ") not exists!");
         id = id + accuOffset.get(index);
         id += baseId;
         return id;
     }
 
     @Override
-    protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset) throws IllegalArgumentException {
-        int index = (trees.size() == 1) ? 0 : findIndexById(id);
-        int treeInnerOffset = getTreeInnerOffset(id, index);
-        TrieDictionary<T> tree = trees.get(index);
-        int size = tree.getValueBytesFromIdImpl(treeInnerOffset, returnValue, offset);
-        return size;
-    }
-
-    @Override
-    protected byte[] getValueBytesFromIdImpl(int id) throws IllegalArgumentException {
+    protected byte[] getValueBytesFromIdWithoutCache(int id) throws IllegalArgumentException {
         int index = (trees.size() == 1) ? 0 : findIndexById(id);
         int treeInnerOffset = getTreeInnerOffset(id, index);
         TrieDictionary<T> tree = trees.get(index);
-        byte[] result = tree.getValueBytesFromId(treeInnerOffset);
+        byte[] result = tree.getValueBytesFromIdWithoutCache(treeInnerOffset);
         return result;
     }
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForestBuilder.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForestBuilder.java b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForestBuilder.java
index af2e302..69da472 100755
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForestBuilder.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForestBuilder.java
@@ -131,7 +131,7 @@ public class TrieDictionaryForestBuilder<T> {
         trees.add(tree);
         int minId = tree.getMinId();
         accuOffset.add(curOffset);
-        byte[] valueBytes = tree.getValueBytesFromId(minId);
+        byte[] valueBytes = tree.getValueBytesFromIdWithoutCache(minId);
         valueDivide.add(new ByteArray(valueBytes, 0, valueBytes.length));
         curOffset += (tree.getMaxId() + 1);
     }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/AppendTrieDictionaryTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/AppendTrieDictionaryTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/AppendTrieDictionaryTest.java
index 921925c..18913d0 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/AppendTrieDictionaryTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/AppendTrieDictionaryTest.java
@@ -180,7 +180,7 @@ public class AppendTrieDictionaryTest extends LocalFileMetadataTestCase {
         for (; checkIndex < firstAppend; checkIndex++) {
             String str = strList.get(checkIndex);
             byte[] bytes = converter.convertToBytes(str);
-            int id = dict.getIdFromValueBytesImpl(bytes, 0, bytes.length, 0);
+            int id = dict.getIdFromValueBytesWithoutCache(bytes, 0, bytes.length, 0);
             assertNotEquals(String.format("Value %s not exist", str), -1, id);
             assertFalse(String.format("Id %d for %s should be empty, but is %s", id, str, checkMap.get(id)), checkMap.containsKey(id) && !str.equals(checkMap.get(id)));
             checkMap.put(id, str);
@@ -200,7 +200,7 @@ public class AppendTrieDictionaryTest extends LocalFileMetadataTestCase {
         for (; checkIndex < secondAppend; checkIndex++) {
             String str = strList.get(checkIndex);
             byte[] bytes = converter.convertToBytes(str);
-            int id = dict.getIdFromValueBytesImpl(bytes, 0, bytes.length, 0);
+            int id = dict.getIdFromValueBytesWithoutCache(bytes, 0, bytes.length, 0);
             assertNotEquals(String.format("Value %s not exist", str), -1, id);
             if (checkIndex < firstAppend) {
                 assertEquals("Except id " + id + " for " + str + " but " + checkMap.get(id), str, checkMap.get(id));
@@ -224,7 +224,7 @@ public class AppendTrieDictionaryTest extends LocalFileMetadataTestCase {
         for (; checkIndex < strList.size(); checkIndex++) {
             String str = strList.get(checkIndex);
             byte[] bytes = converter.convertToBytes(str);
-            int id = dict.getIdFromValueBytesImpl(bytes, 0, bytes.length, 0);
+            int id = dict.getIdFromValueBytesWithoutCache(bytes, 0, bytes.length, 0);
             assertNotEquals(String.format("Value %s not exist", str), -1, id);
             if (checkIndex < secondAppend) {
                 assertEquals("Except id " + id + " for " + str + " but " + checkMap.get(id), str, checkMap.get(id));
@@ -237,7 +237,7 @@ public class AppendTrieDictionaryTest extends LocalFileMetadataTestCase {
         if (notfound != null) {
             for (String s : notfound) {
                 byte[] bytes = converter.convertToBytes(s);
-                int id = dict.getIdFromValueBytesImpl(bytes, 0, bytes.length, 0);
+                int id = dict.getIdFromValueBytesWithoutCache(bytes, 0, bytes.length, 0);
                 assertEquals(-1, id);
             }
         }
@@ -245,7 +245,7 @@ public class AppendTrieDictionaryTest extends LocalFileMetadataTestCase {
         dict = testSerialize(dict, converter);
         for (String str : strList) {
             byte[] bytes = converter.convertToBytes(str);
-            int id = dict.getIdFromValueBytesImpl(bytes, 0, bytes.length, 0);
+            int id = dict.getIdFromValueBytesWithoutCache(bytes, 0, bytes.length, 0);
             assertNotEquals(String.format("Value %s not exist", str), -1, id);
             assertEquals("Except id " + id + " for " + str + " but " + checkMap.get(id), str, checkMap.get(id));
         }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/DateStrDictionaryTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/DateStrDictionaryTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/DateStrDictionaryTest.java
index ffc8ceb..c6d2e05 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/DateStrDictionaryTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/DateStrDictionaryTest.java
@@ -66,9 +66,6 @@ public class DateStrDictionaryTest {
     public void testNull() {
         int nullId = dict.getIdFromValue(null);
         assertNull(dict.getValueFromId(nullId));
-        int nullId2 = dict.getIdFromValueBytes(null, 0, 0);
-        assertEquals(dict.getValueBytesFromId(nullId2, null, 0), -1);
-        assertEquals(nullId, nullId2);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/MultipleDictionaryValueEnumeratorTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/MultipleDictionaryValueEnumeratorTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/MultipleDictionaryValueEnumeratorTest.java
index 73e0935..2e90bcf 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/MultipleDictionaryValueEnumeratorTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/MultipleDictionaryValueEnumeratorTest.java
@@ -134,20 +134,6 @@ public class MultipleDictionaryValueEnumeratorTest {
             return "" + values[id];
         }
 
-        @Override
-        protected int getIdFromValueBytesImpl(byte[] value, int offset, int len, int roundingFlag) {
-            return 0;
-        }
-
-        @Override
-        protected byte[] getValueBytesFromIdImpl(int id) {
-            return null;
-        }
-
-        @Override
-        protected int getValueBytesFromIdImpl(int id, byte[] returnValue, int offset) {
-            return 0;
-        }
 
         @Override
         public void dump(PrintStream out) {}

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
index 23e925c..38f2648 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
@@ -59,7 +59,7 @@ public class NumberDictionaryTest extends LocalFileMetadataTestCase {
 
     @Test
     public void testMinMax() {
-        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<String>(new StringBytesConverter());
+        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<String>(new NumberDictionaryForestBuilder.Number2BytesConverter());
         builder.addValue("" + Long.MAX_VALUE);
         builder.addValue("" + Long.MIN_VALUE);
         NumberDictionary<String> dict = builder.build(0);
@@ -123,7 +123,7 @@ public class NumberDictionaryTest extends LocalFileMetadataTestCase {
         int n = 100;
 
         Set<BigDecimal> set = Sets.newHashSet();
-        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<String>(new StringBytesConverter());
+        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<String>(new NumberDictionaryForestBuilder.Number2BytesConverter());
         for (int i = 0; i < n; i++) {
             String num = randNumber();
             if (set.add(new BigDecimal(num))) {

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
index ce07a86..f981942 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
@@ -23,6 +23,8 @@ import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
+import static org.junit.Assert.fail;
+
 /**
  */
 public class TimeStrDictionaryTest {
@@ -62,7 +64,12 @@ public class TimeStrDictionaryTest {
 
     @Test
     public void testIllegal() {
-        Assert.assertEquals(-1, dict.getIdFromValue("2038-01-19 03:14:07"));
+        try{
+            dict.getIdFromValue("2038-01-19 03:14:07");
+            fail("should throw exception");
+        }catch (IllegalArgumentException e){
+            //correct
+        }
     }
 
     public void encodeDecode(String origin) {

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestBenchmark.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestBenchmark.java b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestBenchmark.java
index 0b4c0e3..adc1074 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestBenchmark.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestBenchmark.java
@@ -25,7 +25,6 @@ import org.junit.Test;
 
 import java.util.ArrayList;
 import java.util.Collections;
-import java.util.List;
 import java.util.Random;
 import java.util.UUID;
 
@@ -123,7 +122,8 @@ public class TrieDictionaryForestBenchmark {
         int step = 1;
         for (int i = 0; i < testTimes; i++) {
             for (int j = 0; j < cardnality; j++) {
-                step |= dict.getValueBytesFromId(j).length;
+                //step |= dict.getValueBytesFromId(j).length;
+                step |= dict.getValueFromId(j).length();
             }
         }
         return System.currentTimeMillis() - startTime;
@@ -135,8 +135,7 @@ public class TrieDictionaryForestBenchmark {
         byte[] returnValue = new byte[2048];
         for (int i = 0; i < testTimes; i++) {
             for (int j = 0; j < cardnality; j++) {
-                int size = dict.getValueBytesFromId(j, returnValue, 0);
-                step |= size;
+                step |= dict.getValueFromId(j).length();
             }
         }
         return System.currentTimeMillis() - startTime;
@@ -154,16 +153,11 @@ public class TrieDictionaryForestBenchmark {
     }
 
     private long runQueryIdByValueBytes(ArrayList<String> rawData, Dictionary<String> dict, int cardnality, int testTimes) {
-        List<byte[]> testBytes = new ArrayList<>();
-        StringBytesConverter converter = new StringBytesConverter();
-        for (int i = 0; i < cardnality; i++) {
-            testBytes.add(converter.convertToBytes(rawData.get(i)));
-        }
         long startTime = System.currentTimeMillis();
         int step = 1;
         for (int i = 0; i < testTimes; i++) {
             for (int j = 0; j < cardnality; j++) {
-                step |= dict.getIdFromValueBytes(testBytes.get(j), 0, testBytes.get(j).length);
+                step |= dict.getIdFromValue(rawData.get(j));
             }
         }
         return System.currentTimeMillis() - startTime;

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
index 68cf301..c7fb9c4 100755
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
@@ -641,7 +641,7 @@ public class TrieDictionaryForestTest {
         System.out.println("max memory:" + Runtime.getRuntime().maxMemory());
         System.gc();
         Thread.currentThread().sleep(1000);
-        NumberDictionaryBuilder<String> b = new NumberDictionaryBuilder<>(new StringBytesConverter());
+        NumberDictionaryBuilder<String> b = new NumberDictionaryBuilder<>(new NumberDictionaryForestBuilder.Number2BytesConverter());
         int k = 0;
         while (true) {
             b.addValue(k + "");
@@ -820,7 +820,7 @@ public class TrieDictionaryForestTest {
         for (int i = 0; i < times; i++) {
             for (int j = 0; j < n; j++) {
                 //System.out.println("looking for value:"+new String(array[j]));
-                keep |= dict.getIdFromValueBytes(array[j], 0, array[j].length);
+                keep |= dict.getIdFromValueBytesWithoutCache(array[j], 0, array[j].length, 0);
             }
         }
         long timeValueToIdByDict = System.currentTimeMillis() - start;
@@ -845,7 +845,7 @@ public class TrieDictionaryForestTest {
         start = System.currentTimeMillis();
         for (int i = 0; i < times; i++) {
             for (int j = 0; j < n; j++) {
-                keep |= dict.getValueBytesFromId(j, valueBytes, 0);
+                keep |= dict.getValueBytesFromIdWithoutCache(j).length;
             }
         }
         long timeIdToValueByDict = System.currentTimeMillis() - start;
@@ -884,7 +884,7 @@ public class TrieDictionaryForestTest {
             for (String s : notFound) {
                 try {
                     int nullId = dict.getIdFromValue(s);
-                    //System.out.println("null value id:" + nullId);
+                    System.out.println("null value id:" + nullId);
                     fail("For not found value '" + s + "', IllegalArgumentException is expected");
                 } catch (IllegalArgumentException e) {
                     // good
@@ -905,9 +905,6 @@ public class TrieDictionaryForestTest {
         // test null value
         int nullId = dict.getIdFromValue(null);
         assertNull(dict.getValueFromId(nullId));
-        int nullId2 = dict.getIdFromValueBytes(null, 0, 0);
-        assertEquals(dict.getValueBytesFromId(nullId2, null, 0), -1);
-        assertEquals(nullId, nullId2);
     }
 
     private Map<String, Integer> rightIdMap(int baseId, ArrayList<String> strs) {

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryTest.java
index a87d7cb..22a93a0 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryTest.java
@@ -47,7 +47,7 @@ public class TrieDictionaryTest {
         int count = (int) (Integer.MAX_VALUE * 0.8 / 64);
         benchmarkStringDictionary(new RandomStrings(count));
     }
-    
+
     private static class RandomStrings implements Iterable<String> {
         final private int size;
 
@@ -55,7 +55,7 @@ public class TrieDictionaryTest {
             this.size = size;
             System.out.println("size = " + size);
         }
-        
+
         @Override
         public Iterator<String> iterator() {
             return new Iterator<String>() {
@@ -71,11 +71,11 @@ public class TrieDictionaryTest {
                 public String next() {
                     if (hasNext() == false)
                         throw new NoSuchElementException();
-                    
+
                     i++;
                     if (i % 1000000 == 0)
                         System.out.println(i);
-                    
+
                     return nextString();
                 }
 
@@ -225,7 +225,7 @@ public class TrieDictionaryTest {
         TrieDictionaryBuilder<String> b = newDictBuilder(str);
         b.stats().print();
         TrieDictionary<String> dict = b.build(0);
-        
+
         TreeSet<String> set = new TreeSet<String>();
         for (String s : str) {
             set.add(s);
@@ -282,7 +282,7 @@ public class TrieDictionaryTest {
         start = System.currentTimeMillis();
         for (int i = 0; i < times; i++) {
             for (int j = 0; j < n; j++) {
-                keep |= dict.getIdFromValueBytes(array[j], 0, array[j].length);
+                keep |= dict.getIdFromValueBytesWithoutCache(array[j], 0, array[j].length, 0);
             }
         }
         long timeValueToIdByDict = System.currentTimeMillis() - start;
@@ -304,12 +304,12 @@ public class TrieDictionaryTest {
         start = System.currentTimeMillis();
         for (int i = 0; i < times; i++) {
             for (int j = 0; j < n; j++) {
-                keep |= dict.getValueBytesFromId(j, valueBytes, 0);
+                keep |= dict.getValueBytesFromIdWithoutCache(j).length;
             }
         }
         long timeIdToValueByDict = System.currentTimeMillis() - start;
         System.out.println(timeIdToValueByDict);
-        
+
         return keep;
     }
 
@@ -350,9 +350,6 @@ public class TrieDictionaryTest {
         // test null value
         int nullId = dict.getIdFromValue(null);
         assertNull(dict.getValueFromId(nullId));
-        int nullId2 = dict.getIdFromValueBytes(null, 0, 0);
-        assertEquals(dict.getValueBytesFromId(nullId2, null, 0), -1);
-        assertEquals(nullId, nullId2);
     }
 
     private static TrieDictionary<String> testSerialize(TrieDictionary<String> dict) {

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapMeasureType.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapMeasureType.java b/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapMeasureType.java
index b6f1975..de2a34a 100644
--- a/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapMeasureType.java
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapMeasureType.java
@@ -18,6 +18,8 @@
 
 package org.apache.kylin.measure.bitmap;
 
+import static com.google.common.base.Preconditions.checkArgument;
+
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
@@ -38,8 +40,6 @@ import org.apache.kylin.metadata.realization.SQLDigest.SQLCall;
 
 import com.google.common.collect.ImmutableMap;
 
-import static com.google.common.base.Preconditions.checkArgument;
-
 /**
  * Created by sunyerui on 15/12/10.
  */
@@ -133,14 +133,13 @@ public class BitmapMeasureType extends MeasureType<BitmapCounter> {
                 Dictionary<String> mergedDict = newDicts.get(colRef);
 
                 MutableBitmapCounter retValue = new MutableBitmapCounter();
-                byte[] literal = new byte[sourceDict.getSizeOfValue()];
                 for (int id : value) {
                     int newId;
-                    int size = sourceDict.getValueBytesFromId(id, literal, 0);
-                    if (size < 0) {
+                    String v = sourceDict.getValueFromId(id);
+                    if (v == null) {
                         newId = mergedDict.nullId();
                     } else {
-                        newId = mergedDict.getIdFromValueBytes(literal, 0, size);
+                        newId = mergedDict.getIdFromValue(v);
                     }
                     retValue.add(newId);
                 }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java b/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
index a5bb06b..3b6e659 100644
--- a/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
@@ -133,17 +133,16 @@ public class RawMeasureType extends MeasureType<List<ByteArray>> {
 
                 int valueSize = value.size();
                 byte[] newIdBuf = new byte[valueSize * mergedDict.getSizeOfId()];
-                byte[] literal = new byte[sourceDict.getSizeOfValue()];
 
                 int bufOffset = 0;
                 for (ByteArray c : value) {
                     int oldId = BytesUtil.readUnsigned(c.array(), c.offset(), c.length());
                     int newId;
-                    int size = sourceDict.getValueBytesFromId(oldId, literal, 0);
-                    if (size < 0) {
+                    String v = sourceDict.getValueFromId(oldId);
+                    if (v == null) {
                         newId = mergedDict.nullId();
                     } else {
-                        newId = mergedDict.getIdFromValueBytes(literal, 0, size);
+                        newId = mergedDict.getIdFromValue(v);
                     }
                     BytesUtil.writeUnsigned(newId, newIdBuf, bufOffset, mergedDict.getSizeOfId());
                     c.set(newIdBuf, bufOffset, mergedDict.getSizeOfId());

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
----------------------------------------------------------------------
diff --git a/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java b/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
index fcd0182..ae186e2 100644
--- a/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
+++ b/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
@@ -35,6 +35,7 @@ import org.apache.kylin.common.util.LocalFileMetadataTestCase;
 import org.apache.kylin.common.util.Pair;
 import org.apache.kylin.cube.gridtable.CubeCodeSystem;
 import org.apache.kylin.dict.NumberDictionaryBuilder;
+import org.apache.kylin.dict.NumberDictionaryForestBuilder;
 import org.apache.kylin.dict.StringBytesConverter;
 import org.apache.kylin.dict.TrieDictionaryBuilder;
 import org.apache.kylin.dimension.DictionaryDimEnc;
@@ -601,7 +602,7 @@ public class DictGridTableTest extends LocalFileMetadataTestCase {
 
     @SuppressWarnings("rawtypes")
     private static Dictionary newDictionaryOfInteger() {
-        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<>(new StringBytesConverter());
+        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<>(new NumberDictionaryForestBuilder.Number2BytesConverter());
         builder.addValue("10");
         builder.addValue("20");
         builder.addValue("30");

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/MergeCuboidMapper.java
----------------------------------------------------------------------
diff --git a/engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/MergeCuboidMapper.java b/engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/MergeCuboidMapper.java
index a79d5aa..047e2b1 100644
--- a/engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/MergeCuboidMapper.java
+++ b/engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/MergeCuboidMapper.java
@@ -186,8 +186,8 @@ public class MergeCuboidMapper extends KylinMapper<Text, Text, Text, Text> {
             if (this.checkNeedMerging(col)) {
                 // if dictionary on fact table column, needs rewrite
                 DictionaryManager dictMgr = DictionaryManager.getInstance(config);
-                Dictionary<?> sourceDict = dictMgr.getDictionary(sourceCubeSegment.getDictResPath(col));
-                Dictionary<?> mergedDict = dictMgr.getDictionary(mergedCubeSegment.getDictResPath(col));
+                Dictionary<String> sourceDict = dictMgr.getDictionary(sourceCubeSegment.getDictResPath(col));
+                Dictionary<String> mergedDict = dictMgr.getDictionary(mergedCubeSegment.getDictResPath(col));
 
                 while (sourceDict.getSizeOfValue() > newKeyBodyBuf.length - bufOffset || //
                         mergedDict.getSizeOfValue() > newKeyBodyBuf.length - bufOffset || //
@@ -200,11 +200,12 @@ public class MergeCuboidMapper extends KylinMapper<Text, Text, Text, Text> {
                 int idInSourceDict = BytesUtil.readUnsigned(splittedByteses[useSplit].value, 0, splittedByteses[useSplit].length);
                 int idInMergedDict;
 
-                int size = sourceDict.getValueBytesFromId(idInSourceDict, newKeyBodyBuf, bufOffset);
-                if (size < 0) {
+                //int size = sourceDict.getValueBytesFromId(idInSourceDict, newKeyBodyBuf, bufOffset);
+                String v = sourceDict.getValueFromId(idInSourceDict);
+                if (v == null) {
                     idInMergedDict = mergedDict.nullId();
                 } else {
-                    idInMergedDict = mergedDict.getIdFromValueBytes(newKeyBodyBuf, bufOffset, size);
+                    idInMergedDict = mergedDict.getIdFromValue(v);
                 }
 
                 BytesUtil.writeUnsigned(idInMergedDict, newKeyBodyBuf, bufOffset, mergedDict.getSizeOfId());

http://git-wip-us.apache.org/repos/asf/kylin/blob/e769bfa0/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
----------------------------------------------------------------------
diff --git a/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java b/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
index f6664bf..72793f5 100644
--- a/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
+++ b/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
@@ -38,7 +38,6 @@ import org.apache.kylin.common.util.Bytes;
 import org.apache.kylin.dict.NumberDictionary;
 import org.apache.kylin.dict.NumberDictionaryBuilder;
 import org.apache.kylin.dict.NumberDictionaryForestBuilder;
-import org.apache.kylin.dict.StringBytesConverter;
 import org.apache.kylin.dict.TrieDictionaryForest;
 import org.apache.kylin.engine.mr.steps.SelfDefineSortableKey.TypeFlag;
 import org.junit.Ignore;
@@ -121,7 +120,7 @@ public class NumberDictionaryForestTest {
         TrieDictionaryForest<String> dict = b.build();
         dict.dump(System.out);
 
-        NumberDictionaryBuilder<String> b2 = new NumberDictionaryBuilder<>(new StringBytesConverter());
+        NumberDictionaryBuilder<String> b2 = new NumberDictionaryBuilder<>(new NumberDictionaryForestBuilder.Number2BytesConverter());
         for (String str : testData)
             b2.addValue(str);
         NumberDictionary<String> dict2 = b2.build(0);
@@ -148,22 +147,20 @@ public class NumberDictionaryForestTest {
         
         assertTrue(dict1.getSizeOfId() == dict2.getSizeOfId());
         assertTrue(dict1.getSizeOfValue() == dict2.getSizeOfValue());
-        
+
         byte[] buf = new byte[dict1.getSizeOfValue()];
-        
+
         {
-            int len = dict1.getValueBytesFromId(0, buf, 0);
-            int newId = dict2.getIdFromValueBytes(buf, 0, len);
+            int newId = dict2.getIdFromValue(dict1.getValueFromId(0));
             assertTrue(newId == 0);
         }
         {
-            int len = dict1.getValueBytesFromId(1, buf, 0);
-            int newId = dict2.getIdFromValueBytes(buf, 0, len);
+
+            int newId = dict2.getIdFromValue(dict1.getValueFromId(1));
             assertTrue(newId == 2);
         }
         {
-            int len = dict1.getValueBytesFromId(2, buf, 0);
-            int newId = dict2.getIdFromValueBytes(buf, 0, len);
+            int newId = dict2.getIdFromValue(dict1.getValueFromId(2));
             assertTrue(newId == 4);
         }
     }


[10/10] kylin git commit: KYLIN-2394 upgrade calcite to 1.11 and avatica to 1.9

Posted by bi...@apache.org.
KYLIN-2394 upgrade calcite to 1.11 and avatica to 1.9


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/fe599e78
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/fe599e78
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/fe599e78

Branch: refs/heads/KYLIN-2394
Commit: fe599e788a95185e3e387af96733f3ef7b23666c
Parents: e894465
Author: Billy Liu <bi...@apache.org>
Authored: Tue Jan 17 22:45:16 2017 +0800
Committer: Billy Liu <bi...@apache.org>
Committed: Tue Jan 17 22:45:16 2017 +0800

----------------------------------------------------------------------
 atopcalcite/pom.xml                             |    5 +-
 .../calcite/sql2rel/SqlToRelConverter.java      | 3941 +++++++++++-------
 jdbc/pom.xml                                    |   11 +-
 .../java/org/apache/kylin/jdbc/KylinMeta.java   |    2 +-
 kylin-it/pom.xml                                |    8 -
 .../org/apache/kylin/jdbc/ITJDBCDriverTest.java |    1 +
 pom.xml                                         |   10 +-
 query/pom.xml                                   |    4 -
 8 files changed, 2412 insertions(+), 1570 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/atopcalcite/pom.xml
----------------------------------------------------------------------
diff --git a/atopcalcite/pom.xml b/atopcalcite/pom.xml
index b916df2..5bcdac3 100644
--- a/atopcalcite/pom.xml
+++ b/atopcalcite/pom.xml
@@ -37,6 +37,9 @@
             <groupId>org.apache.calcite</groupId>
             <artifactId>calcite-core</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.apache.calcite.avatica</groupId>
+            <artifactId>avatica</artifactId>
+        </dependency>
     </dependencies>
-
 </project>


[02/10] kylin git commit: KYLIN-2396 percentile pre-aggregation support

Posted by bi...@apache.org.
KYLIN-2396 percentile pre-aggregation support


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/95d44121
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/95d44121
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/95d44121

Branch: refs/heads/KYLIN-2394
Commit: 95d4412194fb6fc08c99600d162826d9350a7a80
Parents: 4625b05
Author: lidongsjtu <li...@apache.org>
Authored: Mon Jan 16 11:12:36 2017 +0800
Committer: lidongsjtu <li...@apache.org>
Committed: Mon Jan 16 17:25:28 2017 +0800

----------------------------------------------------------------------
 .../org/apache/kylin/common/util/MathUtil.java  |  32 ++++++
 core-metadata/pom.xml                           |   4 +
 .../kylin/measure/MeasureTypeFactory.java       |   4 +-
 .../measure/percentile/PercentileAggFunc.java   |  44 ++++++++
 .../percentile/PercentileAggregator.java        |  64 ++++++++++++
 .../measure/percentile/PercentileContUdf.java   |  37 +++++++
 .../measure/percentile/PercentileCounter.java   |  97 ++++++++++++++++++
 .../percentile/PercentileMeasureType.java       | 102 +++++++++++++++++++
 .../percentile/PercentileSerializer.java        |  71 +++++++++++++
 .../percentile/PercentileAggregatorTest.java    |  55 ++++++++++
 .../percentile/PercentileCounterTest.java       |  79 ++++++++++++++
 .../percentile/PercentileSerializerTest.java    |  68 +++++++++++++
 .../kylin/measure/percentile/TDigestTest.java   |  57 +++++++++++
 .../localmeta/cube_desc/ci_inner_join_cube.json |  12 ++-
 .../localmeta/cube_desc/ci_left_join_cube.json  |  12 ++-
 .../apache/kylin/query/ITKylinQueryTest.java    |  18 ++--
 .../resources/query/sql_percentile/query01.sql  |   2 +
 pom.xml                                         |   6 ++
 storage-hbase/pom.xml                           |   1 +
 19 files changed, 755 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-common/src/main/java/org/apache/kylin/common/util/MathUtil.java
----------------------------------------------------------------------
diff --git a/core-common/src/main/java/org/apache/kylin/common/util/MathUtil.java b/core-common/src/main/java/org/apache/kylin/common/util/MathUtil.java
new file mode 100644
index 0000000..ae674c6
--- /dev/null
+++ b/core-common/src/main/java/org/apache/kylin/common/util/MathUtil.java
@@ -0,0 +1,32 @@
+/*
+ * 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.kylin.common.util;
+
+import java.util.List;
+
+public class MathUtil {
+    public static double findMedianInSortedList(List<Double> m) {
+        int middle = m.size() / 2;
+        if (m.size() % 2 == 1) {
+            return m.get(middle);
+        } else {
+            return (m.get(middle - 1) + m.get(middle)) / 2.0;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/pom.xml
----------------------------------------------------------------------
diff --git a/core-metadata/pom.xml b/core-metadata/pom.xml
index b3fe885..87c4438 100644
--- a/core-metadata/pom.xml
+++ b/core-metadata/pom.xml
@@ -47,6 +47,10 @@
             <groupId>org.roaringbitmap</groupId>
             <artifactId>RoaringBitmap</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.tdunning</groupId>
+            <artifactId>t-digest</artifactId>
+        </dependency>
 
         <!-- Env & Test -->
         <dependency>

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/main/java/org/apache/kylin/measure/MeasureTypeFactory.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/MeasureTypeFactory.java b/core-metadata/src/main/java/org/apache/kylin/measure/MeasureTypeFactory.java
index 8e58858..5d0e007 100644
--- a/core-metadata/src/main/java/org/apache/kylin/measure/MeasureTypeFactory.java
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/MeasureTypeFactory.java
@@ -28,6 +28,7 @@ import org.apache.kylin.measure.bitmap.BitmapMeasureType;
 import org.apache.kylin.measure.dim.DimCountDistinctMeasureType;
 import org.apache.kylin.measure.extendedcolumn.ExtendedColumnMeasureType;
 import org.apache.kylin.measure.hllc.HLLCMeasureType;
+import org.apache.kylin.measure.percentile.PercentileMeasureType;
 import org.apache.kylin.measure.raw.RawMeasureType;
 import org.apache.kylin.measure.topn.TopNMeasureType;
 import org.apache.kylin.metadata.datatype.DataType;
@@ -109,6 +110,7 @@ abstract public class MeasureTypeFactory<T> {
         factoryInsts.add(new TopNMeasureType.Factory());
         factoryInsts.add(new RawMeasureType.Factory());
         factoryInsts.add(new ExtendedColumnMeasureType.Factory());
+        factoryInsts.add(new PercentileMeasureType.Factory());
 
         logger.info("Checking custom measure types from kylin config");
 
@@ -143,7 +145,7 @@ abstract public class MeasureTypeFactory<T> {
             List<MeasureTypeFactory<?>> list = factories.get(funcName);
             if (list == null)
                 list = Lists.newArrayListWithCapacity(2);
-                factories.put(funcName, list);
+            factories.put(funcName, list);
             list.add(factory);
         }
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggFunc.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggFunc.java b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggFunc.java
new file mode 100644
index 0000000..ad02019
--- /dev/null
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggFunc.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.kylin.measure.percentile;
+
+public class PercentileAggFunc {
+    public static PercentileCounter init() {
+        return null;
+    }
+
+    public static PercentileCounter add(PercentileCounter counter, Object v, Object r) {
+        PercentileCounter c = (PercentileCounter) v;
+        Number n = (Number) r;
+        if (counter == null) {
+            counter = new PercentileCounter(c.compression, n.doubleValue());
+        }
+        counter.merge(c);
+        return counter;
+    }
+
+    public static PercentileCounter merge(PercentileCounter counter0, PercentileCounter counter1) {
+        counter0.merge(counter1);
+        return counter0;
+    }
+
+    public static double result(PercentileCounter counter) {
+        return counter == null ? 0L : counter.getResultEstimate();
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggregator.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggregator.java b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggregator.java
new file mode 100644
index 0000000..d6b93eb
--- /dev/null
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileAggregator.java
@@ -0,0 +1,64 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import org.apache.kylin.measure.MeasureAggregator;
+
+public class PercentileAggregator extends MeasureAggregator<PercentileCounter> {
+    final double compression;
+    PercentileCounter sum = null;
+
+    public PercentileAggregator(double compression) {
+        this.compression = compression;
+    }
+
+    @Override
+    public void reset() {
+        sum = null;
+    }
+
+    @Override
+    public void aggregate(PercentileCounter value) {
+        if (sum == null)
+            sum = new PercentileCounter(value);
+        else
+            sum.merge(value);
+    }
+
+    @Override
+    public PercentileCounter aggregate(PercentileCounter value1, PercentileCounter value2) {
+        PercentileCounter merged = new PercentileCounter(value1);
+        merged.merge(value2);
+        return merged;
+    }
+
+    @Override
+    public PercentileCounter getState() {
+        return sum;
+    }
+
+    @Override
+    public int getMemBytesEstimate() {
+        // 10K as upbound
+        // Test on random double data, 20 tDigest, each has 5000000 doubles. Finally merged into one tDigest.
+        // Before compress: 10309 bytes
+        // After compress: 8906 bytes
+        return 10 * 1024;
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileContUdf.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileContUdf.java b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileContUdf.java
new file mode 100644
index 0000000..4ef6b75
--- /dev/null
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileContUdf.java
@@ -0,0 +1,37 @@
+/*
+ * 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.kylin.measure.percentile;
+
+public class PercentileContUdf {
+    public static double init() {
+        return 0;
+    }
+
+    public static double add(double accumulator, double v, double r) {
+        return 0;
+    }
+
+    public static double merge(double accumulator0, double accumulator1) {
+        return 0;
+    }
+
+    public static double result(long accumulator) {
+        return 0;
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileCounter.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileCounter.java b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileCounter.java
new file mode 100644
index 0000000..bf505cf
--- /dev/null
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileCounter.java
@@ -0,0 +1,97 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+
+import com.tdunning.math.stats.AVLTreeDigest;
+import com.tdunning.math.stats.TDigest;
+
+public class PercentileCounter implements Serializable {
+    private static final double INVALID_QUANTILE_RATIO = -1;
+
+    double compression;
+    double quantileRatio;
+
+    TDigest registers;
+
+    public PercentileCounter(double compression) {
+        this(compression, INVALID_QUANTILE_RATIO);
+    }
+
+    public PercentileCounter(PercentileCounter another) {
+        this(another.compression, another.quantileRatio);
+        merge(another);
+    }
+
+    public PercentileCounter(double compression, double quantileRatio) {
+        this.compression = compression;
+        this.quantileRatio = quantileRatio;
+        reInitRegisters();
+    }
+
+    private void reInitRegisters() {
+        this.registers = TDigest.createAvlTreeDigest(this.compression);
+    }
+
+    public void add(double v) {
+        registers.add(v);
+    }
+
+    public void merge(PercentileCounter counter) {
+        assert this.compression == counter.compression;
+        registers.add(counter.registers);
+    }
+
+    public double getResultEstimate() {
+        return registers.quantile(quantileRatio);
+    }
+
+    public void writeRegisters(ByteBuffer out) {
+        registers.compress();
+        registers.asSmallBytes(out);
+    }
+
+    public void readRegisters(ByteBuffer in) {
+        registers = AVLTreeDigest.fromBytes(in);
+        compression = registers.compression();
+    }
+
+    public int getBytesEstimate() {
+        return maxLength();
+    }
+
+    public int maxLength() {
+        // 10KB for max length
+        return 10 * 1024;
+    }
+
+    public int peekLength(ByteBuffer in) {
+        int mark = in.position();
+        AVLTreeDigest.fromBytes(in);
+        int total = in.position() - mark;
+        in.position(mark);
+        return total;
+    }
+
+    public void clear() {
+        reInitRegisters();
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileMeasureType.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileMeasureType.java b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileMeasureType.java
new file mode 100644
index 0000000..45ebe89
--- /dev/null
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileMeasureType.java
@@ -0,0 +1,102 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import java.util.Map;
+
+import org.apache.kylin.common.util.Dictionary;
+import org.apache.kylin.measure.MeasureAggregator;
+import org.apache.kylin.measure.MeasureIngester;
+import org.apache.kylin.measure.MeasureType;
+import org.apache.kylin.measure.MeasureTypeFactory;
+import org.apache.kylin.metadata.datatype.DataType;
+import org.apache.kylin.metadata.datatype.DataTypeSerializer;
+import org.apache.kylin.metadata.model.MeasureDesc;
+import org.apache.kylin.metadata.model.TblColRef;
+
+import com.google.common.collect.ImmutableMap;
+
+public class PercentileMeasureType extends MeasureType<PercentileCounter> {
+    // compression ratio saved in DataType.precision
+    private final DataType dataType;
+    public static final String FUNC_PERCENTILE = "PERCENTILE";
+    public static final String DATATYPE_PERCENTILE = "percentile";
+
+    public PercentileMeasureType(String funcName, DataType dataType) {
+        this.dataType = dataType;
+    }
+
+    public static class Factory extends MeasureTypeFactory<PercentileCounter> {
+
+        @Override
+        public MeasureType<PercentileCounter> createMeasureType(String funcName, DataType dataType) {
+            return new PercentileMeasureType(funcName, dataType);
+        }
+
+        @Override
+        public String getAggrFunctionName() {
+            return FUNC_PERCENTILE;
+        }
+
+        @Override
+        public String getAggrDataTypeName() {
+            return DATATYPE_PERCENTILE;
+        }
+
+        @Override
+        public Class<? extends DataTypeSerializer<PercentileCounter>> getAggrDataTypeSerializer() {
+            return PercentileSerializer.class;
+        }
+    }
+
+    @Override
+    public MeasureIngester<PercentileCounter> newIngester() {
+        return new MeasureIngester<PercentileCounter>() {
+            PercentileCounter current = new PercentileCounter(dataType.getPrecision());
+
+            @Override
+            public PercentileCounter valueOf(String[] values, MeasureDesc measureDesc, Map<TblColRef, Dictionary<String>> dictionaryMap) {
+                PercentileCounter counter = current;
+                counter.clear();
+                for (String v : values) {
+                    if (v != null)
+                        counter.add(Double.parseDouble(v));
+                }
+                return counter;
+            }
+        };
+    }
+
+    @Override
+    public MeasureAggregator<PercentileCounter> newAggregator() {
+        return new PercentileAggregator(dataType.getPrecision());
+    }
+
+    @Override
+    public boolean needRewrite() {
+        return true;
+    }
+
+    static final Map<String, Class<?>> UDAF_MAP = ImmutableMap.<String, Class<?>> of(PercentileMeasureType.FUNC_PERCENTILE, PercentileAggFunc.class);
+
+    @Override
+    public Map<String, Class<?>> getRewriteCalciteAggrFunctions() {
+        return UDAF_MAP;
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileSerializer.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileSerializer.java b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileSerializer.java
new file mode 100644
index 0000000..a0a2a77
--- /dev/null
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/percentile/PercentileSerializer.java
@@ -0,0 +1,71 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import java.nio.ByteBuffer;
+
+import org.apache.kylin.metadata.datatype.DataType;
+import org.apache.kylin.metadata.datatype.DataTypeSerializer;
+
+public class PercentileSerializer extends DataTypeSerializer<PercentileCounter> {
+    // be thread-safe and avoid repeated obj creation
+    private ThreadLocal<PercentileCounter> current = new ThreadLocal<>();
+
+    private double compression;
+
+    public PercentileSerializer(DataType type) {
+        this.compression = type.getPrecision();
+    }
+
+    @Override
+    public int peekLength(ByteBuffer in) {
+        return current().peekLength(in);
+    }
+
+    @Override
+    public int maxLength() {
+        return current().maxLength();
+    }
+
+    @Override
+    public int getStorageBytesEstimate() {
+        return current().getBytesEstimate();
+    }
+
+    private PercentileCounter current() {
+        PercentileCounter counter = current.get();
+        if (counter == null) {
+            counter = new PercentileCounter(compression);
+            current.set(counter);
+        }
+        return counter;
+    }
+
+    @Override
+    public void serialize(PercentileCounter value, ByteBuffer out) {
+        value.writeRegisters(out);
+    }
+
+    @Override
+    public PercentileCounter deserialize(ByteBuffer in) {
+        PercentileCounter counter = current();
+        counter.readRegisters(in);
+        return counter;
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileAggregatorTest.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileAggregatorTest.java b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileAggregatorTest.java
new file mode 100644
index 0000000..9d59d46
--- /dev/null
+++ b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileAggregatorTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.kylin.common.util.MathUtil;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+
+public class PercentileAggregatorTest {
+    @Test
+    public void testAggregate() {
+        double compression = 100;
+        int datasize = 10000;
+        PercentileAggregator aggregator = new PercentileAggregator(compression);
+        Random random = new Random();
+        List<Double> dataset = Lists.newArrayListWithCapacity(datasize);
+        for (int i = 0; i < datasize; i++) {
+            double d = random.nextDouble();
+            dataset.add(d);
+
+            PercentileCounter c = new PercentileCounter(compression, 0.5);
+            c.add(d);
+            aggregator.aggregate(c);
+        }
+        Collections.sort(dataset);
+
+        double actualResult = aggregator.getState().getResultEstimate();
+        double expectResult = MathUtil.findMedianInSortedList(dataset);
+        assertEquals(expectResult, actualResult, 0.001);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileCounterTest.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileCounterTest.java b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileCounterTest.java
new file mode 100644
index 0000000..abaa409
--- /dev/null
+++ b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileCounterTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.kylin.common.util.MathUtil;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+import com.tdunning.math.stats.TDigest;
+
+public class PercentileCounterTest {
+    @Test
+    public void testBasic() {
+        int times = 1;
+        int compression = 100;
+        for (int t = 0; t < times; t++) {
+            PercentileCounter counter = new PercentileCounter(compression, 0.5);
+            Random random = new Random();
+            int dataSize = 10000;
+            List<Double> dataset = Lists.newArrayListWithCapacity(dataSize);
+            for (int i = 0; i < dataSize; i++) {
+                double d = random.nextDouble();
+                counter.add(d);
+                dataset.add(d);
+            }
+            Collections.sort(dataset);
+
+            double actualResult = counter.getResultEstimate();
+            double expectedResult = MathUtil.findMedianInSortedList(dataset);
+            assertEquals(expectedResult, actualResult, 0.001);
+        }
+    }
+
+    @Test
+    public void testTDigest() {
+        double compression = 100;
+        double quantile = 0.5;
+
+        PercentileCounter counter = new PercentileCounter(compression, quantile);
+        TDigest tDigest = TDigest.createAvlTreeDigest(compression);
+
+        Random random = new Random();
+        int dataSize = 10000;
+        List<Double> dataset = Lists.newArrayListWithCapacity(dataSize);
+        for (int i = 0; i < dataSize; i++) {
+            double d = random.nextDouble();
+            counter.add(d);
+            tDigest.add(d);
+        }
+        double actualResult = counter.getResultEstimate();
+
+        Collections.sort(dataset);
+        double expectedResult = tDigest.quantile(quantile);
+
+        assertEquals(expectedResult, actualResult, 0);
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileSerializerTest.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileSerializerTest.java b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileSerializerTest.java
new file mode 100644
index 0000000..07b4495
--- /dev/null
+++ b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/PercentileSerializerTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import static org.junit.Assert.assertEquals;
+
+import java.nio.ByteBuffer;
+import java.util.Random;
+
+import org.apache.kylin.common.util.LocalFileMetadataTestCase;
+import org.apache.kylin.metadata.datatype.DataType;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Created by dongli on 5/21/16.
+ */
+public class PercentileSerializerTest extends LocalFileMetadataTestCase {
+
+    @Before
+    public void setup() throws Exception {
+        createTestMetadata();
+    }
+
+    @After
+    public void after() throws Exception {
+        cleanAfterClass();
+    }
+
+    @Test
+    public void testBasic() {
+        PercentileSerializer serializer = new PercentileSerializer(DataType.getType("percentile(100)"));
+        PercentileCounter counter = new PercentileCounter(100, 0.5);
+        Random random = new Random();
+        for (int i = 0; i < 1000; i++) {
+            counter.add(random.nextDouble());
+        }
+        double markResult = counter.getResultEstimate();
+
+        ByteBuffer buffer = ByteBuffer.allocateDirect(serializer.getStorageBytesEstimate());
+        serializer.serialize(counter, buffer);
+
+        buffer.flip();
+        counter = serializer.deserialize(buffer);
+        PercentileCounter counter1 = new PercentileCounter(100, 0.5);
+        counter1.merge(counter);
+
+        assertEquals(markResult, counter1.getResultEstimate(), 0.01);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/core-metadata/src/test/java/org/apache/kylin/measure/percentile/TDigestTest.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/test/java/org/apache/kylin/measure/percentile/TDigestTest.java b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/TDigestTest.java
new file mode 100644
index 0000000..1adb604
--- /dev/null
+++ b/core-metadata/src/test/java/org/apache/kylin/measure/percentile/TDigestTest.java
@@ -0,0 +1,57 @@
+/*
+ * 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.kylin.measure.percentile;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.kylin.common.util.MathUtil;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+import com.tdunning.math.stats.TDigest;
+
+@Ignore
+public class TDigestTest {
+    @Test
+    public void testBasic() {
+        int times = 1;
+        int compression = 100;
+        for (int t = 0; t < times; t++) {
+            TDigest tDigest = TDigest.createAvlTreeDigest(compression);
+            Random random = new Random();
+            int dataSize = 10000;
+            List<Double> dataset = Lists.newArrayListWithCapacity(dataSize);
+            for (int i = 0; i < dataSize; i++) {
+                double d = random.nextDouble();
+                tDigest.add(d);
+                dataset.add(d);
+            }
+            Collections.sort(dataset);
+
+            double actualResult = tDigest.quantile(0.5);
+            double expectedResult = MathUtil.findMedianInSortedList(dataset);
+            assertEquals(expectedResult, actualResult, 0.01);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/examples/test_case_data/localmeta/cube_desc/ci_inner_join_cube.json
----------------------------------------------------------------------
diff --git a/examples/test_case_data/localmeta/cube_desc/ci_inner_join_cube.json b/examples/test_case_data/localmeta/cube_desc/ci_inner_join_cube.json
index 1ebd7f3..0fda3b3 100644
--- a/examples/test_case_data/localmeta/cube_desc/ci_inner_join_cube.json
+++ b/examples/test_case_data/localmeta/cube_desc/ci_inner_join_cube.json
@@ -267,6 +267,16 @@
       },
       "returntype" : "raw"
     }
+  }, {
+    "name" : "GVM_PERCENTILE",
+    "function" : {
+      "expression" : "PERCENTILE",
+      "parameter" : {
+        "type" : "column",
+        "value" : "TEST_KYLIN_FACT.PRICE"
+      },
+      "returntype" : "percentile(100)"
+    }
   } ],
   "dictionaries": [ {
     "column": "TEST_KYLIN_FACT.TEST_COUNT_DISTINCT_BITMAP",
@@ -358,7 +368,7 @@
       "name" : "f3",
       "columns" : [ {
         "qualifier" : "m",
-        "measure_refs" : [ "TEST_EXTENDED_COLUMN", "TRANS_ID_RAW", "PRICE_RAW", "CAL_DT_RAW", "BUYER_CONTACT", "SELLER_CONTACT" ]
+        "measure_refs" : [ "TEST_EXTENDED_COLUMN", "TRANS_ID_RAW", "PRICE_RAW", "CAL_DT_RAW", "BUYER_CONTACT", "SELLER_CONTACT", "GVM_PERCENTILE" ]
       } ]
     } ]
   },

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/examples/test_case_data/localmeta/cube_desc/ci_left_join_cube.json
----------------------------------------------------------------------
diff --git a/examples/test_case_data/localmeta/cube_desc/ci_left_join_cube.json b/examples/test_case_data/localmeta/cube_desc/ci_left_join_cube.json
index 4048b6e..51139ae 100644
--- a/examples/test_case_data/localmeta/cube_desc/ci_left_join_cube.json
+++ b/examples/test_case_data/localmeta/cube_desc/ci_left_join_cube.json
@@ -267,6 +267,16 @@
       },
       "returntype" : "raw"
     }
+  }, {
+    "name" : "GVM_PERCENTILE",
+    "function" : {
+      "expression" : "PERCENTILE",
+      "parameter" : {
+        "type" : "column",
+        "value" : "TEST_KYLIN_FACT.PRICE"
+      },
+      "returntype" : "percentile(100)"
+    }
   } ],
   "dictionaries": [ {
     "column": "TEST_KYLIN_FACT.TEST_COUNT_DISTINCT_BITMAP",
@@ -358,7 +368,7 @@
       "name" : "f3",
       "columns" : [ {
         "qualifier" : "m",
-        "measure_refs" : [ "TEST_EXTENDED_COLUMN", "TRANS_ID_RAW", "PRICE_RAW", "CAL_DT_RAW", "BUYER_CONTACT", "SELLER_CONTACT" ]
+        "measure_refs" : [ "TEST_EXTENDED_COLUMN", "TRANS_ID_RAW", "PRICE_RAW", "CAL_DT_RAW", "BUYER_CONTACT", "SELLER_CONTACT", "GVM_PERCENTILE" ]
       } ]
     } ]
   },

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
----------------------------------------------------------------------
diff --git a/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java b/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
index 82d0873..02134d4 100644
--- a/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
+++ b/kylin-it/src/test/java/org/apache/kylin/query/ITKylinQueryTest.java
@@ -192,17 +192,17 @@ public class ITKylinQueryTest extends KylinTestBase {
     public void testSnowflakeQuery() throws Exception {
         execAndCompQuery(getQueryFolderPrefix() + "src/test/resources/query/sql_snowflake", null, true);
     }
-    
+
     @Test
     public void testDateTimeQuery() throws Exception {
         execAndCompQuery(getQueryFolderPrefix() + "src/test/resources/query/sql_datetime", null, true);
     }
-    
+
     @Test
     public void testExtendedColumnQuery() throws Exception {
         execAndCompQuery(getQueryFolderPrefix() + "src/test/resources/query/sql_extended_column", null, true);
     }
-    
+
     @Test
     public void testLikeQuery() throws Exception {
         execAndCompQuery(getQueryFolderPrefix() + "src/test/resources/query/sql_like", null, true);
@@ -270,8 +270,7 @@ public class ITKylinQueryTest extends KylinTestBase {
             this.batchExecuteQuery(getQueryFolderPrefix() + "src/test/resources/query/sql_intersect_count");
         }
     }
-    
-    
+
     @Test
     public void testMultiModelQuery() throws Exception {
         if ("left".equalsIgnoreCase(joinType)) {
@@ -280,7 +279,7 @@ public class ITKylinQueryTest extends KylinTestBase {
             joinType = "left";
         }
     }
-    
+
     @Test
     public void testDimDistinctCountQuery() throws Exception {
         execAndCompQuery(getQueryFolderPrefix() + "src/test/resources/query/sql_distinct_dim", null, true);
@@ -392,10 +391,15 @@ public class ITKylinQueryTest extends KylinTestBase {
         // compare the result
         Assert.assertEquals(expectVersion, queriedVersion);
     }
-    
+
     @Test
     public void testSelectStarColumnCount() throws Exception {
         execAndCompColumnCount("select * from test_kylin_fact limit 10", 11);
         execAndCompColumnCount("select * from test_kylin_fact", 11);
     }
+
+    @Test
+    public void testPercentileQuery() throws Exception {
+        batchExecuteQuery("src/test/resources/query/sql_percentile");
+    }
 }

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/kylin-it/src/test/resources/query/sql_percentile/query01.sql
----------------------------------------------------------------------
diff --git a/kylin-it/src/test/resources/query/sql_percentile/query01.sql b/kylin-it/src/test/resources/query/sql_percentile/query01.sql
new file mode 100644
index 0000000..4f6d573
--- /dev/null
+++ b/kylin-it/src/test/resources/query/sql_percentile/query01.sql
@@ -0,0 +1,2 @@
+select seller_id, percentile(price, 0.5) from test_kylin_fact
+group by seller_id
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index e391103..e8ccb6c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -102,6 +102,7 @@
         <supercsv.version>2.4.0</supercsv.version>
         <cors.version>2.5</cors.version>
         <tomcat.version>8.5.9</tomcat.version>
+        <t-digest.version>3.1</t-digest.version>
 
         <!-- REST Service -->
         <spring.framework.version>3.2.17.RELEASE</spring.framework.version>
@@ -658,6 +659,11 @@
                 <version>${roaring.version}</version>
             </dependency>
             <dependency>
+                <groupId>com.tdunning</groupId>
+                <artifactId>t-digest</artifactId>
+                <version>${t-digest.version}</version>
+            </dependency>
+            <dependency>
                 <groupId>cglib</groupId>
                 <artifactId>cglib</artifactId>
                 <version>${cglib.version}</version>

http://git-wip-us.apache.org/repos/asf/kylin/blob/95d44121/storage-hbase/pom.xml
----------------------------------------------------------------------
diff --git a/storage-hbase/pom.xml b/storage-hbase/pom.xml
index eb2c104..3aea531 100644
--- a/storage-hbase/pom.xml
+++ b/storage-hbase/pom.xml
@@ -121,6 +121,7 @@
                                     <include>org.apache.kylin:kylin-core-cube</include>
                                     <include>com.ning:compress-lzf</include>
                                     <include>org.roaringbitmap:RoaringBitmap</include>
+                                    <include>com.tdunning:t-digest</include>
                                     <!-- below for inverted index only -->
                                     <include>com.n3twork.druid:extendedset</include>
                                     <include>org.apache.commons:commons-lang3</include>


[07/10] kylin git commit: KYLIN-2387 remove the usage of ImmutableRoaringBitmap.bitmapOf to be compatible with older version of roaringbitmap

Posted by bi...@apache.org.
KYLIN-2387 remove the usage of ImmutableRoaringBitmap.bitmapOf to be compatible with older version of roaringbitmap


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/e8944650
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/e8944650
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/e8944650

Branch: refs/heads/KYLIN-2394
Commit: e894465007f422d619ddeab2acd87e38fa093fd9
Parents: f182670
Author: gaodayue <ga...@meituan.com>
Authored: Tue Jan 17 18:39:01 2017 +0800
Committer: gaodayue <ga...@meituan.com>
Committed: Tue Jan 17 18:39:01 2017 +0800

----------------------------------------------------------------------
 .../apache/kylin/measure/bitmap/BitmapSerializer.java   |  2 +-
 .../kylin/measure/bitmap/ImmutableBitmapCounter.java    |  4 ----
 .../kylin/measure/bitmap/BitmapAggregatorTest.java      |  6 +++---
 .../apache/kylin/measure/bitmap/BitmapCounterTest.java  | 12 +++++++-----
 .../kylin/measure/bitmap/BitmapSerializerTest.java      |  7 ++++---
 5 files changed, 15 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/e8944650/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapSerializer.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapSerializer.java b/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapSerializer.java
index 8b15d1c..0e970de 100644
--- a/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapSerializer.java
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/BitmapSerializer.java
@@ -25,7 +25,7 @@ import java.io.IOException;
 import java.nio.ByteBuffer;
 
 public class BitmapSerializer extends DataTypeSerializer<BitmapCounter> {
-    private static final BitmapCounter DELEGATE = new ImmutableBitmapCounter();
+    private static final BitmapCounter DELEGATE = new MutableBitmapCounter();
 
     // called by reflection
     public BitmapSerializer(DataType type) {

http://git-wip-us.apache.org/repos/asf/kylin/blob/e8944650/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/ImmutableBitmapCounter.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/ImmutableBitmapCounter.java b/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/ImmutableBitmapCounter.java
index 5c39a4a..753f089 100644
--- a/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/ImmutableBitmapCounter.java
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/bitmap/ImmutableBitmapCounter.java
@@ -34,10 +34,6 @@ public class ImmutableBitmapCounter implements BitmapCounter {
 
     protected ImmutableRoaringBitmap bitmap;
 
-    public ImmutableBitmapCounter() {
-        this(ImmutableRoaringBitmap.bitmapOf());
-    }
-
     public ImmutableBitmapCounter(ImmutableRoaringBitmap bitmap) {
         this.bitmap = bitmap;
     }

http://git-wip-us.apache.org/repos/asf/kylin/blob/e8944650/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapAggregatorTest.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapAggregatorTest.java b/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapAggregatorTest.java
index 03eb53a..a52e427 100644
--- a/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapAggregatorTest.java
+++ b/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapAggregatorTest.java
@@ -19,7 +19,7 @@
 package org.apache.kylin.measure.bitmap;
 
 import org.junit.Test;
-import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
@@ -32,12 +32,12 @@ public class BitmapAggregatorTest {
         assertNull(null, aggregator.getState());
 
         aggregator.aggregate(new ImmutableBitmapCounter(
-                ImmutableRoaringBitmap.bitmapOf(10, 20, 30, 40)
+                MutableRoaringBitmap.bitmapOf(10, 20, 30, 40)
         ));
         assertEquals(4, aggregator.getState().getCount());
 
         aggregator.aggregate(new ImmutableBitmapCounter(
-                ImmutableRoaringBitmap.bitmapOf(25, 30, 35, 40, 45)
+                MutableRoaringBitmap.bitmapOf(25, 30, 35, 40, 45)
         ));
         assertEquals(7, aggregator.getState().getCount());
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/e8944650/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapCounterTest.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapCounterTest.java b/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapCounterTest.java
index 70e4ecc..ee7733f 100644
--- a/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapCounterTest.java
+++ b/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapCounterTest.java
@@ -19,7 +19,7 @@
 package org.apache.kylin.measure.bitmap;
 
 import org.junit.Test;
-import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
 
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
@@ -29,8 +29,9 @@ public class BitmapCounterTest {
 
     @Test
     public void testBitmapCounter() {
-        ImmutableRoaringBitmap bitmap = ImmutableRoaringBitmap.bitmapOf(10, 20, 30, 1000);
-        ImmutableBitmapCounter counter = new ImmutableBitmapCounter(bitmap);
+        ImmutableBitmapCounter counter = new ImmutableBitmapCounter(
+                MutableRoaringBitmap.bitmapOf(10, 20, 30, 1000)
+        );
         assertEquals(4, counter.getCount());
         assertTrue(counter.getMemBytes() > 0);
 
@@ -59,8 +60,9 @@ public class BitmapCounterTest {
 
     @Test
     public void testToMutableBitmapCounter() {
-        ImmutableRoaringBitmap bitmap = ImmutableRoaringBitmap.bitmapOf(10, 20, 30, 1000);
-        ImmutableBitmapCounter immutable = new ImmutableBitmapCounter(bitmap);
+        ImmutableBitmapCounter immutable = new ImmutableBitmapCounter(
+                MutableRoaringBitmap.bitmapOf(10, 20, 30, 1000)
+        );
         MutableBitmapCounter mutable = new MutableBitmapCounter();
         mutable.orWith(immutable);
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/e8944650/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapSerializerTest.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapSerializerTest.java b/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapSerializerTest.java
index 71fcae6..e5b828d 100644
--- a/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapSerializerTest.java
+++ b/core-metadata/src/test/java/org/apache/kylin/measure/bitmap/BitmapSerializerTest.java
@@ -24,7 +24,7 @@ import org.junit.AfterClass;
 import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
 
 import java.nio.BufferOverflowException;
 import java.nio.ByteBuffer;
@@ -47,8 +47,9 @@ public class BitmapSerializerTest extends LocalFileMetadataTestCase {
     public void testBitmapSerDe() {
         BitmapSerializer serializer = new BitmapSerializer(DataType.ANY);
 
-        ImmutableRoaringBitmap bitmap = ImmutableRoaringBitmap.bitmapOf(1, 1234, 5678, 100000);
-        ImmutableBitmapCounter counter = new ImmutableBitmapCounter(bitmap);
+        ImmutableBitmapCounter counter = new ImmutableBitmapCounter(
+                MutableRoaringBitmap.bitmapOf(1, 1234, 5678, 100000)
+        );
 
         ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
         serializer.serialize(counter, buffer);


[08/10] kylin git commit: KYLIN-2394 upgrade calcite to 1.11 and avatica to 1.9

Posted by bi...@apache.org.
http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/jdbc/pom.xml
----------------------------------------------------------------------
diff --git a/jdbc/pom.xml b/jdbc/pom.xml
index cd784f4..1960da6 100644
--- a/jdbc/pom.xml
+++ b/jdbc/pom.xml
@@ -66,13 +66,16 @@
                         </goals>
                         <configuration>
                             <createDependencyReducedPom>false</createDependencyReducedPom>
+
                             <artifactSet>
-                                <!-- jackson is already packaged into calcite-avatica.jar. To avoid including jackson
-                                twice, we include calcite-avatica which has jackson and exclude jackson. -->
                                 <excludes>
                                     <exclude>com.fasterxml.jackson.core:*</exclude>
+                                    <exclude>com.google.protobuf:*</exclude>
+                                    <exclude>commons-logging:*</exclude>
+                                    <exclude>commons-codec:*</exclude>
                                 </excludes>
                             </artifactSet>
+
                             <relocations>
                                 <relocation>
                                     <pattern>org.apache.calcite</pattern>
@@ -86,10 +89,6 @@
                                     <pattern>org.apache.http</pattern>
                                     <shadedPattern>${shadeBase}.org.apache.http</shadedPattern>
                                 </relocation>
-                                <relocation>
-                                    <pattern>org.apache.commons</pattern>
-                                    <shadedPattern>${shadeBase}.org.apache.commons</shadedPattern>
-                                </relocation>
                             </relocations>
                             <filters>
                                 <filter>

http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java
----------------------------------------------------------------------
diff --git a/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java b/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java
index a1b9aef..8e69e68 100644
--- a/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java
+++ b/jdbc/src/main/java/org/apache/kylin/jdbc/KylinMeta.java
@@ -209,7 +209,7 @@ public class KylinMeta extends MetaImpl {
             } catch (NoSuchFieldException e) {
                 throw new RuntimeException(e);
             }
-            columns.add(columnMetaData(name, index, field.getType()));
+            columns.add(columnMetaData(name, index, field.getType(), true));
             fields.add(field);
             fieldNames.add(fieldName);
         }

http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/kylin-it/pom.xml
----------------------------------------------------------------------
diff --git a/kylin-it/pom.xml b/kylin-it/pom.xml
index 080558b..f92f318 100644
--- a/kylin-it/pom.xml
+++ b/kylin-it/pom.xml
@@ -74,14 +74,6 @@
             <groupId>org.apache.kylin</groupId>
             <artifactId>kylin-query</artifactId>
         </dependency>
-        <dependency>
-            <groupId>org.apache.calcite</groupId>
-            <artifactId>calcite-linq4j</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>commons-cli</groupId>
-            <artifactId>commons-cli</artifactId>
-        </dependency>
 
         <!-- Env & Test -->
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/kylin-it/src/test/java/org/apache/kylin/jdbc/ITJDBCDriverTest.java
----------------------------------------------------------------------
diff --git a/kylin-it/src/test/java/org/apache/kylin/jdbc/ITJDBCDriverTest.java b/kylin-it/src/test/java/org/apache/kylin/jdbc/ITJDBCDriverTest.java
index df6eb2f..05f615f 100644
--- a/kylin-it/src/test/java/org/apache/kylin/jdbc/ITJDBCDriverTest.java
+++ b/kylin-it/src/test/java/org/apache/kylin/jdbc/ITJDBCDriverTest.java
@@ -21,6 +21,7 @@ package org.apache.kylin.jdbc;
 import java.io.File;
 import java.sql.Connection;
 import java.sql.DatabaseMetaData;
+import java.sql.Driver;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.Statement;

http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index e8ccb6c..6d28033 100644
--- a/pom.xml
+++ b/pom.xml
@@ -112,8 +112,8 @@
         <aspectj.version>1.8.9</aspectj.version>
 
         <!-- Calcite Version -->
-        <calcite.version>1.10.0</calcite.version>
-        <avatica.version>1.8.0</avatica.version>
+        <calcite.version>1.11.0</calcite.version>
+        <avatica.version>1.9.0</avatica.version>
 
         <!-- Sonar -->
         <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
@@ -450,15 +450,9 @@
                 </exclusions>
             </dependency>
             <dependency>
-                <groupId>org.apache.calcite</groupId>
-                <artifactId>calcite-linq4j</artifactId>
-                <version>${calcite.version}</version>
-            </dependency>
-            <dependency>
                 <groupId>org.apache.calcite.avatica</groupId>
                 <artifactId>avatica</artifactId>
                 <version>${avatica.version}</version>
-
             </dependency>
             <!-- Workaround for hive 0.14 avatica dependency -->
             <dependency>

http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/query/pom.xml
----------------------------------------------------------------------
diff --git a/query/pom.xml b/query/pom.xml
index 1dc05d1..c565e3a 100644
--- a/query/pom.xml
+++ b/query/pom.xml
@@ -42,10 +42,6 @@
             <artifactId>kylin-core-storage</artifactId>
         </dependency>
         <dependency>
-            <groupId>org.apache.calcite</groupId>
-            <artifactId>calcite-core</artifactId>
-        </dependency>
-        <dependency>
             <groupId>commons-cli</groupId>
             <artifactId>commons-cli</artifactId>
         </dependency>


[09/10] kylin git commit: KYLIN-2394 upgrade calcite to 1.11 and avatica to 1.9

Posted by bi...@apache.org.
http://git-wip-us.apache.org/repos/asf/kylin/blob/fe599e78/atopcalcite/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
----------------------------------------------------------------------
diff --git a/atopcalcite/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java b/atopcalcite/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
index e0782ce..171e299 100644
--- a/atopcalcite/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
+++ b/atopcalcite/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
@@ -16,24 +16,6 @@
  */
 package org.apache.calcite.sql2rel;
 
-import static org.apache.calcite.sql.SqlUtil.stripAs;
-import static org.apache.calcite.util.Static.RESOURCE;
-
-import java.lang.reflect.Type;
-import java.math.BigDecimal;
-import java.util.AbstractList;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
 import org.apache.calcite.avatica.util.Spaces;
 import org.apache.calcite.linq4j.Ord;
 import org.apache.calcite.plan.Convention;
@@ -85,7 +67,6 @@ import org.apache.calcite.rel.stream.Delta;
 import org.apache.calcite.rel.stream.LogicalDelta;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
-import org.apache.calcite.rel.type.RelDataTypeFactory.FieldInfoBuilder;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexCall;
@@ -116,6 +97,7 @@ import org.apache.calcite.sql.SqlCallBinding;
 import org.apache.calcite.sql.SqlDataTypeSpec;
 import org.apache.calcite.sql.SqlDelete;
 import org.apache.calcite.sql.SqlDynamicParam;
+import org.apache.calcite.sql.SqlExplainFormat;
 import org.apache.calcite.sql.SqlExplainLevel;
 import org.apache.calcite.sql.SqlFunction;
 import org.apache.calcite.sql.SqlIdentifier;
@@ -177,17 +159,37 @@ import org.apache.calcite.util.NumberUtil;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.trace.CalciteTrace;
-import org.slf4j.Logger;
 
 import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
+
+import org.slf4j.Logger;
+
+import java.lang.reflect.Type;
+import java.math.BigDecimal;
+import java.util.AbstractList;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import static org.apache.calcite.sql.SqlUtil.stripAs;
+import static org.apache.calcite.util.Static.RESOURCE;
 
 /*
  * The code has synced with calcite. Hope one day, we could remove the hardcode override point.
@@ -209,42 +211,56 @@ import com.google.common.collect.Sets;
 public class SqlToRelConverter {
     //~ Static fields/initializers ---------------------------------------------
 
+    protected static final Logger SQL2REL_LOGGER =
+            CalciteTrace.getSqlToRelTracer();
+
+    private static final BigDecimal TWO = BigDecimal.valueOf(2L);
+
     /** Size of the smallest IN list that will be converted to a semijoin to a
      * static table. */
-    public static final int DEFAULT_IN_SUBQUERY_THRESHOLD = 20;
-    protected static final Logger SQL2REL_LOGGER = CalciteTrace.getSqlToRelTracer();
-    private static final BigDecimal TWO = BigDecimal.valueOf(2L);
+    public static final int DEFAULT_IN_SUB_QUERY_THRESHOLD = 20;
+
+    @Deprecated // to be removed before 2.0
+    public static final int DEFAULT_IN_SUBQUERY_THRESHOLD =
+            DEFAULT_IN_SUB_QUERY_THRESHOLD;
 
     //~ Instance fields --------------------------------------------------------
-    public final SqlToRelConverter.Config config;
-    public final RelOptTable.ViewExpander viewExpander;
+
     protected final SqlValidator validator;
     protected final RexBuilder rexBuilder;
     protected final Prepare.CatalogReader catalogReader;
     protected final RelOptCluster cluster;
+    private DefaultValueFactory defaultValueFactory;
+    private SubQueryConverter subQueryConverter;
     protected final List<RelNode> leaves = new ArrayList<>();
-    protected final RelDataTypeFactory typeFactory;
     private final List<SqlDynamicParam> dynamicParamSqlNodes = new ArrayList<>();
     private final SqlOperatorTable opTab;
+    protected final RelDataTypeFactory typeFactory;
     private final SqlNodeToRexConverter exprConverter;
+    private int explainParamCount;
+    public final SqlToRelConverter.Config config;
+
     /**
-     * Fields used in name resolution for correlated subqueries.
+     * Fields used in name resolution for correlated sub-queries.
      */
-    private final Map<CorrelationId, DeferredLookup> mapCorrelToDeferred = new HashMap<>();
+    private final Map<CorrelationId, DeferredLookup> mapCorrelToDeferred =
+            new HashMap<>();
+
     /**
      * Stack of names of datasets requested by the <code>
      * TABLE(SAMPLE(&lt;datasetName&gt;, &lt;query&gt;))</code> construct.
      */
     private final Deque<String> datasetStack = new ArrayDeque<>();
+
     /**
-     * Mapping of non-correlated subqueries that have been converted to their
-     * equivalent constants. Used to avoid re-evaluating the subquery if it's
+     * Mapping of non-correlated sub-queries that have been converted to their
+     * equivalent constants. Used to avoid re-evaluating the sub-query if it's
      * already been evaluated.
      */
-    private final Map<SqlNode, RexNode> mapConvertedNonCorrSubqs = new HashMap<>();
-    private DefaultValueFactory defaultValueFactory;
-    private SubqueryConverter subqueryConverter;
-    private int explainParamCount;
+    private final Map<SqlNode, RexNode> mapConvertedNonCorrSubqs =
+            new HashMap<>();
+
+    public final RelOptTable.ViewExpander viewExpander;
 
     //~ Constructors -----------------------------------------------------------
     /**
@@ -258,23 +274,46 @@ public class SqlToRelConverter {
      * @param convertletTable Expression converter
      */
     @Deprecated // to be removed before 2.0
-    public SqlToRelConverter(RelOptTable.ViewExpander viewExpander, SqlValidator validator, Prepare.CatalogReader catalogReader, RelOptPlanner planner, RexBuilder rexBuilder, SqlRexConvertletTable convertletTable) {
-        this(viewExpander, validator, catalogReader, RelOptCluster.create(planner, rexBuilder), convertletTable, Config.DEFAULT);
+    public SqlToRelConverter(
+            RelOptTable.ViewExpander viewExpander,
+            SqlValidator validator,
+            Prepare.CatalogReader catalogReader,
+            RelOptPlanner planner,
+            RexBuilder rexBuilder,
+            SqlRexConvertletTable convertletTable) {
+        this(viewExpander, validator, catalogReader,
+                RelOptCluster.create(planner, rexBuilder), convertletTable,
+                Config.DEFAULT);
     }
 
     @Deprecated // to be removed before 2.0
-    public SqlToRelConverter(RelOptTable.ViewExpander viewExpander, SqlValidator validator, Prepare.CatalogReader catalogReader, RelOptCluster cluster, SqlRexConvertletTable convertletTable) {
-        this(viewExpander, validator, catalogReader, cluster, convertletTable, Config.DEFAULT);
+    public SqlToRelConverter(
+            RelOptTable.ViewExpander viewExpander,
+            SqlValidator validator,
+            Prepare.CatalogReader catalogReader,
+            RelOptCluster cluster,
+            SqlRexConvertletTable convertletTable) {
+        this(viewExpander, validator, catalogReader, cluster, convertletTable,
+                Config.DEFAULT);
     }
 
     /* Creates a converter. */
-    public SqlToRelConverter(RelOptTable.ViewExpander viewExpander, SqlValidator validator, Prepare.CatalogReader catalogReader, RelOptCluster cluster, SqlRexConvertletTable convertletTable, Config config) {
+    public SqlToRelConverter(
+            RelOptTable.ViewExpander viewExpander,
+            SqlValidator validator,
+            Prepare.CatalogReader catalogReader,
+            RelOptCluster cluster,
+            SqlRexConvertletTable convertletTable,
+            Config config) {
         this.viewExpander = viewExpander;
-        this.opTab = (validator == null) ? SqlStdOperatorTable.instance() : validator.getOperatorTable();
+        this.opTab =
+                (validator
+                        == null) ? SqlStdOperatorTable.instance()
+                        : validator.getOperatorTable();
         this.validator = validator;
         this.catalogReader = catalogReader;
         this.defaultValueFactory = new NullDefaultValueFactory();
-        this.subqueryConverter = new NoOpSubqueryConverter();
+        this.subQueryConverter = new NoOpSubQueryConverter();
         this.rexBuilder = cluster.getRexBuilder();
         this.typeFactory = rexBuilder.getTypeFactory();
         this.cluster = Preconditions.checkNotNull(cluster);
@@ -285,157 +324,6 @@ public class SqlToRelConverter {
 
     //~ Methods ----------------------------------------------------------------
 
-    private static boolean isStream(SqlNode query) {
-        return query instanceof SqlSelect && ((SqlSelect) query).isKeywordPresent(SqlSelectKeyword.STREAM);
-    }
-
-    public static boolean isOrdered(SqlNode query) {
-        switch (query.getKind()) {
-        case SELECT:
-            return ((SqlSelect) query).getOrderList() != null && ((SqlSelect) query).getOrderList().size() > 0;
-        case WITH:
-            return isOrdered(((SqlWith) query).body);
-        case ORDER_BY:
-            return ((SqlOrderBy) query).orderList.size() > 0;
-        default:
-            return false;
-        }
-    }
-
-    /**
-     * Returns whether a given node contains a {@link SqlInOperator}.
-     *
-     * @param node a RexNode tree
-     */
-    private static boolean containsInOperator(SqlNode node) {
-        try {
-            SqlVisitor<Void> visitor = new SqlBasicVisitor<Void>() {
-                public Void visit(SqlCall call) {
-                    if (call.getOperator() instanceof SqlInOperator) {
-                        throw new Util.FoundOne(call);
-                    }
-                    return super.visit(call);
-                }
-            };
-            node.accept(visitor);
-            return false;
-        } catch (Util.FoundOne e) {
-            Util.swallow(e, null);
-            return true;
-        }
-    }
-
-    /**
-     * Push down all the NOT logical operators into any IN/NOT IN operators.
-     *
-     * @param sqlNode the root node from which to look for NOT operators
-     * @return the transformed SqlNode representation with NOT pushed down.
-     */
-    private static SqlNode pushDownNotForIn(SqlNode sqlNode) {
-        if ((sqlNode instanceof SqlCall) && containsInOperator(sqlNode)) {
-            SqlCall sqlCall = (SqlCall) sqlNode;
-            if ((sqlCall.getOperator() == SqlStdOperatorTable.AND) || (sqlCall.getOperator() == SqlStdOperatorTable.OR)) {
-                SqlNode[] sqlOperands = ((SqlBasicCall) sqlCall).operands;
-                for (int i = 0; i < sqlOperands.length; i++) {
-                    sqlOperands[i] = pushDownNotForIn(sqlOperands[i]);
-                }
-                return sqlNode;
-            } else if (sqlCall.getOperator() == SqlStdOperatorTable.NOT) {
-                SqlNode childNode = sqlCall.operand(0);
-                assert childNode instanceof SqlCall;
-                SqlBasicCall childSqlCall = (SqlBasicCall) childNode;
-                if (childSqlCall.getOperator() == SqlStdOperatorTable.AND) {
-                    SqlNode[] andOperands = childSqlCall.getOperands();
-                    SqlNode[] orOperands = new SqlNode[andOperands.length];
-                    for (int i = 0; i < orOperands.length; i++) {
-                        orOperands[i] = SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, andOperands[i]);
-                    }
-                    for (int i = 0; i < orOperands.length; i++) {
-                        orOperands[i] = pushDownNotForIn(orOperands[i]);
-                    }
-                    return SqlStdOperatorTable.OR.createCall(SqlParserPos.ZERO, orOperands[0], orOperands[1]);
-                } else if (childSqlCall.getOperator() == SqlStdOperatorTable.OR) {
-                    SqlNode[] orOperands = childSqlCall.getOperands();
-                    SqlNode[] andOperands = new SqlNode[orOperands.length];
-                    for (int i = 0; i < andOperands.length; i++) {
-                        andOperands[i] = SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO, orOperands[i]);
-                    }
-                    for (int i = 0; i < andOperands.length; i++) {
-                        andOperands[i] = pushDownNotForIn(andOperands[i]);
-                    }
-                    return SqlStdOperatorTable.AND.createCall(SqlParserPos.ZERO, andOperands[0], andOperands[1]);
-                } else if (childSqlCall.getOperator() == SqlStdOperatorTable.NOT) {
-                    SqlNode[] notOperands = childSqlCall.getOperands();
-                    assert notOperands.length == 1;
-                    return pushDownNotForIn(notOperands[0]);
-                } else if (childSqlCall.getOperator() instanceof SqlInOperator) {
-                    SqlNode[] inOperands = childSqlCall.getOperands();
-                    SqlInOperator inOp = (SqlInOperator) childSqlCall.getOperator();
-                    if (inOp.isNotIn()) {
-                        return SqlStdOperatorTable.IN.createCall(SqlParserPos.ZERO, inOperands[0], inOperands[1]);
-                    } else {
-                        return SqlStdOperatorTable.NOT_IN.createCall(SqlParserPos.ZERO, inOperands[0], inOperands[1]);
-                    }
-                } else {
-                    // childSqlCall is "leaf" node in a logical expression tree
-                    // (only considering AND, OR, NOT)
-                    return sqlNode;
-                }
-            } else {
-                // sqlNode is "leaf" node in a logical expression tree
-                // (only considering AND, OR, NOT)
-                return sqlNode;
-            }
-        } else {
-            // tree rooted at sqlNode does not contain inOperator
-            return sqlNode;
-        }
-    }
-
-    private static boolean containsNullLiteral(SqlNodeList valueList) {
-        for (SqlNode node : valueList.getList()) {
-            if (node instanceof SqlLiteral) {
-                SqlLiteral lit = (SqlLiteral) node;
-                if (lit.getValue() == null) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    private static JoinRelType convertJoinType(JoinType joinType) {
-        switch (joinType) {
-        case COMMA:
-        case INNER:
-        case CROSS:
-            return JoinRelType.INNER;
-        case FULL:
-            return JoinRelType.FULL;
-        case LEFT:
-            return JoinRelType.LEFT;
-        case RIGHT:
-            return JoinRelType.RIGHT;
-        default:
-            throw Util.unexpected(joinType);
-        }
-    }
-
-    private static boolean desc(RelFieldCollation.Direction direction) {
-        switch (direction) {
-        case DESCENDING:
-        case STRICTLY_DESCENDING:
-            return true;
-        default:
-            return false;
-        }
-    }
-
-    /** Creates a builder for a {@link Config}. */
-    public static ConfigBuilder configBuilder() {
-        return new ConfigBuilder();
-    }
-
     /**
      * @return the RelOptCluster in use.
      */
@@ -490,7 +378,7 @@ public class SqlToRelConverter {
     }
 
     /**
-     * @return mapping of non-correlated subqueries that have been converted to
+     * @return mapping of non-correlated sub-queries that have been converted to
      * the constants that they evaluate to
      */
     public Map<SqlNode, RexNode> getMapConvertedNonCorrSubqs() {
@@ -498,13 +386,14 @@ public class SqlToRelConverter {
     }
 
     /**
-     * Adds to the current map of non-correlated converted subqueries the
-     * elements from another map that contains non-correlated subqueries that
+     * Adds to the current map of non-correlated converted sub-queries the
+     * elements from another map that contains non-correlated sub-queries that
      * have been converted by another SqlToRelConverter.
      *
      * @param alreadyConvertedNonCorrSubqs the other map
      */
-    public void addConvertedNonCorrSubqs(Map<SqlNode, RexNode> alreadyConvertedNonCorrSubqs) {
+    public void addConvertedNonCorrSubqs(
+            Map<SqlNode, RexNode> alreadyConvertedNonCorrSubqs) {
         mapConvertedNonCorrSubqs.putAll(alreadyConvertedNonCorrSubqs);
     }
 
@@ -519,13 +408,13 @@ public class SqlToRelConverter {
     }
 
     /**
-     * Sets a new SubqueryConverter. To have any effect, this must be called
+     * Sets a new SubQueryConverter. To have any effect, this must be called
      * before any convert method.
      *
-     * @param converter new SubqueryConverter
+     * @param converter new SubQueryConverter
      */
-    public void setSubqueryConverter(SubqueryConverter converter) {
-        subqueryConverter = converter;
+    public void setSubQueryConverter(SubQueryConverter converter) {
+        subQueryConverter = converter;
     }
 
     /**
@@ -548,24 +437,42 @@ public class SqlToRelConverter {
         // SQL statement is something like an INSERT which has no
         // validator type information associated with its result,
         // hence the namespace check above.)
-        final List<RelDataTypeField> validatedFields = validator.getValidatedNodeType(query).getFieldList();
-        final RelDataType validatedRowType = validator.getTypeFactory().createStructType(Pair.right(validatedFields), SqlValidatorUtil.uniquify(Pair.left(validatedFields), catalogReader.isCaseSensitive()));
-
-        final List<RelDataTypeField> convertedFields = result.getRowType().getFieldList().subList(0, validatedFields.size());
-        final RelDataType convertedRowType = validator.getTypeFactory().createStructType(convertedFields);
-
-        if (!RelOptUtil.equal("validated row type", validatedRowType, "converted row type", convertedRowType, Litmus.IGNORE)) {
-            throw new AssertionError("Conversion to relational algebra failed to " + "preserve datatypes:\n" + "validated type:\n" + validatedRowType.getFullTypeString() + "\nconverted type:\n" + convertedRowType.getFullTypeString() + "\nrel:\n" + RelOptUtil.toString(result));
+        final List<RelDataTypeField> validatedFields =
+                validator.getValidatedNodeType(query).getFieldList();
+        final RelDataType validatedRowType =
+                validator.getTypeFactory().createStructType(
+                        Pair.right(validatedFields),
+                        SqlValidatorUtil.uniquify(Pair.left(validatedFields),
+                                catalogReader.isCaseSensitive()));
+
+        final List<RelDataTypeField> convertedFields =
+                result.getRowType().getFieldList().subList(0, validatedFields.size());
+        final RelDataType convertedRowType =
+                validator.getTypeFactory().createStructType(convertedFields);
+
+        if (!RelOptUtil.equal("validated row type", validatedRowType,
+                "converted row type", convertedRowType, Litmus.IGNORE)) {
+            throw new AssertionError("Conversion to relational algebra failed to "
+                    + "preserve datatypes:\n"
+                    + "validated type:\n"
+                    + validatedRowType.getFullTypeString()
+                    + "\nconverted type:\n"
+                    + convertedRowType.getFullTypeString()
+                    + "\nrel:\n"
+                    + RelOptUtil.toString(result));
         }
     }
 
-    public RelNode flattenTypes(RelNode rootRel, boolean restructure) {
-        RelStructuredTypeFlattener typeFlattener = new RelStructuredTypeFlattener(rexBuilder, createToRelContext());
-        return typeFlattener.rewrite(rootRel, restructure);
+    public RelNode flattenTypes(
+            RelNode rootRel,
+            boolean restructure) {
+        RelStructuredTypeFlattener typeFlattener =
+                new RelStructuredTypeFlattener(rexBuilder, createToRelContext(), restructure);
+        return typeFlattener.rewrite(rootRel);
     }
 
     /**
-     * If subquery is correlated and decorrelation is enabled, performs
+     * If sub-query is correlated and decorrelation is enabled, performs
      * decorrelation.
      *
      * @param query   Query
@@ -606,14 +513,21 @@ public class SqlToRelConverter {
         // Trim fields that are not used by their consumer.
         if (isTrimUnusedFields()) {
             final RelFieldTrimmer trimmer = newFieldTrimmer();
-            final List<RelCollation> collations = rootRel.getTraitSet().getTraits(RelCollationTraitDef.INSTANCE);
+            final List<RelCollation> collations =
+                    rootRel.getTraitSet().getTraits(RelCollationTraitDef.INSTANCE);
             rootRel = trimmer.trim(rootRel);
-            if (!ordered && collations != null && !collations.isEmpty() && !collations.equals(ImmutableList.of(RelCollations.EMPTY))) {
-                final RelTraitSet traitSet = rootRel.getTraitSet().replace(RelCollationTraitDef.INSTANCE, collations);
+            if (!ordered
+                    && collations != null
+                    && !collations.isEmpty()
+                    && !collations.equals(ImmutableList.of(RelCollations.EMPTY))) {
+                final RelTraitSet traitSet = rootRel.getTraitSet()
+                        .replace(RelCollationTraitDef.INSTANCE, collations);
                 rootRel = rootRel.copy(traitSet, rootRel.getInputs());
             }
             if (SQL2REL_LOGGER.isDebugEnabled()) {
-                SQL2REL_LOGGER.debug(RelOptUtil.dumpPlan("Plan after trimming unused fields", rootRel, false, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
+                SQL2REL_LOGGER.debug(
+                        RelOptUtil.dumpPlan("Plan after trimming unused fields", rootRel,
+                                SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
             }
         }
         return rootRel;
@@ -625,7 +539,8 @@ public class SqlToRelConverter {
      * @return Field trimmer
      */
     protected RelFieldTrimmer newFieldTrimmer() {
-        final RelBuilder relBuilder = RelFactories.LOGICAL_BUILDER.create(cluster, null);
+        final RelBuilder relBuilder =
+                RelFactories.LOGICAL_BUILDER.create(cluster, null);
         return new RelFieldTrimmer(validator, relBuilder);
     }
 
@@ -640,14 +555,18 @@ public class SqlToRelConverter {
      *                        will become a JDBC result set; <code>false</code> if
      *                        the query will be part of a view.
      */
-    public RelRoot convertQuery(SqlNode query, final boolean needsValidation, final boolean top) {
+    public RelRoot convertQuery(
+            SqlNode query,
+            final boolean needsValidation,
+            final boolean top) {
         SqlNode origQuery = query; /* OVERRIDE POINT */
-        
+
         if (needsValidation) {
             query = validator.validate(query);
         }
 
-        RelMetadataQuery.THREAD_PROVIDERS.set(JaninoRelMetadataProvider.of(cluster.getMetadataProvider()));
+        RelMetadataQuery.THREAD_PROVIDERS.set(
+                JaninoRelMetadataProvider.of(cluster.getMetadataProvider()));
         RelNode result = convertQueryRecursive(query, top, null).rel;
         if (top) {
             if (isStream(query)) {
@@ -663,18 +582,23 @@ public class SqlToRelConverter {
         checkConvertedType(query, result);
 
         if (SQL2REL_LOGGER.isDebugEnabled()) {
-            SQL2REL_LOGGER.debug(RelOptUtil.dumpPlan("Plan after converting SqlNode to RelNode", result, false, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
+            SQL2REL_LOGGER.debug(
+                    RelOptUtil.dumpPlan("Plan after converting SqlNode to RelNode",
+                            result, SqlExplainFormat.TEXT,
+                            SqlExplainLevel.EXPPLAN_ATTRIBUTES));
         }
 
         final RelDataType validatedRowType = validator.getValidatedNodeType(query);
-        return hackSelectStar(origQuery, RelRoot.of(result, validatedRowType, query.getKind()).withCollation(collation));
+        RelRoot origResult =  RelRoot.of(result, validatedRowType, query.getKind())
+                .withCollation(collation);
+        return hackSelectStar(origQuery, origResult);
     }
 
     /* OVERRIDE POINT */
     private RelRoot hackSelectStar(SqlNode query, RelRoot root) {
         /*
          * Rel tree is like:
-         * 
+         *
          *   LogicalSort (optional)
          *    |- LogicalProject
          *        |- LogicalFilter (optional)
@@ -690,7 +614,7 @@ public class SqlToRelConverter {
         } else {
             return root;
         }
-        
+
         RelNode input = rootPrj.getInput();
         if (!(//
                 input.getClass().getSimpleName().equals("OLAPTableScan")//
@@ -700,13 +624,13 @@ public class SqlToRelConverter {
 
         if (rootPrj.getRowType().getFieldCount() < input.getRowType().getFieldCount())
             return root;
-        
+
         RelDataType inType = rootPrj.getRowType();
         List<String> inFields = inType.getFieldNames();
         List<RexNode> projExp = new ArrayList<>();
         List<Pair<Integer, String>> projFields = new ArrayList<>();
-        FieldInfoBuilder projTypeBuilder = getCluster().getTypeFactory().builder();
-        FieldInfoBuilder validTypeBuilder = getCluster().getTypeFactory().builder();
+        RelDataTypeFactory.FieldInfoBuilder projTypeBuilder = getCluster().getTypeFactory().builder();
+        RelDataTypeFactory.FieldInfoBuilder validTypeBuilder = getCluster().getTypeFactory().builder();
         for (int i = 0; i < inFields.size(); i++) {
             if (!inFields.get(i).startsWith("_KY_")) {
                 projExp.add(rootPrj.getProjects().get(i));
@@ -721,15 +645,34 @@ public class SqlToRelConverter {
         if (rootSort != null) {
             rootSort = (LogicalSort) rootSort.copy(rootSort.getTraitSet(), rootPrj, rootSort.collation, rootSort.offset, rootSort.fetch);
         }
-        
+
         RelDataType validRowType = getCluster().getTypeFactory().createStructType(validTypeBuilder);
         root = new RelRoot(rootSort == null ? rootPrj : rootSort, validRowType, root.kind, projFields, root.collation);
-        
+
         validator.setValidatedNodeType(query, validRowType);
-        
+
         return root;
     }
 
+    private static boolean isStream(SqlNode query) {
+        return query instanceof SqlSelect
+                && ((SqlSelect) query).isKeywordPresent(SqlSelectKeyword.STREAM);
+    }
+
+    public static boolean isOrdered(SqlNode query) {
+        switch (query.getKind()) {
+            case SELECT:
+                return ((SqlSelect) query).getOrderList() != null
+                        && ((SqlSelect) query).getOrderList().size() > 0;
+            case WITH:
+                return isOrdered(((SqlWith) query).body);
+            case ORDER_BY:
+                return ((SqlOrderBy) query).orderList.size() > 0;
+            default:
+                return false;
+        }
+    }
+
     private RelCollation requiredCollation(RelNode r) {
         if (r instanceof Sort) {
             return ((Sort) r).collation;
@@ -756,7 +699,8 @@ public class SqlToRelConverter {
     /**
      * Factory method for creating translation workspace.
      */
-    protected Blackboard createBlackboard(SqlValidatorScope scope, Map<String, RexNode> nameToNodeMap, boolean top) {
+    protected Blackboard createBlackboard(SqlValidatorScope scope,
+                                          Map<String, RexNode> nameToNodeMap, boolean top) {
         return new Blackboard(scope, nameToNodeMap, top);
     }
 
@@ -764,25 +708,45 @@ public class SqlToRelConverter {
      * Implementation of {@link #convertSelect(SqlSelect, boolean)};
      * derived class may override.
      */
-    protected void convertSelectImpl(final Blackboard bb, SqlSelect select) {
-        convertFrom(bb, select.getFrom());
-        convertWhere(bb, select.getWhere());
+    protected void convertSelectImpl(
+            final Blackboard bb,
+            SqlSelect select) {
+        convertFrom(
+                bb,
+                select.getFrom());
+        convertWhere(
+                bb,
+                select.getWhere());
 
         final List<SqlNode> orderExprList = new ArrayList<>();
         final List<RelFieldCollation> collationList = new ArrayList<>();
-        gatherOrderExprs(bb, select, select.getOrderList(), orderExprList, collationList);
-        final RelCollation collation = cluster.traitSet().canonize(RelCollations.of(collationList));
+        gatherOrderExprs(
+                bb,
+                select,
+                select.getOrderList(),
+                orderExprList,
+                collationList);
+        final RelCollation collation =
+                cluster.traitSet().canonize(RelCollations.of(collationList));
 
         if (validator.isAggregate(select)) {
-            convertAgg(bb, select, orderExprList);
+            convertAgg(
+                    bb,
+                    select,
+                    orderExprList);
         } else {
-            convertSelectList(bb, select, orderExprList);
+            convertSelectList(
+                    bb,
+                    select,
+                    orderExprList);
         }
 
         if (select.isDistinct()) {
             distinctify(bb, true);
         }
-        convertOrder(select, bb, collation, orderExprList, select.getOffset(), select.getFetch());
+        convertOrder(
+                select, bb, collation, orderExprList, select.getOffset(),
+                select.getFetch());
         bb.setRoot(bb.root, true);
     }
 
@@ -798,7 +762,9 @@ public class SqlToRelConverter {
      * @param bb               Blackboard
      * @param checkForDupExprs Check for duplicate expressions
      */
-    private void distinctify(Blackboard bb, boolean checkForDupExprs) {
+    private void distinctify(
+            Blackboard bb,
+            boolean checkForDupExprs) {
         // Look for duplicate expressions in the project.
         // Say we have 'select x, y, x, z'.
         // Then dups will be {[2, 0]}
@@ -832,7 +798,9 @@ public class SqlToRelConverter {
                     newProjects.add(RexInputRef.of2(i, fields));
                 }
             }
-            rel = LogicalProject.create(rel, Pair.left(newProjects), Pair.right(newProjects));
+            rel =
+                    LogicalProject.create(rel, Pair.left(newProjects),
+                            Pair.right(newProjects));
             bb.root = rel;
             distinctify(bb, false);
             rel = bb.root;
@@ -843,21 +811,34 @@ public class SqlToRelConverter {
             for (int i = 0; i < fields.size(); i++) {
                 final int origin = origins.get(i);
                 RelDataTypeField field = fields.get(i);
-                undoProjects.add(Pair.of((RexNode) new RexInputRef(squished.get(origin), field.getType()), field.getName()));
+                undoProjects.add(
+                        Pair.of(
+                                (RexNode) new RexInputRef(
+                                        squished.get(origin), field.getType()),
+                                field.getName()));
             }
 
-            rel = LogicalProject.create(rel, Pair.left(undoProjects), Pair.right(undoProjects));
-            bb.setRoot(rel, false);
+            rel =
+                    LogicalProject.create(rel, Pair.left(undoProjects),
+                            Pair.right(undoProjects));
+            bb.setRoot(
+                    rel,
+                    false);
 
             return;
         }
 
         // Usual case: all of the expressions in the SELECT clause are
         // different.
-        final ImmutableBitSet groupSet = ImmutableBitSet.range(rel.getRowType().getFieldCount());
-        rel = createAggregate(bb, false, groupSet, ImmutableList.of(groupSet), ImmutableList.<AggregateCall> of());
-
-        bb.setRoot(rel, false);
+        final ImmutableBitSet groupSet =
+                ImmutableBitSet.range(rel.getRowType().getFieldCount());
+        rel =
+                createAggregate(bb, false, groupSet, ImmutableList.of(groupSet),
+                        ImmutableList.<AggregateCall>of());
+
+        bb.setRoot(
+                rel,
+                false);
     }
 
     private int findExpr(RexNode seek, List<RexNode> exprs, int count) {
@@ -882,16 +863,29 @@ public class SqlToRelConverter {
      *                      returning first row
      * @param fetch         Expression for number of rows to fetch
      */
-    protected void convertOrder(SqlSelect select, Blackboard bb, RelCollation collation, List<SqlNode> orderExprList, SqlNode offset, SqlNode fetch) {
-        if (select.getOrderList() == null || select.getOrderList().getList().isEmpty()) {
+    protected void convertOrder(
+            SqlSelect select,
+            Blackboard bb,
+            RelCollation collation,
+            List<SqlNode> orderExprList,
+            SqlNode offset,
+            SqlNode fetch) {
+        if (select.getOrderList() == null
+                || select.getOrderList().getList().isEmpty()) {
             assert collation.getFieldCollations().isEmpty();
-            if ((offset == null || ((SqlLiteral) offset).bigDecimalValue().equals(BigDecimal.ZERO)) && fetch == null) {
+            if ((offset == null
+                    || ((SqlLiteral) offset).bigDecimalValue().equals(BigDecimal.ZERO))
+                    && fetch == null) {
                 return;
             }
         }
 
         // Create a sorter using the previously constructed collations.
-        bb.setRoot(LogicalSort.create(bb.root, collation, offset == null ? null : convertExpression(offset), fetch == null ? null : convertExpression(fetch)), false);
+        bb.setRoot(
+                LogicalSort.create(bb.root, collation,
+                        offset == null ? null : convertExpression(offset),
+                        fetch == null ? null : convertExpression(fetch)),
+                false);
 
         // If extra expressions were added to the project list for sorting,
         // add another project to remove them. But make the collation empty, because
@@ -901,300 +895,492 @@ public class SqlToRelConverter {
         if (orderExprList.size() > 0 && !bb.top) {
             final List<RexNode> exprs = new ArrayList<>();
             final RelDataType rowType = bb.root.getRowType();
-            final int fieldCount = rowType.getFieldCount() - orderExprList.size();
+            final int fieldCount =
+                    rowType.getFieldCount() - orderExprList.size();
             for (int i = 0; i < fieldCount; i++) {
                 exprs.add(rexBuilder.makeInputRef(bb.root, i));
             }
-            bb.setRoot(LogicalProject.create(bb.root, exprs, rowType.getFieldNames().subList(0, fieldCount)), false);
+            bb.setRoot(
+                    LogicalProject.create(bb.root, exprs,
+                            rowType.getFieldNames().subList(0, fieldCount)),
+                    false);
         }
     }
 
     /**
-     * Converts a WHERE clause.
+     * Returns whether a given node contains a {@link SqlInOperator}.
      *
-     * @param bb    Blackboard
-     * @param where WHERE clause, may be null
+     * @param node a RexNode tree
      */
-    private void convertWhere(final Blackboard bb, final SqlNode where) {
-        if (where == null) {
-            return;
-        }
-        SqlNode newWhere = pushDownNotForIn(where);
-        replaceSubqueries(bb, newWhere, RelOptUtil.Logic.UNKNOWN_AS_FALSE);
-        final RexNode convertedWhere = bb.convertExpression(newWhere);
-
-        // only allocate filter if the condition is not TRUE
-        if (convertedWhere.isAlwaysTrue()) {
-            return;
-        }
-
-        final RelNode filter = RelOptUtil.createFilter(bb.root, convertedWhere);
-        final RelNode r;
-        final CorrelationUse p = getCorrelationUse(bb, filter);
-        if (p != null) {
-            assert p.r instanceof Filter;
-            Filter f = (Filter) p.r;
-            r = LogicalFilter.create(f.getInput(), f.getCondition(), ImmutableSet.of(p.id));
-        } else {
-            r = filter;
-        }
-
-        bb.setRoot(r, false);
-    }
-
-    private void replaceSubqueries(final Blackboard bb, final SqlNode expr, RelOptUtil.Logic logic) {
-        findSubqueries(bb, expr, logic, false);
-        for (SubQuery node : bb.subqueryList) {
-            substituteSubquery(bb, node);
+    private static boolean containsInOperator(
+            SqlNode node) {
+        try {
+            SqlVisitor<Void> visitor =
+                    new SqlBasicVisitor<Void>() {
+                        public Void visit(SqlCall call) {
+                            if (call.getOperator() instanceof SqlInOperator) {
+                                throw new Util.FoundOne(call);
+                            }
+                            return super.visit(call);
+                        }
+                    };
+            node.accept(visitor);
+            return false;
+        } catch (Util.FoundOne e) {
+            Util.swallow(e, null);
+            return true;
         }
     }
 
-    private void substituteSubquery(Blackboard bb, SubQuery subQuery) {
-        final RexNode expr = subQuery.expr;
-        if (expr != null) {
-            // Already done.
-            return;
-        }
-
-        final SqlBasicCall call;
-        final RelNode rel;
-        final SqlNode query;
-        final Pair<RelNode, Boolean> converted;
-        switch (subQuery.node.getKind()) {
-        case CURSOR:
-            convertCursor(bb, subQuery);
-            return;
-
-        case MULTISET_QUERY_CONSTRUCTOR:
-        case MULTISET_VALUE_CONSTRUCTOR:
-        case ARRAY_QUERY_CONSTRUCTOR:
-            rel = convertMultisets(ImmutableList.of(subQuery.node), bb);
-            subQuery.expr = bb.register(rel, JoinRelType.INNER);
-            return;
-
-        case IN:
-            call = (SqlBasicCall) subQuery.node;
-            query = call.operand(1);
-            if (!config.isExpand() && !(query instanceof SqlNodeList)) {
-                return;
-            }
-            final SqlNode leftKeyNode = call.operand(0);
-
-            final List<RexNode> leftKeys;
-            switch (leftKeyNode.getKind()) {
-            case ROW:
-                leftKeys = Lists.newArrayList();
-                for (SqlNode sqlExpr : ((SqlBasicCall) leftKeyNode).getOperandList()) {
-                    leftKeys.add(bb.convertExpression(sqlExpr));
-                }
-                break;
-            default:
-                leftKeys = ImmutableList.of(bb.convertExpression(leftKeyNode));
-            }
-
-            final boolean isNotIn = ((SqlInOperator) call.getOperator()).isNotIn();
-            if (query instanceof SqlNodeList) {
-                SqlNodeList valueList = (SqlNodeList) query;
-                if (!containsNullLiteral(valueList) && valueList.size() < getInSubqueryThreshold()) {
-                    // We're under the threshold, so convert to OR.
-                    subQuery.expr = convertInToOr(bb, leftKeys, valueList, isNotIn);
-                    return;
-                }
-
-                // Otherwise, let convertExists translate
-                // values list into an inline table for the
-                // reference to Q below.
-            }
-
-            // Project out the search columns from the left side
-
-            //  Q1:
-            // "select from emp where emp.deptno in (select col1 from T)"
-            //
-            // is converted to
-            //
-            // "select from
-            //   emp inner join (select distinct col1 from T)) q
-            //   on emp.deptno = q.col1
-            //
-            // Q2:
-            // "select from emp where emp.deptno not in (Q)"
-            //
-            // is converted to
-            //
-            // "select from
-            //   emp left outer join (select distinct col1, TRUE from T) q
-            //   on emp.deptno = q.col1
-            //   where emp.deptno <> null
-            //         and q.indicator <> TRUE"
-            //
-            final boolean outerJoin = bb.subqueryNeedsOuterJoin || isNotIn || subQuery.logic == RelOptUtil.Logic.TRUE_FALSE_UNKNOWN;
-            final RelDataType targetRowType = SqlTypeUtil.promoteToRowType(typeFactory, validator.getValidatedNodeType(leftKeyNode), null);
-            converted = convertExists(query, RelOptUtil.SubqueryType.IN, subQuery.logic, outerJoin, targetRowType);
-            if (converted.right) {
-                // Generate
-                //    emp CROSS JOIN (SELECT COUNT(*) AS c,
-                //                       COUNT(deptno) AS ck FROM dept)
-                final RelDataType longType = typeFactory.createSqlType(SqlTypeName.BIGINT);
-                final RelNode seek = converted.left.getInput(0); // fragile
-                final int keyCount = leftKeys.size();
-                final List<Integer> args = ImmutableIntList.range(0, keyCount);
-                LogicalAggregate aggregate = LogicalAggregate.create(seek, false, ImmutableBitSet.of(), null, ImmutableList.of(AggregateCall.create(SqlStdOperatorTable.COUNT, false, ImmutableList.<Integer> of(), -1, longType, null), AggregateCall.create(SqlStdOperatorTable.COUNT, false, args, -1, longType, null)));
-                LogicalJoin join = LogicalJoin.create(bb.root, aggregate, rexBuilder.makeLiteral(true), ImmutableSet.<CorrelationId> of(), JoinRelType.INNER);
-                bb.setRoot(join, false);
-            }
-            RexNode rex = bb.register(converted.left, outerJoin ? JoinRelType.LEFT : JoinRelType.INNER, leftKeys);
-
-            subQuery.expr = translateIn(subQuery, bb.root, rex);
-            if (isNotIn) {
-                subQuery.expr = rexBuilder.makeCall(SqlStdOperatorTable.NOT, subQuery.expr);
+    /**
+     * Push down all the NOT logical operators into any IN/NOT IN operators.
+     *
+     * @param sqlNode the root node from which to look for NOT operators
+     * @return the transformed SqlNode representation with NOT pushed down.
+     */
+    private static SqlNode pushDownNotForIn(SqlNode sqlNode) {
+        if ((sqlNode instanceof SqlCall) && containsInOperator(sqlNode)) {
+            SqlCall sqlCall = (SqlCall) sqlNode;
+            if ((sqlCall.getOperator() == SqlStdOperatorTable.AND)
+                    || (sqlCall.getOperator() == SqlStdOperatorTable.OR)) {
+                SqlNode[] sqlOperands = ((SqlBasicCall) sqlCall).operands;
+                for (int i = 0; i < sqlOperands.length; i++) {
+                    sqlOperands[i] = pushDownNotForIn(sqlOperands[i]);
+                }
+                return sqlNode;
+            } else if (sqlCall.getOperator() == SqlStdOperatorTable.NOT) {
+                SqlNode childNode = sqlCall.operand(0);
+                assert childNode instanceof SqlCall;
+                SqlBasicCall childSqlCall = (SqlBasicCall) childNode;
+                if (childSqlCall.getOperator() == SqlStdOperatorTable.AND) {
+                    SqlNode[] andOperands = childSqlCall.getOperands();
+                    SqlNode[] orOperands = new SqlNode[andOperands.length];
+                    for (int i = 0; i < orOperands.length; i++) {
+                        orOperands[i] =
+                                SqlStdOperatorTable.NOT.createCall(
+                                        SqlParserPos.ZERO,
+                                        andOperands[i]);
+                    }
+                    for (int i = 0; i < orOperands.length; i++) {
+                        orOperands[i] = pushDownNotForIn(orOperands[i]);
+                    }
+                    return SqlStdOperatorTable.OR.createCall(SqlParserPos.ZERO,
+                            orOperands[0], orOperands[1]);
+                } else if (childSqlCall.getOperator() == SqlStdOperatorTable.OR) {
+                    SqlNode[] orOperands = childSqlCall.getOperands();
+                    SqlNode[] andOperands = new SqlNode[orOperands.length];
+                    for (int i = 0; i < andOperands.length; i++) {
+                        andOperands[i] =
+                                SqlStdOperatorTable.NOT.createCall(
+                                        SqlParserPos.ZERO,
+                                        orOperands[i]);
+                    }
+                    for (int i = 0; i < andOperands.length; i++) {
+                        andOperands[i] = pushDownNotForIn(andOperands[i]);
+                    }
+                    return SqlStdOperatorTable.AND.createCall(SqlParserPos.ZERO,
+                            andOperands[0], andOperands[1]);
+                } else if (childSqlCall.getOperator() == SqlStdOperatorTable.NOT) {
+                    SqlNode[] notOperands = childSqlCall.getOperands();
+                    assert notOperands.length == 1;
+                    return pushDownNotForIn(notOperands[0]);
+                } else if (childSqlCall.getOperator() instanceof SqlInOperator) {
+                    SqlNode[] inOperands = childSqlCall.getOperands();
+                    SqlInOperator inOp =
+                            (SqlInOperator) childSqlCall.getOperator();
+                    if (inOp.isNotIn()) {
+                        return SqlStdOperatorTable.IN.createCall(
+                                SqlParserPos.ZERO,
+                                inOperands[0],
+                                inOperands[1]);
+                    } else {
+                        return SqlStdOperatorTable.NOT_IN.createCall(
+                                SqlParserPos.ZERO,
+                                inOperands[0],
+                                inOperands[1]);
+                    }
+                } else {
+                    // childSqlCall is "leaf" node in a logical expression tree
+                    // (only considering AND, OR, NOT)
+                    return sqlNode;
+                }
+            } else {
+                // sqlNode is "leaf" node in a logical expression tree
+                // (only considering AND, OR, NOT)
+                return sqlNode;
             }
+        } else {
+            // tree rooted at sqlNode does not contain inOperator
+            return sqlNode;
+        }
+    }
+
+    /**
+     * Converts a WHERE clause.
+     *
+     * @param bb    Blackboard
+     * @param where WHERE clause, may be null
+     */
+    private void convertWhere(
+            final Blackboard bb,
+            final SqlNode where) {
+        if (where == null) {
             return;
+        }
+        SqlNode newWhere = pushDownNotForIn(where);
+        replaceSubQueries(bb, newWhere, RelOptUtil.Logic.UNKNOWN_AS_FALSE);
+        final RexNode convertedWhere = bb.convertExpression(newWhere);
 
-        case EXISTS:
-            // "select from emp where exists (select a from T)"
-            //
-            // is converted to the following if the subquery is correlated:
-            //
-            // "select from emp left outer join (select AGG_TRUE() as indicator
-            // from T group by corr_var) q where q.indicator is true"
-            //
-            // If there is no correlation, the expression is replaced with a
-            // boolean indicating whether the subquery returned 0 or >= 1 row.
-            call = (SqlBasicCall) subQuery.node;
-            query = call.operand(0);
-            if (!config.isExpand()) {
+        // only allocate filter if the condition is not TRUE
+        if (convertedWhere.isAlwaysTrue()) {
+            return;
+        }
+
+        final RelFactories.FilterFactory factory =
+                RelFactories.DEFAULT_FILTER_FACTORY;
+        final RelNode filter = factory.createFilter(bb.root, convertedWhere);
+        final RelNode r;
+        final CorrelationUse p = getCorrelationUse(bb, filter);
+        if (p != null) {
+            assert p.r instanceof Filter;
+            Filter f = (Filter) p.r;
+            r = LogicalFilter.create(f.getInput(), f.getCondition(),
+                    ImmutableSet.of(p.id));
+        } else {
+            r = filter;
+        }
+
+        bb.setRoot(r, false);
+    }
+
+    private void replaceSubQueries(
+            final Blackboard bb,
+            final SqlNode expr,
+            RelOptUtil.Logic logic) {
+        findSubQueries(bb, expr, logic, false);
+        for (SubQuery node : bb.subQueryList) {
+            substituteSubQuery(bb, node);
+        }
+    }
+
+    private void substituteSubQuery(Blackboard bb, SubQuery subQuery) {
+        final RexNode expr = subQuery.expr;
+        if (expr != null) {
+            // Already done.
+            return;
+        }
+
+        final SqlBasicCall call;
+        final RelNode rel;
+        final SqlNode query;
+        final RelOptUtil.Exists converted;
+        switch (subQuery.node.getKind()) {
+            case CURSOR:
+                convertCursor(bb, subQuery);
                 return;
-            }
-            converted = convertExists(query, RelOptUtil.SubqueryType.EXISTS, subQuery.logic, true, null);
-            assert !converted.right;
-            if (convertNonCorrelatedSubQuery(subQuery, bb, converted.left, true)) {
+
+            case MULTISET_QUERY_CONSTRUCTOR:
+            case MULTISET_VALUE_CONSTRUCTOR:
+            case ARRAY_QUERY_CONSTRUCTOR:
+                rel = convertMultisets(ImmutableList.of(subQuery.node), bb);
+                subQuery.expr = bb.register(rel, JoinRelType.INNER);
                 return;
-            }
-            subQuery.expr = bb.register(converted.left, JoinRelType.LEFT);
-            return;
 
-        case SCALAR_QUERY:
-            // Convert the subquery.  If it's non-correlated, convert it
-            // to a constant expression.
-            if (!config.isExpand()) {
+            case IN:
+                call = (SqlBasicCall) subQuery.node;
+                query = call.operand(1);
+                if (!config.isExpand() && !(query instanceof SqlNodeList)) {
+                    return;
+                }
+                final SqlNode leftKeyNode = call.operand(0);
+
+                final List<RexNode> leftKeys;
+                switch (leftKeyNode.getKind()) {
+                    case ROW:
+                        leftKeys = Lists.newArrayList();
+                        for (SqlNode sqlExpr : ((SqlBasicCall) leftKeyNode).getOperandList()) {
+                            leftKeys.add(bb.convertExpression(sqlExpr));
+                        }
+                        break;
+                    default:
+                        leftKeys = ImmutableList.of(bb.convertExpression(leftKeyNode));
+                }
+
+                final boolean notIn = ((SqlInOperator) call.getOperator()).isNotIn();
+                if (query instanceof SqlNodeList) {
+                    SqlNodeList valueList = (SqlNodeList) query;
+                    if (!containsNullLiteral(valueList)
+                            && valueList.size() < config.getInSubQueryThreshold()) {
+                        // We're under the threshold, so convert to OR.
+                        subQuery.expr =
+                                convertInToOr(
+                                        bb,
+                                        leftKeys,
+                                        valueList,
+                                        notIn);
+                        return;
+                    }
+
+                    // Otherwise, let convertExists translate
+                    // values list into an inline table for the
+                    // reference to Q below.
+                }
+
+                // Project out the search columns from the left side
+
+                // Q1:
+                // "select from emp where emp.deptno in (select col1 from T)"
+                //
+                // is converted to
+                //
+                // "select from
+                //   emp inner join (select distinct col1 from T)) q
+                //   on emp.deptno = q.col1
+                //
+                // Q2:
+                // "select from emp where emp.deptno not in (Q)"
+                //
+                // is converted to
+                //
+                // "select from
+                //   emp left outer join (select distinct col1, TRUE from T) q
+                //   on emp.deptno = q.col1
+                //   where emp.deptno <> null
+                //         and q.indicator <> TRUE"
+                //
+                final RelDataType targetRowType =
+                        SqlTypeUtil.promoteToRowType(typeFactory,
+                                validator.getValidatedNodeType(leftKeyNode), null);
+                converted =
+                        convertExists(query, RelOptUtil.SubQueryType.IN, subQuery.logic,
+                                notIn, targetRowType);
+                if (converted.indicator) {
+                    // Generate
+                    //    emp CROSS JOIN (SELECT COUNT(*) AS c,
+                    //                       COUNT(deptno) AS ck FROM dept)
+                    final RelDataType longType =
+                            typeFactory.createSqlType(SqlTypeName.BIGINT);
+                    final RelNode seek = converted.r.getInput(0); // fragile
+                    final int keyCount = leftKeys.size();
+                    final List<Integer> args = ImmutableIntList.range(0, keyCount);
+                    LogicalAggregate aggregate =
+                            LogicalAggregate.create(seek, false, ImmutableBitSet.of(), null,
+                                    ImmutableList.of(
+                                            AggregateCall.create(SqlStdOperatorTable.COUNT, false,
+                                                    ImmutableList.<Integer>of(), -1, longType, null),
+                                            AggregateCall.create(SqlStdOperatorTable.COUNT, false,
+                                                    args, -1, longType, null)));
+                    LogicalJoin join =
+                            LogicalJoin.create(bb.root, aggregate, rexBuilder.makeLiteral(true),
+                                    ImmutableSet.<CorrelationId>of(), JoinRelType.INNER);
+                    bb.setRoot(join, false);
+                }
+                final RexNode rex =
+                        bb.register(converted.r,
+                                converted.outerJoin ? JoinRelType.LEFT : JoinRelType.INNER,
+                                leftKeys);
+
+                RelOptUtil.Logic logic = subQuery.logic;
+                switch (logic) {
+                    case TRUE_FALSE_UNKNOWN:
+                    case UNKNOWN_AS_TRUE:
+                        if (!converted.indicator) {
+                            logic = RelOptUtil.Logic.TRUE_FALSE;
+                        }
+                }
+                subQuery.expr = translateIn(logic, bb.root, rex);
+                if (notIn) {
+                    subQuery.expr =
+                            rexBuilder.makeCall(SqlStdOperatorTable.NOT, subQuery.expr);
+                }
                 return;
-            }
-            call = (SqlBasicCall) subQuery.node;
-            query = call.operand(0);
-            converted = convertExists(query, RelOptUtil.SubqueryType.SCALAR, subQuery.logic, true, null);
-            assert !converted.right;
-            if (convertNonCorrelatedSubQuery(subQuery, bb, converted.left, false)) {
+
+            case EXISTS:
+                // "select from emp where exists (select a from T)"
+                //
+                // is converted to the following if the sub-query is correlated:
+                //
+                // "select from emp left outer join (select AGG_TRUE() as indicator
+                // from T group by corr_var) q where q.indicator is true"
+                //
+                // If there is no correlation, the expression is replaced with a
+                // boolean indicating whether the sub-query returned 0 or >= 1 row.
+                call = (SqlBasicCall) subQuery.node;
+                query = call.operand(0);
+                if (!config.isExpand()) {
+                    return;
+                }
+                converted = convertExists(query, RelOptUtil.SubQueryType.EXISTS,
+                        subQuery.logic, true, null);
+                assert !converted.indicator;
+                if (convertNonCorrelatedSubQuery(subQuery, bb, converted.r, true)) {
+                    return;
+                }
+                subQuery.expr = bb.register(converted.r, JoinRelType.LEFT);
                 return;
-            }
-            rel = convertToSingleValueSubq(query, converted.left);
-            subQuery.expr = bb.register(rel, JoinRelType.LEFT);
-            return;
 
-        case SELECT:
-            // This is used when converting multiset queries:
-            //
-            // select * from unnest(select multiset[deptno] from emps);
-            //
-            converted = convertExists(subQuery.node, RelOptUtil.SubqueryType.SCALAR, subQuery.logic, true, null);
-            assert !converted.right;
-            subQuery.expr = bb.register(converted.left, JoinRelType.LEFT);
-            return;
+            case SCALAR_QUERY:
+                // Convert the sub-query.  If it's non-correlated, convert it
+                // to a constant expression.
+                if (!config.isExpand()) {
+                    return;
+                }
+                call = (SqlBasicCall) subQuery.node;
+                query = call.operand(0);
+                converted = convertExists(query, RelOptUtil.SubQueryType.SCALAR,
+                        subQuery.logic, true, null);
+                assert !converted.indicator;
+                if (convertNonCorrelatedSubQuery(subQuery, bb, converted.r, false)) {
+                    return;
+                }
+                rel = convertToSingleValueSubq(query, converted.r);
+                subQuery.expr = bb.register(rel, JoinRelType.LEFT);
+                return;
+
+            case SELECT:
+                // This is used when converting multiset queries:
+                //
+                // select * from unnest(select multiset[deptno] from emps);
+                //
+                converted = convertExists(subQuery.node, RelOptUtil.SubQueryType.SCALAR,
+                        subQuery.logic, true, null);
+                assert !converted.indicator;
+                subQuery.expr = bb.register(converted.r, JoinRelType.LEFT);
+                return;
 
-        default:
-            throw Util.newInternal("unexpected kind of subquery :" + subQuery.node);
+            default:
+                throw Util.newInternal("unexpected kind of sub-query :" + subQuery.node);
         }
     }
 
-    private RexNode translateIn(SubQuery subQuery, RelNode root, final RexNode rex) {
-        switch (subQuery.logic) {
-        case TRUE:
-            return rexBuilder.makeLiteral(true);
+    private RexNode translateIn(RelOptUtil.Logic logic, RelNode root,
+                                final RexNode rex) {
+        switch (logic) {
+            case TRUE:
+                return rexBuilder.makeLiteral(true);
+
+            case TRUE_FALSE:
+            case UNKNOWN_AS_FALSE:
+                assert rex instanceof RexRangeRef;
+                final int fieldCount = rex.getType().getFieldCount();
+                RexNode rexNode = rexBuilder.makeFieldAccess(rex, fieldCount - 1);
+                rexNode = rexBuilder.makeCall(SqlStdOperatorTable.IS_TRUE, rexNode);
+
+                // Then append the IS NOT NULL(leftKeysForIn).
+                //
+                // RexRangeRef contains the following fields:
+                //   leftKeysForIn,
+                //   rightKeysForIn (the original sub-query select list),
+                //   nullIndicator
+                //
+                // The first two lists contain the same number of fields.
+                final int k = (fieldCount - 1) / 2;
+                for (int i = 0; i < k; i++) {
+                    rexNode =
+                            rexBuilder.makeCall(
+                                    SqlStdOperatorTable.AND,
+                                    rexNode,
+                                    rexBuilder.makeCall(
+                                            SqlStdOperatorTable.IS_NOT_NULL,
+                                            rexBuilder.makeFieldAccess(rex, i)));
+                }
+                return rexNode;
+
+            case TRUE_FALSE_UNKNOWN:
+            case UNKNOWN_AS_TRUE:
+                // select e.deptno,
+                //   case
+                //   when ct.c = 0 then false
+                //   when dt.i is not null then true
+                //   when e.deptno is null then null
+                //   when ct.ck < ct.c then null
+                //   else false
+                //   end
+                // from e
+                // cross join (select count(*) as c, count(deptno) as ck from v) as ct
+                // left join (select distinct deptno, true as i from v) as dt
+                //   on e.deptno = dt.deptno
+                final Join join = (Join) root;
+                final Project left = (Project) join.getLeft();
+                final RelNode leftLeft = ((Join) left.getInput()).getLeft();
+                final int leftLeftCount = leftLeft.getRowType().getFieldCount();
+                final RelDataType longType =
+                        typeFactory.createSqlType(SqlTypeName.BIGINT);
+                final RexNode cRef = rexBuilder.makeInputRef(root, leftLeftCount);
+                final RexNode ckRef = rexBuilder.makeInputRef(root, leftLeftCount + 1);
+                final RexNode iRef =
+                        rexBuilder.makeInputRef(root, root.getRowType().getFieldCount() - 1);
+
+                final RexLiteral zero =
+                        rexBuilder.makeExactLiteral(BigDecimal.ZERO, longType);
+                final RexLiteral trueLiteral = rexBuilder.makeLiteral(true);
+                final RexLiteral falseLiteral = rexBuilder.makeLiteral(false);
+                final RexNode unknownLiteral =
+                        rexBuilder.makeNullLiteral(SqlTypeName.BOOLEAN);
+
+                final ImmutableList.Builder<RexNode> args = ImmutableList.builder();
+                args.add(rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, cRef, zero),
+                        falseLiteral,
+                        rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, iRef),
+                        trueLiteral);
+                final JoinInfo joinInfo = join.analyzeCondition();
+                for (int leftKey : joinInfo.leftKeys) {
+                    final RexNode kRef = rexBuilder.makeInputRef(root, leftKey);
+                    args.add(rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, kRef),
+                            unknownLiteral);
+                }
+                args.add(rexBuilder.makeCall(SqlStdOperatorTable.LESS_THAN, ckRef, cRef),
+                        unknownLiteral,
+                        falseLiteral);
 
-        case UNKNOWN_AS_FALSE:
-            assert rex instanceof RexRangeRef;
-            final int fieldCount = rex.getType().getFieldCount();
-            RexNode rexNode = rexBuilder.makeFieldAccess(rex, fieldCount - 1);
-            rexNode = rexBuilder.makeCall(SqlStdOperatorTable.IS_TRUE, rexNode);
-
-            // Then append the IS NOT NULL(leftKeysForIn).
-            //
-            // RexRangeRef contains the following fields:
-            //   leftKeysForIn,
-            //   rightKeysForIn (the original subquery select list),
-            //   nullIndicator
-            //
-            // The first two lists contain the same number of fields.
-            final int k = (fieldCount - 1) / 2;
-            for (int i = 0; i < k; i++) {
-                rexNode = rexBuilder.makeCall(SqlStdOperatorTable.AND, rexNode, rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, rexBuilder.makeFieldAccess(rex, i)));
-            }
-            return rexNode;
-
-        case TRUE_FALSE_UNKNOWN:
-        case UNKNOWN_AS_TRUE:
-            // select e.deptno,
-            //   case
-            //   when ct.c = 0 then false
-            //   when dt.i is not null then true
-            //   when e.deptno is null then null
-            //   when ct.ck < ct.c then null
-            //   else false
-            //   end
-            // from e
-            // cross join (select count(*) as c, count(deptno) as ck from v) as ct
-            // left join (select distinct deptno, true as i from v) as dt
-            //   on e.deptno = dt.deptno
-            final Join join = (Join) root;
-            final Project left = (Project) join.getLeft();
-            final RelNode leftLeft = ((Join) left.getInput()).getLeft();
-            final int leftLeftCount = leftLeft.getRowType().getFieldCount();
-            final RelDataType nullableBooleanType = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BOOLEAN), true);
-            final RelDataType longType = typeFactory.createSqlType(SqlTypeName.BIGINT);
-            final RexNode cRef = rexBuilder.makeInputRef(root, leftLeftCount);
-            final RexNode ckRef = rexBuilder.makeInputRef(root, leftLeftCount + 1);
-            final RexNode iRef = rexBuilder.makeInputRef(root, root.getRowType().getFieldCount() - 1);
-
-            final RexLiteral zero = rexBuilder.makeExactLiteral(BigDecimal.ZERO, longType);
-            final RexLiteral trueLiteral = rexBuilder.makeLiteral(true);
-            final RexLiteral falseLiteral = rexBuilder.makeLiteral(false);
-            final RexNode unknownLiteral = rexBuilder.makeNullLiteral(SqlTypeName.BOOLEAN);
-
-            final ImmutableList.Builder<RexNode> args = ImmutableList.builder();
-            args.add(rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, cRef, zero), falseLiteral, rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, iRef), trueLiteral);
-            final JoinInfo joinInfo = join.analyzeCondition();
-            for (int leftKey : joinInfo.leftKeys) {
-                final RexNode kRef = rexBuilder.makeInputRef(root, leftKey);
-                args.add(rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, kRef), unknownLiteral);
-            }
-            args.add(rexBuilder.makeCall(SqlStdOperatorTable.LESS_THAN, ckRef, cRef), unknownLiteral, falseLiteral);
+                return rexBuilder.makeCall(SqlStdOperatorTable.CASE, args.build());
 
-            return rexBuilder.makeCall(nullableBooleanType, SqlStdOperatorTable.CASE, args.build());
+            default:
+                throw new AssertionError(logic);
+        }
+    }
 
-        default:
-            throw new AssertionError(subQuery.logic);
+    private static boolean containsNullLiteral(SqlNodeList valueList) {
+        for (SqlNode node : valueList.getList()) {
+            if (node instanceof SqlLiteral) {
+                SqlLiteral lit = (SqlLiteral) node;
+                if (lit.getValue() == null) {
+                    return true;
+                }
+            }
         }
+        return false;
     }
 
     /**
-     * Determines if a subquery is non-correlated and if so, converts it to a
+     * Determines if a sub-query is non-correlated and if so, converts it to a
      * constant.
      *
-     * @param subQuery  the call that references the subquery
-     * @param bb        blackboard used to convert the subquery
-     * @param converted RelNode tree corresponding to the subquery
-     * @param isExists  true if the subquery is part of an EXISTS expression
-     * @return if the subquery can be converted to a constant
+     * @param subQuery  the call that references the sub-query
+     * @param bb        blackboard used to convert the sub-query
+     * @param converted RelNode tree corresponding to the sub-query
+     * @param isExists  true if the sub-query is part of an EXISTS expression
+     * @return Whether the sub-query can be converted to a constant
      */
-    private boolean convertNonCorrelatedSubQuery(SubQuery subQuery, Blackboard bb, RelNode converted, boolean isExists) {
+    private boolean convertNonCorrelatedSubQuery(
+            SubQuery subQuery,
+            Blackboard bb,
+            RelNode converted,
+            boolean isExists) {
         SqlCall call = (SqlBasicCall) subQuery.node;
-        if (subqueryConverter.canConvertSubquery() && isSubQueryNonCorrelated(converted, bb)) {
-            // First check if the subquery has already been converted
-            // because it's a nested subquery.  If so, don't re-evaluate
+        if (subQueryConverter.canConvertSubQuery()
+                && isSubQueryNonCorrelated(converted, bb)) {
+            // First check if the sub-query has already been converted
+            // because it's a nested sub-query.  If so, don't re-evaluate
             // it again.
             RexNode constExpr = mapConvertedNonCorrSubqs.get(call);
             if (constExpr == null) {
-                constExpr = subqueryConverter.convertSubquery(call, this, isExists, config.isExplain());
+                constExpr =
+                        subQueryConverter.convertSubQuery(
+                                call,
+                                this,
+                                isExists,
+                                config.isExplain());
             }
             if (constExpr != null) {
                 subQuery.expr = constExpr;
@@ -1213,14 +1399,17 @@ public class SqlToRelConverter {
      * @param plan   the original RelNode tree corresponding to the statement
      * @return the converted RelNode tree
      */
-    public RelNode convertToSingleValueSubq(SqlNode query, RelNode plan) {
+    public RelNode convertToSingleValueSubq(
+            SqlNode query,
+            RelNode plan) {
         // Check whether query is guaranteed to produce a single value.
         if (query instanceof SqlSelect) {
             SqlSelect select = (SqlSelect) query;
             SqlNodeList selectList = select.getSelectList();
             SqlNodeList groupList = select.getGroup();
 
-            if ((selectList.size() == 1) && ((groupList == null) || (groupList.size() == 0))) {
+            if ((selectList.size() == 1)
+                    && ((groupList == null) || (groupList.size() == 0))) {
                 SqlNode selectExpr = selectList.get(0);
                 if (selectExpr instanceof SqlCall) {
                     SqlCall selectExprCall = (SqlCall) selectExpr;
@@ -1231,7 +1420,8 @@ public class SqlToRelConverter {
 
                 // If there is a limit with 0 or 1,
                 // it is ensured to produce a single value
-                if (select.getFetch() != null && select.getFetch() instanceof SqlNumericLiteral) {
+                if (select.getFetch() != null
+                        && select.getFetch() instanceof SqlNumericLiteral) {
                     SqlNumericLiteral limitNum = (SqlNumericLiteral) select.getFetch();
                     if (((BigDecimal) limitNum.getValue()).intValue() < 2) {
                         return plan;
@@ -1243,13 +1433,17 @@ public class SqlToRelConverter {
             // it is necessary to look into the operands to determine
             // whether SingleValueAgg is necessary
             SqlCall exprCall = (SqlCall) query;
-            if (exprCall.getOperator() instanceof SqlValuesOperator && Util.isSingleValue(exprCall)) {
+            if (exprCall.getOperator()
+                    instanceof SqlValuesOperator
+                    && Util.isSingleValue(exprCall)) {
                 return plan;
             }
         }
 
         // If not, project SingleValueAgg
-        return RelOptUtil.createSingleValueAggRel(cluster, plan);
+        return RelOptUtil.createSingleValueAggRel(
+                cluster,
+                plan);
     }
 
     /**
@@ -1260,30 +1454,52 @@ public class SqlToRelConverter {
      * @param isNotIn    is this a NOT IN operator
      * @return converted expression
      */
-    private RexNode convertInToOr(final Blackboard bb, final List<RexNode> leftKeys, SqlNodeList valuesList, boolean isNotIn) {
+    private RexNode convertInToOr(
+            final Blackboard bb,
+            final List<RexNode> leftKeys,
+            SqlNodeList valuesList,
+            boolean isNotIn) {
         final List<RexNode> comparisons = new ArrayList<>();
         for (SqlNode rightVals : valuesList) {
             RexNode rexComparison;
             if (leftKeys.size() == 1) {
-                rexComparison = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, leftKeys.get(0), ensureSqlType(leftKeys.get(0).getType(), bb.convertExpression(rightVals)));
+                rexComparison =
+                        rexBuilder.makeCall(SqlStdOperatorTable.EQUALS,
+                                leftKeys.get(0),
+                                ensureSqlType(leftKeys.get(0).getType(),
+                                        bb.convertExpression(rightVals)));
             } else {
                 assert rightVals instanceof SqlCall;
                 final SqlBasicCall call = (SqlBasicCall) rightVals;
-                assert (call.getOperator() instanceof SqlRowOperator) && call.operandCount() == leftKeys.size();
-                rexComparison = RexUtil.composeConjunction(rexBuilder, Iterables.transform(Pair.zip(leftKeys, call.getOperandList()), new Function<Pair<RexNode, SqlNode>, RexNode>() {
-                    public RexNode apply(Pair<RexNode, SqlNode> pair) {
-                        return rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, pair.left, ensureSqlType(pair.left.getType(), bb.convertExpression(pair.right)));
-                    }
-                }), false);
+                assert (call.getOperator() instanceof SqlRowOperator)
+                        && call.operandCount() == leftKeys.size();
+                rexComparison =
+                        RexUtil.composeConjunction(
+                                rexBuilder,
+                                Iterables.transform(
+                                        Pair.zip(leftKeys, call.getOperandList()),
+                                        new Function<Pair<RexNode, SqlNode>, RexNode>() {
+                                            public RexNode apply(Pair<RexNode, SqlNode> pair) {
+                                                return rexBuilder.makeCall(SqlStdOperatorTable.EQUALS,
+                                                        pair.left,
+                                                        ensureSqlType(pair.left.getType(),
+                                                                bb.convertExpression(pair.right)));
+                                            }
+                                        }),
+                                false);
             }
             comparisons.add(rexComparison);
         }
 
-        RexNode result = RexUtil.composeDisjunction(rexBuilder, comparisons, true);
+        RexNode result =
+                RexUtil.composeDisjunction(rexBuilder, comparisons, true);
         assert result != null;
 
         if (isNotIn) {
-            result = rexBuilder.makeCall(SqlStdOperatorTable.NOT, result);
+            result =
+                    rexBuilder.makeCall(
+                            SqlStdOperatorTable.NOT,
+                            result);
         }
 
         return result;
@@ -1293,7 +1509,9 @@ public class SqlToRelConverter {
      * cast if necessary. If the expression already has the right type family,
      * returns the expression unchanged. */
     private RexNode ensureSqlType(RelDataType type, RexNode node) {
-        if (type.getSqlTypeName() == node.getType().getSqlTypeName() || (type.getSqlTypeName() == SqlTypeName.VARCHAR && node.getType().getSqlTypeName() == SqlTypeName.CHAR)) {
+        if (type.getSqlTypeName() == node.getType().getSqlTypeName()
+                || (type.getSqlTypeName() == SqlTypeName.VARCHAR
+                && node.getType().getSqlTypeName() == SqlTypeName.CHAR)) {
             return node;
         }
         return rexBuilder.ensureType(type, node, true);
@@ -1307,17 +1525,17 @@ public class SqlToRelConverter {
      * predicate. A threshold of 0 forces usage of an inline table in all cases; a
      * threshold of Integer.MAX_VALUE forces usage of OR in all cases
      *
-     * @return threshold, default {@link #DEFAULT_IN_SUBQUERY_THRESHOLD}
+     * @return threshold, default {@link #DEFAULT_IN_SUB_QUERY_THRESHOLD}
      */
     @Deprecated // to be removed before 2.0
     protected int getInSubqueryThreshold() {
-        //return config.getInSubqueryThreshold();
-        /* OVERRIDE POINT */
+        //return config.getInSubQueryThreshold();
+         /* OVERRIDE POINT */
         return Integer.MAX_VALUE;
     }
 
     /**
-     * Converts an EXISTS or IN predicate into a join. For EXISTS, the subquery
+     * Converts an EXISTS or IN predicate into a join. For EXISTS, the sub-query
      * produces an indicator variable, and the result is a relational expression
      * which outer joins that indicator to the original query. After performing
      * the outer join, the condition will be TRUE if the EXISTS condition holds,
@@ -1325,23 +1543,34 @@ public class SqlToRelConverter {
      *
      * @param seek           A query, for example 'select * from emp' or
      *                       'values (1,2,3)' or '('Foo', 34)'.
-     * @param subqueryType   Whether sub-query is IN, EXISTS or scalar
+     * @param subQueryType   Whether sub-query is IN, EXISTS or scalar
      * @param logic Whether the answer needs to be in full 3-valued logic (TRUE,
      *     FALSE, UNKNOWN) will be required, or whether we can accept an
      *     approximation (say representing UNKNOWN as FALSE)
-     * @param needsOuterJoin Whether an outer join is needed
+     * @param notIn Whether the operation is NOT IN
      * @return join expression
      * @pre extraExpr == null || extraName != null
      */
-    private Pair<RelNode, Boolean> convertExists(SqlNode seek, RelOptUtil.SubqueryType subqueryType, RelOptUtil.Logic logic, boolean needsOuterJoin, RelDataType targetDataType) {
-        final SqlValidatorScope seekScope = (seek instanceof SqlSelect) ? validator.getSelectScope((SqlSelect) seek) : null;
+    private RelOptUtil.Exists convertExists(
+            SqlNode seek,
+            RelOptUtil.SubQueryType subQueryType,
+            RelOptUtil.Logic logic,
+            boolean notIn,
+            RelDataType targetDataType) {
+        final SqlValidatorScope seekScope =
+                (seek instanceof SqlSelect)
+                        ? validator.getSelectScope((SqlSelect) seek)
+                        : null;
         final Blackboard seekBb = createBlackboard(seekScope, null, false);
         RelNode seekRel = convertQueryOrInList(seekBb, seek, targetDataType);
 
-        return RelOptUtil.createExistsPlan(seekRel, subqueryType, logic, needsOuterJoin);
+        return RelOptUtil.createExistsPlan(seekRel, subQueryType, logic, notIn);
     }
 
-    private RelNode convertQueryOrInList(Blackboard bb, SqlNode seek, RelDataType targetRowType) {
+    private RelNode convertQueryOrInList(
+            Blackboard bb,
+            SqlNode seek,
+            RelDataType targetRowType) {
         // NOTE: Once we start accepting single-row queries as row constructors,
         // there will be an ambiguity here for a case like X IN ((SELECT Y FROM
         // Z)).  The SQL standard resolves the ambiguity by saying that a lone
@@ -1349,25 +1578,40 @@ public class SqlToRelConverter {
         // expression.  The semantic difference is that a table expression can
         // return multiple rows.
         if (seek instanceof SqlNodeList) {
-            return convertRowValues(bb, seek, ((SqlNodeList) seek).getList(), false, targetRowType);
+            return convertRowValues(
+                    bb,
+                    seek,
+                    ((SqlNodeList) seek).getList(),
+                    false,
+                    targetRowType);
         } else {
             return convertQueryRecursive(seek, false, null).project();
         }
     }
 
-    private RelNode convertRowValues(Blackboard bb, SqlNode rowList, Collection<SqlNode> rows, boolean allowLiteralsOnly, RelDataType targetRowType) {
+    private RelNode convertRowValues(
+            Blackboard bb,
+            SqlNode rowList,
+            Collection<SqlNode> rows,
+            boolean allowLiteralsOnly,
+            RelDataType targetRowType) {
         // NOTE jvs 30-Apr-2006: We combine all rows consisting entirely of
         // literals into a single LogicalValues; this gives the optimizer a smaller
         // input tree.  For everything else (computed expressions, row
-        // subqueries), we union each row in as a projection on top of a
+        // sub-queries), we union each row in as a projection on top of a
         // LogicalOneRow.
 
-        final ImmutableList.Builder<ImmutableList<RexLiteral>> tupleList = ImmutableList.builder();
+        final ImmutableList.Builder<ImmutableList<RexLiteral>> tupleList =
+                ImmutableList.builder();
         final RelDataType rowType;
         if (targetRowType != null) {
             rowType = targetRowType;
         } else {
-            rowType = SqlTypeUtil.promoteToRowType(typeFactory, validator.getValidatedNodeType(rowList), null);
+            rowType =
+                    SqlTypeUtil.promoteToRowType(
+                            typeFactory,
+                            validator.getValidatedNodeType(rowList),
+                            null);
         }
 
         final List<RelNode> unionInputs = new ArrayList<>();
@@ -1377,7 +1621,12 @@ public class SqlToRelConverter {
                 call = (SqlBasicCall) node;
                 ImmutableList.Builder<RexLiteral> tuple = ImmutableList.builder();
                 for (Ord<SqlNode> operand : Ord.zip(call.operands)) {
-                    RexLiteral rexLiteral = convertLiteralInValuesList(operand.e, bb, rowType, operand.i);
+                    RexLiteral rexLiteral =
+                            convertLiteralInValuesList(
+                                    operand.e,
+                                    bb,
+                                    rowType,
+                                    operand.i);
                     if ((rexLiteral == null) && allowLiteralsOnly) {
                         return null;
                     }
@@ -1393,7 +1642,12 @@ public class SqlToRelConverter {
                     continue;
                 }
             } else {
-                RexLiteral rexLiteral = convertLiteralInValuesList(node, bb, rowType, 0);
+                RexLiteral rexLiteral =
+                        convertLiteralInValuesList(
+                                node,
+                                bb,
+                                rowType,
+                                0);
                 if ((rexLiteral != null) && config.isCreateValuesRel()) {
                     tupleList.add(ImmutableList.of(rexLiteral));
                     continue;
@@ -1404,11 +1658,15 @@ public class SqlToRelConverter {
                 }
 
                 // convert "1" to "row(1)"
-                call = (SqlBasicCall) SqlStdOperatorTable.ROW.createCall(SqlParserPos.ZERO, node);
+                call =
+                        (SqlBasicCall) SqlStdOperatorTable.ROW.createCall(
+                                SqlParserPos.ZERO,
+                                node);
             }
             unionInputs.add(convertRowConstructor(bb, call));
         }
-        LogicalValues values = LogicalValues.create(cluster, rowType, tupleList.build());
+        LogicalValues values =
+                LogicalValues.create(cluster, rowType, tupleList.build());
         RelNode resultRel;
         if (unionInputs.isEmpty()) {
             resultRel = values;
@@ -1422,7 +1680,11 @@ public class SqlToRelConverter {
         return resultRel;
     }
 
-    private RexLiteral convertLiteralInValuesList(SqlNode sqlNode, Blackboard bb, RelDataType rowType, int iField) {
+    private RexLiteral convertLiteralInValuesList(
+            SqlNode sqlNode,
+            Blackboard bb,
+            RelDataType rowType,
+            int iField) {
         if (!(sqlNode instanceof SqlLiteral)) {
             return null;
         }
@@ -1435,7 +1697,10 @@ public class SqlToRelConverter {
             return null;
         }
 
-        RexNode literalExpr = exprConverter.convertLiteral(bb, (SqlLiteral) sqlNode);
+        RexNode literalExpr =
+                exprConverter.convertLiteral(
+                        bb,
+                        (SqlLiteral) sqlNode);
 
         if (!(literalExpr instanceof RexLiteral)) {
             assert literalExpr.isA(SqlKind.CAST);
@@ -1452,14 +1717,24 @@ public class SqlToRelConverter {
         Comparable value = literal.getValue();
 
         if (SqlTypeUtil.isExactNumeric(type) && SqlTypeUtil.hasScale(type)) {
-            BigDecimal roundedValue = NumberUtil.rescaleBigDecimal((BigDecimal) value, type.getScale());
-            return rexBuilder.makeExactLiteral(roundedValue, type);
+            BigDecimal roundedValue =
+                    NumberUtil.rescaleBigDecimal(
+                            (BigDecimal) value,
+                            type.getScale());
+            return rexBuilder.makeExactLiteral(
+                    roundedValue,
+                    type);
         }
 
-        if ((value instanceof NlsString) && (type.getSqlTypeName() == SqlTypeName.CHAR)) {
+        if ((value instanceof NlsString)
+                && (type.getSqlTypeName() == SqlTypeName.CHAR)) {
             // pad fixed character type
             NlsString unpadded = (NlsString) value;
-            return rexBuilder.makeCharLiteral(new NlsString(Spaces.padRight(unpadded.getValue(), type.getPrecision()), unpadded.getCharsetName(), unpadded.getCollation()));
+            return rexBuilder.makeCharLiteral(
+                    new NlsString(
+                            Spaces.padRight(unpadded.getValue(), type.getPrecision()),
+                            unpadded.getCharsetName(),
+                            unpadded.getCollation()));
         }
         return literal;
     }
@@ -1481,67 +1756,78 @@ public class SqlToRelConverter {
      * @param logic Whether the answer needs to be in full 3-valued logic (TRUE,
      *              FALSE, UNKNOWN) will be required, or whether we can accept
      *              an approximation (say representing UNKNOWN as FALSE)
-     * @param registerOnlyScalarSubqueries if set to true and the parse tree
+     * @param registerOnlyScalarSubQueries if set to true and the parse tree
      *                                     corresponds to a variation of a select
      *                                     node, only register it if it's a scalar
-     *                                     subquery
+     *                                     sub-query
      */
-    private void findSubqueries(Blackboard bb, SqlNode node, RelOptUtil.Logic logic, boolean registerOnlyScalarSubqueries) {
+    private void findSubQueries(
+            Blackboard bb,
+            SqlNode node,
+            RelOptUtil.Logic logic,
+            boolean registerOnlyScalarSubQueries) {
         final SqlKind kind = node.getKind();
         switch (kind) {
-        case EXISTS:
-        case SELECT:
-        case MULTISET_QUERY_CONSTRUCTOR:
-        case MULTISET_VALUE_CONSTRUCTOR:
-        case ARRAY_QUERY_CONSTRUCTOR:
-        case CURSOR:
-        case SCALAR_QUERY:
-            if (!registerOnlyScalarSubqueries || (kind == SqlKind.SCALAR_QUERY)) {
-                bb.registerSubquery(node, RelOptUtil.Logic.TRUE_FALSE);
-            }
-            return;
-        case IN:
-            if (((SqlCall) node).getOp

<TRUNCATED>

[05/10] kylin git commit: KYLIN-2400 code review

Posted by bi...@apache.org.
KYLIN-2400 code review


Project: http://git-wip-us.apache.org/repos/asf/kylin/repo
Commit: http://git-wip-us.apache.org/repos/asf/kylin/commit/576d2dd3
Tree: http://git-wip-us.apache.org/repos/asf/kylin/tree/576d2dd3
Diff: http://git-wip-us.apache.org/repos/asf/kylin/diff/576d2dd3

Branch: refs/heads/KYLIN-2394
Commit: 576d2dd352b11f428db1d6308e35350a2fca122e
Parents: e769bfa
Author: Li Yang <li...@apache.org>
Authored: Tue Jan 17 11:06:26 2017 +0800
Committer: Li Yang <li...@apache.org>
Committed: Tue Jan 17 11:06:26 2017 +0800

----------------------------------------------------------------------
 .../apache/kylin/common/util/Dictionary.java    | 42 +++-----------------
 .../apache/kylin/dict/AppendTrieDictionary.java | 39 +++++++-----------
 .../apache/kylin/dict/DictionaryGenerator.java  |  2 +-
 .../kylin/dict/NumberDictionaryBuilder.java     | 10 ++---
 .../dict/NumberDictionaryForestBuilder.java     |  7 +++-
 .../apache/kylin/dict/TrieDictionaryForest.java |  2 +-
 .../apache/kylin/dict/NumberDictionaryTest.java |  4 +-
 .../kylin/dict/TimeStrDictionaryTest.java       |  8 ++--
 .../kylin/dict/TrieDictionaryForestTest.java    |  2 +-
 .../kylin/measure/raw/RawMeasureType.java       |  3 ++
 .../storage/gtrecord/DictGridTableTest.java     |  3 +-
 .../mr/steps/NumberDictionaryForestTest.java    |  2 +-
 12 files changed, 43 insertions(+), 81 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
----------------------------------------------------------------------
diff --git a/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java b/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
index 9d675f9..4b5c1c4 100644
--- a/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
+++ b/core-common/src/main/java/org/apache/kylin/common/util/Dictionary.java
@@ -94,13 +94,12 @@ abstract public class Dictionary<T> implements Serializable {
     final public int getIdFromValue(T value, int roundingFlag) throws IllegalArgumentException {
         if (isNullObjectForm(value))
             return nullId();
-        else {
-            int id = getIdFromValueImpl(value, roundingFlag);
-            if(id == -1){
-                throw new IllegalArgumentException("Value : " + value + "no exists");
-            }
-            return id;
+
+        int id = getIdFromValueImpl(value, roundingFlag);
+        if (id == -1) {
+            throw new IllegalArgumentException("Value : " + value + " not exists");
         }
+        return id;
     }
 
     final public boolean containsValue(T value) throws IllegalArgumentException {
@@ -137,37 +136,6 @@ abstract public class Dictionary<T> implements Serializable {
 
     abstract protected T getValueFromIdImpl(int id);
 
-    /**
-     * Convenient form of
-     * <code>getIdFromValueBytes(value, offset, len, 0)</code>
-     */
-
-
-    /**
-     * A lower level API, return ID integer from raw value bytes. In case of not found 
-     * <p>
-     * - if roundingFlag=0, throw IllegalArgumentException; <br>
-     * - if roundingFlag<0, the closest smaller ID integer if exist; <br>
-     * - if roundingFlag>0, the closest bigger ID integer if exist. <br>
-     * <p>
-     * Bypassing the cache layer, this could be significantly slower than getIdFromValue(T value).
-     * 
-     * @throws IllegalArgumentException
-     *             if value is not found in dictionary and rounding is off;
-     *             or if rounding cannot find a smaller or bigger ID
-     */
-
-    /**
-     * A lower level API, get byte values from ID, return the number of bytes
-     * written. Bypassing the cache layer, this could be significantly slower
-     * than getIdFromValue(T value).
-     *
-     * @return size of value bytes, 0 if empty string, -1 if null
-     *
-     * @throws IllegalArgumentException
-     *             if ID is not found in dictionary
-     */
-
     abstract public void dump(PrintStream out);
 
     public int nullId() {

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java b/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
index 3aef967..faffcc0 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/AppendTrieDictionary.java
@@ -91,14 +91,11 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
 
     volatile private TreeMap<DictSliceKey, DictSlice> dictSliceMap;
 
-
     // Constructor both for build and deserialize
     public AppendTrieDictionary() {
         enableCache();
     }
 
-
-
     public void initParams(String baseDir, int baseId, int maxId, int maxValueLength, int nValues, BytesConverter bytesConverter) throws IOException {
         this.baseDir = baseDir;
         this.baseId = baseId;
@@ -111,8 +108,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
     public void initDictSliceMap(CachedTreeMap dictMap) throws IOException {
         int maxVersions = KylinConfig.getInstanceFromEnv().getAppendDictMaxVersions();
         long versionTTL = KylinConfig.getInstanceFromEnv().getAppendDictVersionTTL();
-        CachedTreeMap newDictSliceMap = CachedTreeMap.CachedTreeMapBuilder.newBuilder().maxSize(1).baseDir(baseDir)
-            .immutable(true).maxVersions(maxVersions).versionTTL(versionTTL).keyClazz(DictSliceKey.class).valueClazz(DictSlice.class).build();
+        CachedTreeMap newDictSliceMap = CachedTreeMap.CachedTreeMapBuilder.newBuilder().maxSize(1).baseDir(baseDir).immutable(true).maxVersions(maxVersions).versionTTL(versionTTL).keyClazz(DictSliceKey.class).valueClazz(DictSlice.class).build();
         newDictSliceMap.loadEntry(dictMap);
         this.dictSliceMap = newDictSliceMap;
     }
@@ -210,7 +206,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
                 this.sizeChildOffset = headIn.read();
                 this.sizeOfId = headIn.read();
 
-                this.childOffsetMask = ~(((long)(BIT_IS_LAST_CHILD | BIT_IS_END_OF_VALUE)) << ((sizeChildOffset - 1) * 8));
+                this.childOffsetMask = ~(((long) (BIT_IS_LAST_CHILD | BIT_IS_END_OF_VALUE)) << ((sizeChildOffset - 1) * 8));
                 this.firstByteOffset = sizeChildOffset + 1; // the offset from begin of node to its first value byte
             } catch (Exception e) {
                 if (e instanceof RuntimeException)
@@ -229,7 +225,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
                 if (checkFlag(nodeOffset, BIT_IS_END_OF_VALUE)) {
                     break;
                 }
-                nodeOffset = headSize + (int)(BytesUtil.readLong(trieBytes, nodeOffset, sizeChildOffset) & childOffsetMask);
+                nodeOffset = headSize + (int) (BytesUtil.readLong(trieBytes, nodeOffset, sizeChildOffset) & childOffsetMask);
                 if (nodeOffset == headSize) {
                     break;
                 }
@@ -271,7 +267,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
                 }
 
                 // find a child to continue
-                int c = headSize + (int)(BytesUtil.readLong(trieBytes, n, sizeChildOffset) & childOffsetMask);
+                int c = headSize + (int) (BytesUtil.readLong(trieBytes, n, sizeChildOffset) & childOffsetMask);
                 if (c == headSize) // has no children
                     return -1;
                 byte inpByte = inp[o];
@@ -310,7 +306,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
             DictNode root = null;
             while (true) {
                 int p = n + firstByteOffset;
-                int childOffset = (int)(BytesUtil.readLong(trieBytes, n, sizeChildOffset) & childOffsetMask);
+                int childOffset = (int) (BytesUtil.readLong(trieBytes, n, sizeChildOffset) & childOffsetMask);
                 int parLen = BytesUtil.readUnsigned(trieBytes, p - 1, 1);
                 boolean isEndOfValue = checkFlag(n, BIT_IS_END_OF_VALUE);
 
@@ -357,13 +353,13 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
                     lastChild = false;
                 }
                 int p = offset + firstByteOffset;
-                int childOffset = (int)(BytesUtil.readLong(trieBytes, offset, sizeChildOffset) & childOffsetMask);
+                int childOffset = (int) (BytesUtil.readLong(trieBytes, offset, sizeChildOffset) & childOffsetMask);
                 int parLen = BytesUtil.readUnsigned(trieBytes, p - 1, 1);
                 boolean isEndOfValue = checkFlag(offset, BIT_IS_END_OF_VALUE);
 
                 // Copy value overflow, the data is corrupted
                 if (trieBytes.length < p + parLen) {
-                   return false;
+                    return false;
                 }
 
                 // Check id is fine
@@ -401,7 +397,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
                 throw new IllegalArgumentException("Wrong file type (magic does not match)");
 
             DataInputStream headIn = new DataInputStream(//
-                new ByteArrayInputStream(headPartial, HEAD_SIZE_I, headPartial.length - HEAD_SIZE_I));
+                    new ByteArrayInputStream(headPartial, HEAD_SIZE_I, headPartial.length - HEAD_SIZE_I));
             int headSize = headIn.readShort();
             int bodyLen = headIn.readInt();
             headIn.close();
@@ -665,8 +661,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
 
             // nValueBytes
             if (n.part.length > 255)
-                throw new RuntimeException("Value length is " + n.part.length
-                    + " and larger than 255: " + Bytes.toStringBinary(n.part));
+                throw new RuntimeException("Value length is " + n.part.length + " and larger than 255: " + Bytes.toStringBinary(n.part));
             BytesUtil.writeUnsigned(n.part.length, trieBytes, o, 1);
             o++;
 
@@ -785,7 +780,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
                 int t = s.mbpn_sizeValueTotal + s.mbpn_nNodes * (s.mbpn_sizeNoValueBytes + s.mbpn_sizeChildOffset - 1);
                 // *4 because 2 MSB of offset is used for isEndOfValue & isEndChild flag
                 // expand t to long before *4, avoiding exceed Integer.MAX_VALUE
-                if (BytesUtil.sizeForValue((long)t * 4) <= s.mbpn_sizeChildOffset - 1) {
+                if (BytesUtil.sizeForValue((long) t * 4) <= s.mbpn_sizeChildOffset - 1) {
                     s.mbpn_sizeChildOffset--;
                     s.mbpn_footprint = t;
                 } else
@@ -886,8 +881,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
                 builder = new Builder<>(resourcePath, null, dictDir, 0, 0, 0, new StringBytesConverter(), null);
             } else {
                 logger.info("GlobalDict {} exist, append value", resourcePath);
-                builder = new Builder<>(resourcePath, dictToUse, dictToUse.baseDir, dictToUse.maxId, dictToUse.maxValueLength,
-                    dictToUse.nValues, dictToUse.bytesConvert, dictToUse.writeDictMap());
+                builder = new Builder<>(resourcePath, dictToUse, dictToUse.baseDir, dictToUse.maxId, dictToUse.maxValueLength, dictToUse.nValues, dictToUse.bytesConvert, dictToUse.writeDictMap());
             }
 
             return builder;
@@ -926,8 +920,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
             int maxVersions = KylinConfig.getInstanceFromEnv().getAppendDictMaxVersions();
             long versionTTL = KylinConfig.getInstanceFromEnv().getAppendDictVersionTTL();
             // create a new cached map with baseDir
-            mutableDictSliceMap = CachedTreeMap.CachedTreeMapBuilder.newBuilder().maxSize(1).baseDir(baseDir)
-                .maxVersions(maxVersions).versionTTL(versionTTL).keyClazz(DictSliceKey.class).valueClazz(DictNode.class).immutable(false).build();
+            mutableDictSliceMap = CachedTreeMap.CachedTreeMapBuilder.newBuilder().maxSize(1).baseDir(baseDir).maxVersions(maxVersions).versionTTL(versionTTL).keyClazz(DictSliceKey.class).valueClazz(DictNode.class).immutable(false).build();
             if (dictMapBytes != null) {
                 ((Writable) mutableDictSliceMap).readFields(new DataInputStream(new ByteArrayInputStream(dictMapBytes)));
             }
@@ -1105,7 +1098,7 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
 
         public synchronized AppendTrieDictionary<T> build(int baseId) throws IOException {
             boolean keepAppend = releaseInstance(resourcePath);
-            CachedTreeMap dictSliceMap = (CachedTreeMap)mutableDictSliceMap;
+            CachedTreeMap dictSliceMap = (CachedTreeMap) mutableDictSliceMap;
             dict.initParams(baseDir, baseId, maxId, maxValueLength, nValues, bytesConverter);
             dict.flushIndex(dictSliceMap, keepAppend);
             dict.initDictSliceMap(dictSliceMap);
@@ -1155,7 +1148,6 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
         return maxValueLength;
     }
 
-
     public void flushIndex(CachedTreeMap dictSliceMap, boolean keepAppend) throws IOException {
         try (FSDataOutputStream indexOut = dictSliceMap.openIndexOutput()) {
             indexOut.writeInt(baseId);
@@ -1220,14 +1212,12 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
             initParams(baseDir, baseId, maxId, maxValueLength, nValues, converter);
 
             // Create instance for deserialize data, and update to map in dict
-            CachedTreeMap dictMap = CachedTreeMap.CachedTreeMapBuilder.newBuilder()
-                .baseDir(baseDir).immutable(true).keyClazz(DictSliceKey.class).valueClazz(DictSlice.class).build();
+            CachedTreeMap dictMap = CachedTreeMap.CachedTreeMapBuilder.newBuilder().baseDir(baseDir).immutable(true).keyClazz(DictSliceKey.class).valueClazz(DictSlice.class).build();
             dictMap.readFields(input);
             initDictSliceMap(dictMap);
         }
     }
 
-
     @Override
     public void dump(PrintStream out) {
         out.println("Total " + nValues + " values, " + (dictSliceMap == null ? 0 : dictSliceMap.size()) + " slice");
@@ -1261,4 +1251,3 @@ public class AppendTrieDictionary<T> extends CacheDictionary<T> {
     }
 
 }
-

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java b/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
index c23e7b5..61a0664 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/DictionaryGenerator.java
@@ -227,7 +227,7 @@ public class DictionaryGenerator {
         @Override
         public void init(DictionaryInfo info, int baseId) throws IOException {
             this.baseId = baseId;
-            this.builder = new NumberDictionaryBuilder(new NumberDictionaryForestBuilder.Number2BytesConverter());
+            this.builder = new NumberDictionaryBuilder();
         }
         
         @Override

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
index b9e94414..288e38f 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryBuilder.java
@@ -25,17 +25,17 @@ package org.apache.kylin.dict;
  * @author yangli9
  */
 @Deprecated
-public class NumberDictionaryBuilder<T> extends TrieDictionaryBuilder<T> {
+public class NumberDictionaryBuilder extends TrieDictionaryBuilder<String> {
 
 
-    public NumberDictionaryBuilder(BytesConverter<T> bytesConverter) {
-        super(bytesConverter);
+    public NumberDictionaryBuilder() {
+        super(new NumberDictionaryForestBuilder.Number2BytesConverter());
     }
 
 
-    public NumberDictionary<T> build(int baseId) {
+    public NumberDictionary build(int baseId) {
         byte[] trieBytes = buildTrieBytes(baseId);
-        NumberDictionary2<T> r = new NumberDictionary2<T>(trieBytes);
+        NumberDictionary2 r = new NumberDictionary2(trieBytes);
         return r;
     }
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryForestBuilder.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryForestBuilder.java b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryForestBuilder.java
index 7c750f4..b072599 100644
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryForestBuilder.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/NumberDictionaryForestBuilder.java
@@ -18,6 +18,8 @@
 
 package org.apache.kylin.dict;
 
+import java.io.Serializable;
+
 import org.apache.kylin.common.util.Bytes;
 import org.apache.kylin.dict.NumberDictionary.NumberBytesCodec;
 
@@ -26,8 +28,9 @@ import org.apache.kylin.dict.NumberDictionary.NumberBytesCodec;
  */
 public class NumberDictionaryForestBuilder extends TrieDictionaryForestBuilder<String> {
 
-    public static class Number2BytesConverter implements BytesConverter<String>, java.io.Serializable {
-
+    public static class Number2BytesConverter implements BytesConverter<String>, Serializable {
+        private static final long serialVersionUID = 1L;
+        
         static final int MAX_DIGITS_BEFORE_DECIMAL_POINT = NumberDictionary.MAX_DIGITS_BEFORE_DECIMAL_POINT;
         static final transient ThreadLocal<NumberBytesCodec> LOCAL = new ThreadLocal<NumberBytesCodec>();
 

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
index d1b5a99..04292d2 100755
--- a/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
+++ b/core-dictionary/src/main/java/org/apache/kylin/dict/TrieDictionaryForest.java
@@ -129,7 +129,7 @@ public class TrieDictionaryForest<T> extends CacheDictionary<T> {
         }
         TrieDictionary<T> tree = trees.get(index);
         int id = tree.getIdFromValueBytesWithoutCache(value, offset, len, roundingFlag);
-        if(id == -1)
+        if (id == -1)
             throw new IllegalArgumentException("Value '" + Bytes.toString(value, offset, len) + "' (" + Bytes.toStringBinary(value, offset, len) + ") not exists!");
         id = id + accuOffset.get(index);
         id += baseId;

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
index 38f2648..1c04745 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/NumberDictionaryTest.java
@@ -59,7 +59,7 @@ public class NumberDictionaryTest extends LocalFileMetadataTestCase {
 
     @Test
     public void testMinMax() {
-        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<String>(new NumberDictionaryForestBuilder.Number2BytesConverter());
+        NumberDictionaryBuilder builder = new NumberDictionaryBuilder();
         builder.addValue("" + Long.MAX_VALUE);
         builder.addValue("" + Long.MIN_VALUE);
         NumberDictionary<String> dict = builder.build(0);
@@ -123,7 +123,7 @@ public class NumberDictionaryTest extends LocalFileMetadataTestCase {
         int n = 100;
 
         Set<BigDecimal> set = Sets.newHashSet();
-        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<String>(new NumberDictionaryForestBuilder.Number2BytesConverter());
+        NumberDictionaryBuilder builder = new NumberDictionaryBuilder();
         for (int i = 0; i < n; i++) {
             String num = randNumber();
             if (set.add(new BigDecimal(num))) {

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
index f981942..e852d26 100644
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/TimeStrDictionaryTest.java
@@ -18,13 +18,13 @@
 
 package org.apache.kylin.dict;
 
+import static org.junit.Assert.fail;
+
 import org.apache.kylin.common.util.DateFormat;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-import static org.junit.Assert.fail;
-
 /**
  */
 public class TimeStrDictionaryTest {
@@ -64,10 +64,10 @@ public class TimeStrDictionaryTest {
 
     @Test
     public void testIllegal() {
-        try{
+        try {
             dict.getIdFromValue("2038-01-19 03:14:07");
             fail("should throw exception");
-        }catch (IllegalArgumentException e){
+        } catch (IllegalArgumentException e) {
             //correct
         }
     }

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
----------------------------------------------------------------------
diff --git a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
index c7fb9c4..dd1f951 100755
--- a/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
+++ b/core-dictionary/src/test/java/org/apache/kylin/dict/TrieDictionaryForestTest.java
@@ -641,7 +641,7 @@ public class TrieDictionaryForestTest {
         System.out.println("max memory:" + Runtime.getRuntime().maxMemory());
         System.gc();
         Thread.currentThread().sleep(1000);
-        NumberDictionaryBuilder<String> b = new NumberDictionaryBuilder<>(new NumberDictionaryForestBuilder.Number2BytesConverter());
+        NumberDictionaryBuilder b = new NumberDictionaryBuilder();
         int k = 0;
         while (true) {
             b.addValue(k + "");

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
----------------------------------------------------------------------
diff --git a/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java b/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
index 3b6e659..31f35e9 100644
--- a/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
+++ b/core-metadata/src/main/java/org/apache/kylin/measure/raw/RawMeasureType.java
@@ -46,6 +46,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class RawMeasureType extends MeasureType<List<ByteArray>> {
+    private static final long serialVersionUID = 1L;
 
     private static final Logger logger = LoggerFactory.getLogger(RawMeasureType.class);
 
@@ -103,6 +104,8 @@ public class RawMeasureType extends MeasureType<List<ByteArray>> {
     @Override
     public MeasureIngester<List<ByteArray>> newIngester() {
         return new MeasureIngester<List<ByteArray>>() {
+            private static final long serialVersionUID = 1L;
+
             //encode measure value to dictionary
             @Override
             public List<ByteArray> valueOf(String[] values, MeasureDesc measureDesc, Map<TblColRef, Dictionary<String>> dictionaryMap) {

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
----------------------------------------------------------------------
diff --git a/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java b/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
index ae186e2..7500b00 100644
--- a/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
+++ b/core-storage/src/test/java/org/apache/kylin/storage/gtrecord/DictGridTableTest.java
@@ -35,7 +35,6 @@ import org.apache.kylin.common.util.LocalFileMetadataTestCase;
 import org.apache.kylin.common.util.Pair;
 import org.apache.kylin.cube.gridtable.CubeCodeSystem;
 import org.apache.kylin.dict.NumberDictionaryBuilder;
-import org.apache.kylin.dict.NumberDictionaryForestBuilder;
 import org.apache.kylin.dict.StringBytesConverter;
 import org.apache.kylin.dict.TrieDictionaryBuilder;
 import org.apache.kylin.dimension.DictionaryDimEnc;
@@ -602,7 +601,7 @@ public class DictGridTableTest extends LocalFileMetadataTestCase {
 
     @SuppressWarnings("rawtypes")
     private static Dictionary newDictionaryOfInteger() {
-        NumberDictionaryBuilder<String> builder = new NumberDictionaryBuilder<>(new NumberDictionaryForestBuilder.Number2BytesConverter());
+        NumberDictionaryBuilder builder = new NumberDictionaryBuilder();
         builder.addValue("10");
         builder.addValue("20");
         builder.addValue("30");

http://git-wip-us.apache.org/repos/asf/kylin/blob/576d2dd3/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
----------------------------------------------------------------------
diff --git a/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java b/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
index 72793f5..1908992 100644
--- a/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
+++ b/engine-mr/src/test/java/org/apache/kylin/engine/mr/steps/NumberDictionaryForestTest.java
@@ -120,7 +120,7 @@ public class NumberDictionaryForestTest {
         TrieDictionaryForest<String> dict = b.build();
         dict.dump(System.out);
 
-        NumberDictionaryBuilder<String> b2 = new NumberDictionaryBuilder<>(new NumberDictionaryForestBuilder.Number2BytesConverter());
+        NumberDictionaryBuilder b2 = new NumberDictionaryBuilder();
         for (String str : testData)
             b2.addValue(str);
         NumberDictionary<String> dict2 = b2.build(0);