adelapena commented on code in PR #2409:
URL: https://github.com/apache/cassandra/pull/2409#discussion_r1228119977


##########
src/java/org/apache/cassandra/index/sai/disk/v1/bbtree/NumericIndexWriter.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * 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.cassandra.index.sai.disk.v1.bbtree;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.MoreObjects;
+
+import org.apache.cassandra.index.sai.IndexContext;
+import org.apache.cassandra.index.sai.disk.format.IndexComponent;
+import org.apache.cassandra.index.sai.disk.format.IndexDescriptor;
+import org.apache.cassandra.index.sai.disk.v1.segment.SegmentMetadata;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.packed.PackedInts;
+import org.apache.lucene.util.packed.PackedLongValues;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+
+/**
+ * Specialized writer for 1-dim point values, that builds them into a BKD tree 
with auxiliary posting lists on eligible
+ * tree levels.
+ *
+ * Given sorted input {@link org.apache.lucene.codecs.MutablePointValues}, 
1-dim case allows to optimise flush process, because we don't need to
+ * buffer all point values to sort them.
+ */

Review Comment:
   ```suggestion
   /**
    * Specialized writer for 1-dim point values, that builds them into a {@link 
BlockBalancedTreeWriter} with auxiliary
    * posting lists on eligible tree levels.
    * <p>
    * Given sorted input {@link org.apache.lucene.codecs.MutablePointValues}, 
1-dim case allows to optimise flush process,
    * because we don't need to buffer all point values to sort them.
    */
   ```



##########
src/java/org/apache/cassandra/index/sai/disk/v1/bbtree/NumericIndexWriter.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * 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.cassandra.index.sai.disk.v1.bbtree;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.MoreObjects;
+
+import org.apache.cassandra.index.sai.IndexContext;
+import org.apache.cassandra.index.sai.disk.format.IndexComponent;
+import org.apache.cassandra.index.sai.disk.format.IndexDescriptor;
+import org.apache.cassandra.index.sai.disk.v1.segment.SegmentMetadata;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.packed.PackedInts;
+import org.apache.lucene.util.packed.PackedLongValues;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+
+/**
+ * Specialized writer for 1-dim point values, that builds them into a BKD tree 
with auxiliary posting lists on eligible
+ * tree levels.
+ *
+ * Given sorted input {@link org.apache.lucene.codecs.MutablePointValues}, 
1-dim case allows to optimise flush process, because we don't need to
+ * buffer all point values to sort them.
+ */
+public class NumericIndexWriter
+{
+    public static final int MAX_POINTS_IN_LEAF_NODE = 
BlockBalancedTreeWriter.DEFAULT_MAX_POINTS_IN_LEAF_NODE;
+
+    private final BlockBalancedTreeWriter writer;
+    private final IndexDescriptor indexDescriptor;
+    private final IndexContext indexContext;
+    private final int bytesPerValue;
+
+    /**
+     * @param maxSegmentRowId maximum possible segment row ID, used to create 
`maxDoc` for kd-tree
+     */
+    public NumericIndexWriter(IndexDescriptor indexDescriptor,
+                              IndexContext indexContext,
+                              int bytesPerValue,
+                              long maxSegmentRowId)
+    {
+        this(indexDescriptor, indexContext, MAX_POINTS_IN_LEAF_NODE, 
bytesPerValue, maxSegmentRowId);
+    }
+
+    @VisibleForTesting
+    public NumericIndexWriter(IndexDescriptor indexDescriptor,
+                              IndexContext indexContext,
+                              int maxPointsInLeafNode,
+                              int bytesPerValue,
+                              long maxSegmentRowId)
+    {
+        checkArgument(maxSegmentRowId >= 0, "[%s] maxRowId must be 
non-negative value, but got %s", indexContext.getIndexName(), maxSegmentRowId);
+
+        this.indexDescriptor = indexDescriptor;
+        this.indexContext = indexContext;
+        this.bytesPerValue = bytesPerValue;
+        this.writer = new BlockBalancedTreeWriter(maxSegmentRowId + 1, 
bytesPerValue, maxPointsInLeafNode);
+    }
+
+    @Override
+    public String toString()
+    {
+        return MoreObjects.toStringHelper(this)
+                          .add("bytesPerDim", bytesPerValue)
+                          .add("bufferedPoints", writer.getPointCount())
+                          .toString();
+    }
+
+    public static class LeafCallback implements 
BlockBalancedTreeWriter.OneDimensionBKDWriterCallback
+    {
+        final List<PackedLongValues> postings = new ArrayList<>();
+
+        public int numLeaves()
+        {
+            return postings.size();
+        }
+
+        @Override
+        public void writeLeafDocs(BlockBalancedTreeWriter.RowIDAndIndex[] 
sortedByRowID, int offset, int count)
+        {
+            PackedLongValues.Builder builder = 
PackedLongValues.monotonicBuilder(PackedInts.COMPACT);
+
+            for (int i = offset; i < count; ++i)
+            {
+                builder.add(sortedByRowID[i].rowID);
+            }
+            postings.add(builder.build());
+        }
+    }
+
+    /**
+     * Writes a k-d tree and posting lists from a {@link 
org.apache.lucene.codecs.MutablePointValues}.
+     *
+     * @param values points to write
+     *
+     * @return metadata describing the location and size of this kd-tree in 
the overall SSTable kd-tree component file
+     */
+    public SegmentMetadata.ComponentMetadataMap 
writeAll(IntersectingPointValues values) throws IOException

Review Comment:
   This method has multiple vars using the `bkd` prefix. Maybe we could just 
refer to the block balanced tree in the context of this class as just "the 
tree", and name those vars `treePosition`, `treeOutput`, `treeOffset`, 
`treeLength`, etc.



##########
src/java/org/apache/cassandra/index/sai/disk/v1/bbtree/BlockBalancedTreeWriter.java:
##########
@@ -0,0 +1,769 @@
+/*
+ * 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.cassandra.index.sai.disk.v1.bbtree;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.IntFunction;
+
+import com.google.common.base.MoreObjects;
+
+import org.apache.cassandra.index.sai.disk.io.RAMIndexOutput;
+import org.apache.cassandra.index.sai.disk.v1.SAICodecUtils;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.store.GrowableByteArrayDataOutput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.FutureArrays;
+import org.apache.lucene.util.IntroSorter;
+import org.apache.lucene.util.Sorter;
+import org.apache.lucene.util.bkd.MutablePointsReaderUtils;
+
+/**
+ * This is a specialisation of the lucene BKDWriter that only writes a single 
dimension
+ * balanced tree.
+ * <p>
+ * Recursively builds a block balanced tree to assign all incoming points to 
smaller
+ * and smaller rectangles (cells) until the number of points in a given
+ * rectangle is &lt;= <code>maxPointsInLeafNode</code>.  The tree is
+ * fully balanced, which means the leaf nodes will have between 50% and 100% of
+ * the requested <code>maxPointsInLeafNode</code>.  Values that fall exactly
+ * on a cell boundary may be in either cell.
+ *
+ * <p>
+ * See <a 
href="https://www.cs.duke.edu/~pankaj/publications/papers/bkd-sstd.pdf";>this 
paper</a> for details.
+ *
+ * <p>
+ * <b>NOTE</b>: This can write at most Integer.MAX_VALUE * 
<code>maxPointsInLeafNode</code> total points.
+ */
+public class BlockBalancedTreeWriter
+{
+    // Enable to check that values are added to the tree in correct order and 
within bounds
+    private static final boolean DEBUG = false;
+
+    // Default maximum number of point in each leaf block
+    public static final int DEFAULT_MAX_POINTS_IN_LEAF_NODE = 1024;
+
+    private final int bytesPerValue;
+    private final BytesRef scratchBytesRef1 = new BytesRef();
+    private final int maxPointsInLeafNode;
+    private final byte[] minPackedValue;
+    private final byte[] maxPackedValue;
+    private long pointCount;
+    private final long maxDoc;
+
+    public BlockBalancedTreeWriter(long maxDoc, int bytesPerValue, int 
maxPointsInLeafNode)
+    {
+        if (maxPointsInLeafNode <= 0)
+            throw new IllegalArgumentException("maxPointsInLeafNode must be > 
0; got " + maxPointsInLeafNode);
+        if (maxPointsInLeafNode > ArrayUtil.MAX_ARRAY_LENGTH)
+            throw new IllegalArgumentException("maxPointsInLeafNode must be <= 
ArrayUtil.MAX_ARRAY_LENGTH (= " +
+                                               ArrayUtil.MAX_ARRAY_LENGTH + 
"); got " + maxPointsInLeafNode);
+
+        this.maxPointsInLeafNode = maxPointsInLeafNode;
+        this.bytesPerValue = bytesPerValue;
+        this.maxDoc = maxDoc;
+
+        minPackedValue = new byte[bytesPerValue];
+        maxPackedValue = new byte[bytesPerValue];
+    }
+
+    public long getPointCount()
+    {
+        return pointCount;
+    }
+
+    public int getBytesPerValue()
+    {
+        return bytesPerValue;
+    }
+
+    public int getMaxPointsInLeafNode()
+    {
+        return maxPointsInLeafNode;
+    }
+
+    /**
+     * Write the point values from a {@link IntersectingPointValues}. The 
points can be reordered before writing
+     * to disk and does not use transient disk for reordering.
+     */
+    public long writeField(IndexOutput out, IntersectingPointValues reader,
+                           final OneDimensionBKDWriterCallback callback) 
throws IOException
+    {
+        SAICodecUtils.writeHeader(out);
+
+        // We are only ever dealing with one dimension, so we can sort the 
points in ascending order
+        // and write out the values
+        if (reader.needsSorting())
+            MutablePointsReaderUtils.sort(Math.toIntExact(maxDoc), 
bytesPerValue, reader, 0, Math.toIntExact(reader.size()));
+
+        OneDimensionBKDWriter oneDimWriter = new OneDimensionBKDWriter(out, 
callback);
+
+        reader.intersect((docID, packedValue) -> oneDimWriter.add(packedValue, 
docID));
+
+        long filePointer = oneDimWriter.finish();
+
+        SAICodecUtils.writeFooter(out);
+        return filePointer;
+    }
+
+    interface OneDimensionBKDWriterCallback

Review Comment:
   Perhaps we might call this inner class just `Callback`?



##########
src/java/org/apache/cassandra/index/sai/disk/v1/bbtree/NumericIndexWriter.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * 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.cassandra.index.sai.disk.v1.bbtree;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.MoreObjects;
+
+import org.apache.cassandra.index.sai.IndexContext;
+import org.apache.cassandra.index.sai.disk.format.IndexComponent;
+import org.apache.cassandra.index.sai.disk.format.IndexDescriptor;
+import org.apache.cassandra.index.sai.disk.v1.segment.SegmentMetadata;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.packed.PackedInts;
+import org.apache.lucene.util.packed.PackedLongValues;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+
+/**
+ * Specialized writer for 1-dim point values, that builds them into a BKD tree 
with auxiliary posting lists on eligible
+ * tree levels.
+ *
+ * Given sorted input {@link org.apache.lucene.codecs.MutablePointValues}, 
1-dim case allows to optimise flush process, because we don't need to
+ * buffer all point values to sort them.
+ */
+public class NumericIndexWriter
+{
+    public static final int MAX_POINTS_IN_LEAF_NODE = 
BlockBalancedTreeWriter.DEFAULT_MAX_POINTS_IN_LEAF_NODE;
+
+    private final BlockBalancedTreeWriter writer;

Review Comment:
   If `BlockBalancedTree*` is the type of tree that we use for indexing numbers 
in `NumericIndexWriter`, would it make any sense to simply call the tree 
classes `NumericTree*`? Meaning that it's the tree that we use for numbers, 
independently of what kind of tree it is. I guess the advantage would be having 
a shorter name that is possibly clearer in most of the contexts where it's used.



##########
src/java/org/apache/cassandra/index/sai/metrics/QueryEventListener.java:
##########
@@ -24,6 +24,37 @@
  */
 public interface QueryEventListener
 {
+    /**
+     * Collector for kd-tree index file related metrics.
+     */
+    interface BKDIndexEventListener

Review Comment:
   Maybe we could rename this class to `BlockBalancedTreeEventListener`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to