You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by GitBox <gi...@apache.org> on 2020/07/30 07:38:05 UTC
[GitHub] [druid] clintropolis opened a new pull request #10224: Segment backed broadcast join IndexedTable
clintropolis opened a new pull request #10224:
URL: https://github.com/apache/druid/pull/10224
### Description
Related to #9953, this PR adds a simple naive implementation of an `IndexedTable` backed by Druid segments ingested with some extra information to identify which columns are 'join keys' at ingestion time, through the use of a custom segmentizer factory, via the changes done in #9957:
```
"indexSpec": {
"segmentLoader": {
"type": "broadcastJoinableMMapSegmentFactory",
"keyColumns": ["col1", "col2", "col3"]
}
}
```
This is probably longer term done better as being part of `ColumnCapabilities`, maybe a `isJoinKey` method, but since there might be other optimizations/customizations to the segment we are writing out to use for joins, I wanted to defer this change to future work to determine if there is a better segment format for this use case.
The implementation is based on and similar to `RowBasedIndexedTable`, but is fed with a `QueryableIndexSegment` which is scanned and the key columns are read to create the value indexes of the key columns, which are stored in heap memory in a list of hashmaps. The intention is that these will only be created for datasources that are configured to have a 'broadcast' load rule, which will propagate the entire dataset across the cluster, allowing the table to be used for more efficient joins.
The `SegmentManager` has been modified to extend `DataSourceState` to also contain a map of `SegmentId` to another newly added class in this PR, `ReferenceCountingIndexedTable` (related #9982), which ties the lifecycle of these tables to the segment that is backing them.
A new `BroadcastTableJoinableFactory` has been added which is injected with the `SegmentManager` to allow fetching the indexed tables from these broadcast segments to construct into a `Joinable`, binding to `GlobalTableDatasource` introduced in #10020. I have also reworked `JoinableFactory` a bit to allow binding multiple implementations to the same `DataSource` class, and so now is handled with 2 bindings, a `MapBinder<Class<? extends JoinableFactory>, Class<? extends DataSource>>` and a `Multibinder<JoinableFactory>` to provide `MapJoinableFactory` so it can build a `SetMultimap<Class<? extends DataSource>, JoinableFactory>`, which it will now try each factory when building a `Joinable`, returning the first that produces results.
Unit tests and an integration test have been added to test this functionality, and the integration test also should cover much of the broadcast changes done in service of #9953.
This PR adds no new documentation yet, since the functionality should still be considered experimental, but I'll consider how to best document it before the next release and do it in a future follow-up PR.
<hr>
This PR has:
- [ ] been self-reviewed.
- [ ] using the [concurrency checklist](https://github.com/apache/druid/blob/master/dev/code-review/concurrency.md) (Remove this item if the PR doesn't have any relation to concurrency.)
- [ ] added documentation for new or modified features or behaviors.
- [ ] added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
- [ ] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
- [x] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
- [x] added integration tests.
- [x] been tested in a test Druid cluster.
<hr>
##### Key changed/added classes in this PR
* `BroadcastSegmentIndexedTable`
* `ReferenceCountingIndexedTable`
* `BroadcastTableJoinableFactory`
* `BroadcastJoinableMMappedQueryableSegmentizerFactory`
* `SegmentManager`
* `MapJoinableFactory`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r466709051
##########
File path: processing/src/main/java/org/apache/druid/segment/join/table/RowBasedIndexedTable.java
##########
@@ -69,10 +68,6 @@ public RowBasedIndexedTable(
this.keyColumns = keyColumns;
this.version = version;
- if (new HashSet<>(keyColumns).size() != keyColumns.size()) {
Review comment:
Ah, no, #9287 refactored the signature from using a `List<String>` to a `Set<String>`, which I think makes this check pointless.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] lgtm-com[bot] commented on pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
lgtm-com[bot] commented on pull request #10224:
URL: https://github.com/apache/druid/pull/10224#issuecomment-668626141
This pull request **introduces 1 alert** when merging 188c760c11e1e5952d70c87f77e06e00b4cf9e4e into 34a41137522fca463c6af1df5edb2f41297491f5 - [view on LGTM.com](https://lgtm.com/projects/g/apache/druid/rev/pr-fe6df404f32fccc5a08093106ba3c28630461fb7)
**new alerts:**
* 1 for Self assignment
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r471757793
##########
File path: processing/src/main/java/org/apache/druid/segment/join/table/BroadcastSegmentIndexedTable.java
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.druid.segment.join.table;
+
+import com.google.common.base.Preconditions;
+import it.unimi.dsi.fastutil.ints.IntArrayList;
+import it.unimi.dsi.fastutil.ints.IntList;
+import org.apache.druid.java.util.common.IAE;
+import org.apache.druid.java.util.common.granularity.Granularities;
+import org.apache.druid.java.util.common.guava.Sequence;
+import org.apache.druid.java.util.common.guava.Sequences;
+import org.apache.druid.java.util.common.io.Closer;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.segment.BaseObjectColumnValueSelector;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.NilColumnValueSelector;
+import org.apache.druid.segment.QueryableIndex;
+import org.apache.druid.segment.QueryableIndexColumnSelectorFactory;
+import org.apache.druid.segment.QueryableIndexSegment;
+import org.apache.druid.segment.QueryableIndexStorageAdapter;
+import org.apache.druid.segment.SimpleAscendingOffset;
+import org.apache.druid.segment.VirtualColumns;
+import org.apache.druid.segment.column.BaseColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.segment.data.ReadableOffset;
+import org.apache.druid.segment.filter.Filters;
+import org.joda.time.chrono.ISOChronology;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class BroadcastSegmentIndexedTable implements IndexedTable
+{
+ private static final Logger LOG = new Logger(BroadcastSegmentIndexedTable.class);
+
+ private final QueryableIndexSegment segment;
+ private final QueryableIndexStorageAdapter adapter;
+ private final QueryableIndex queryableIndex;
+ private final Set<String> keyColumns;
+ private final RowSignature rowSignature;
+ private final String version;
+ private final List<Map<Object, IntList>> keyColumnsIndex;
+
+ public BroadcastSegmentIndexedTable(final QueryableIndexSegment theSegment, final Set<String> keyColumns, final String version)
+ {
+ this.keyColumns = keyColumns;
+ this.version = version;
+ this.segment = Preconditions.checkNotNull(theSegment, "Segment must not be null");
+ this.adapter = Preconditions.checkNotNull(
+ (QueryableIndexStorageAdapter) segment.asStorageAdapter(),
+ "Segment[%s] must have a QueryableIndexStorageAdapter",
+ segment.getId()
+ );
+ this.queryableIndex = Preconditions.checkNotNull(
+ segment.asQueryableIndex(),
+ "Segment[%s] must have a QueryableIndexSegment",
+ segment.getId()
+ );
+
+ RowSignature.Builder sigBuilder = RowSignature.builder();
+ sigBuilder.add(ColumnHolder.TIME_COLUMN_NAME, ValueType.LONG);
+ for (String column : queryableIndex.getColumnNames()) {
+ sigBuilder.add(column, adapter.getColumnCapabilities(column).getType());
+ }
+ this.rowSignature = sigBuilder.build();
+
+ // initialize keycolumn index maps
+ this.keyColumnsIndex = new ArrayList<>(rowSignature.size());
+ final List<String> keyColumnNames = new ArrayList<>(keyColumns.size());
+ for (int i = 0; i < rowSignature.size(); i++) {
+ final Map<Object, IntList> m;
+ final String columnName = rowSignature.getColumnName(i);
+ if (keyColumns.contains(columnName)) {
+ m = new HashMap<>();
+ keyColumnNames.add(columnName);
+ } else {
+ m = null;
+ }
+ keyColumnsIndex.add(m);
+ }
+
+ // sort of like the dump segment tool, but build key column indexes when reading the segment
+ final Sequence<Cursor> cursors = adapter.makeCursors(
+ Filters.toFilter(null),
+ queryableIndex.getDataInterval().withChronology(ISOChronology.getInstanceUTC()),
+ VirtualColumns.EMPTY,
+ Granularities.ALL,
+ false,
+ null
+ );
+
+ final Sequence<Integer> sequence = Sequences.map(
+ cursors,
+ cursor -> {
+ if (cursor == null) {
+ return 0;
+ }
+ int rowNumber = 0;
+ ColumnSelectorFactory columnSelectorFactory = cursor.getColumnSelectorFactory();
+
+ // this should really be optimized to use dimension selectors where possible to populate indexes from bitmap
+ // indexes, but, an optimization for another day
+ final List<BaseObjectColumnValueSelector> selectors = keyColumnNames
+ .stream()
+ .map(columnName -> {
+ // multi-value dimensions are not currently supported
+ if (adapter.getColumnCapabilities(columnName).hasMultipleValues().isMaybeTrue()) {
+ return NilColumnValueSelector.instance();
+ }
+ return columnSelectorFactory.makeColumnValueSelector(columnName);
+ })
+ .collect(Collectors.toList());
+
+ while (!cursor.isDone()) {
+ for (int keyColumnSelectorIndex = 0; keyColumnSelectorIndex < selectors.size(); keyColumnSelectorIndex++) {
+ final String keyColumnName = keyColumnNames.get(keyColumnSelectorIndex);
+ final int columnPosition = rowSignature.indexOf(keyColumnName);
+ final Map<Object, IntList> keyColumnValueIndex = keyColumnsIndex.get(columnPosition);
+ final Object key = selectors.get(keyColumnSelectorIndex).getObject();
+ if (key != null) {
+ final IntList array = keyColumnValueIndex.computeIfAbsent(key, k -> new IntArrayList());
+ array.add(rowNumber);
+ }
+ }
+
+ if (rowNumber % 100_000 == 0) {
+ if (rowNumber == 0) {
+ LOG.debug("Indexed first row for table %s", theSegment.getId());
+ } else {
+ LOG.debug("Indexed row %s for table %s", rowNumber, theSegment.getId());
+ }
+ }
+ rowNumber++;
+ cursor.advance();
+ }
+ return rowNumber;
+ }
+ );
+
+ Integer totalRows = sequence.accumulate(0, (accumulated, in) -> accumulated += in);
+ LOG.info("Created BroadcastSegmentIndexedTable with %s rows.", totalRows);
+ }
+
+ @Override
+ public String version()
+ {
+ return version;
+ }
+
+ @Override
+ public Set<String> keyColumns()
+ {
+ return keyColumns;
+ }
+
+ @Override
+ public RowSignature rowSignature()
+ {
+ return rowSignature;
+ }
+
+ @Override
+ public int numRows()
+ {
+ return adapter.getNumRows();
+ }
+
+ @Override
+ public Index columnIndex(int column)
+ {
+ return RowBasedIndexedTable.getKeyColumnIndex(column, keyColumnsIndex, rowSignature);
+ }
+
+ @Override
+ public Reader columnReader(int column)
+ {
+ if (column < 0 || rowSignature.getColumnName(0) == null) {
Review comment:
oops, good catch, though it accidentally will throw the same index out of bounds exception a few lines later
```java
final BaseColumn baseColumn = queryableIndex.getColumnHolder(rowSignature.getColumnName(column)).getColumn();
```
However, this check isn't really a good check since it is inconsistent which exception will be thrown, so I've added a `contains` method to `RowSignature` that works with column position to ensure that the index is in range so the exception can be consistently be the IAE being thrown here.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r466711588
##########
File path: processing/src/main/java/org/apache/druid/segment/join/MapJoinableFactory.java
##########
@@ -19,49 +19,64 @@
package org.apache.druid.segment.join;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.SetMultimap;
import com.google.inject.Inject;
+import org.apache.druid.java.util.common.ISE;
import org.apache.druid.query.DataSource;
-import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
/**
* A {@link JoinableFactory} that delegates to the appropriate factory based on the type of the datasource.
*
- * Datasources can register a factory via a DruidBinder
+ * Datasources can register a factory via a DruidBinder. Any number of factories can be bound to a datasource, the
+ * 'first' that matches will be returned to the caller, or none if no matches.
*/
public class MapJoinableFactory implements JoinableFactory
{
- private final Map<Class<? extends DataSource>, JoinableFactory> joinableFactories;
+ private final SetMultimap<Class<? extends DataSource>, JoinableFactory> joinableFactories;
@Inject
- public MapJoinableFactory(Map<Class<? extends DataSource>, JoinableFactory> joinableFactories)
+ public MapJoinableFactory(
+ Set<JoinableFactory> factories,
+ Map<Class<? extends JoinableFactory>, Class<? extends DataSource>> factoryToDataSource
+ )
{
- // Accesses to IdentityHashMap should be faster than to HashMap or ImmutableMap.
- // Class doesn't override Object.equals().
- this.joinableFactories = new IdentityHashMap<>(joinableFactories);
+ this.joinableFactories = HashMultimap.create();
+ factories.forEach(joinableFactory -> {
+ joinableFactories.put(factoryToDataSource.get(joinableFactory.getClass()), joinableFactory);
+ });
}
@Override
public boolean isDirectlyJoinable(DataSource dataSource)
{
- JoinableFactory factory = joinableFactories.get(dataSource.getClass());
- if (factory == null) {
- return false;
- } else {
- return factory.isDirectlyJoinable(dataSource);
+ Set<JoinableFactory> factories = joinableFactories.get(dataSource.getClass());
+ for (JoinableFactory factory : factories) {
+ if (factory.isDirectlyJoinable(dataSource)) {
+ return true;
+ }
}
+ return false;
}
@Override
public Optional<Joinable> build(DataSource dataSource, JoinConditionAnalysis condition)
{
- JoinableFactory factory = joinableFactories.get(dataSource.getClass());
- if (factory == null) {
- return Optional.empty();
- } else {
- return factory.build(dataSource, condition);
+ Set<JoinableFactory> factories = joinableFactories.get(dataSource.getClass());
+ Optional<Joinable> maybeJoinable = Optional.empty();
+ for (JoinableFactory factory : factories) {
+ Optional<Joinable> candidate = factory.build(dataSource, condition);
+ if (candidate.isPresent()) {
+ if (maybeJoinable.isPresent()) {
+ throw new ISE("Multiple joinable factories are valid for table[%s]", dataSource);
Review comment:
That comment isn't super clear, will add some more details. Multiple factories can be bound to the same class of datasource (because factory is an extension point), but not to the same exact datasource (because only 1 factory can create the joinable to use in the query). Having a mix of joinables in the same datasource is an invalid state, so this explodes to prevent undefined behavior instead of just using whichever is first in the set.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on pull request #10224:
URL: https://github.com/apache/druid/pull/10224#issuecomment-668866723
I made some fixes to this PR because while I was testing some stuff I ran into a leak of buffers, because the columns were not being closed that were created by creating the `Reader`. In response to this, I've modified `HashJoinSegmentStorageAdapter` to feed a `Closer` that runs in the sequence baggage similar to `QueryableIndexCursorSequenceBuilder`, and thread it into the join matcher/cursors down into `IndexedTableColumnSelectorFactory` and into `IndexedTableColumnValueSelector` and `IndexedTableDimensionSelector`, so that the `IndexedTable.Reader` they create can be closed when the cursors sequence is processed.
I've also added a new method to the `IndexedTable` interface:
```java
@Nullable
default ColumnSelectorFactory makeColumnSelectorFactory(ReadableOffset offset, boolean descending, Closer closer)
{
return null;
}
```
to allow it to directly provide `ColumnSelectorFactory` to `IndexedTableJoinMatcher` instead of using `IndexedTableColumnSelectorFactory`. This allows `BroadcastSegmentIndexedTable` to supply a `QueryableIndexColumnSelectorFactory` directly from the underlying segment instead of all the indirection of using a `Reader` through the standard selectors. The performance improvement seems pretty significant (from some benchmarks I've been playing with that are not in this PR, will add later, projection '6' in this case is selecting 3 columns from the rhs table):
before:
```
Benchmark (lhsJoinColumn) (projection) (rhsJoinColumn) (rowsPerSegment) (rowsPerTableSegment) (tableType) Mode Cnt Score Error Units
IndexedTableBenchmark.hashJoinCursorColumnValueSelectors dimZipf 6 dimUniform 50000 50000 segment avgt 5 77.403 ± 57.426 ms/op
```
after:
```
Benchmark (lhsJoinColumn) (projection) (rhsJoinColumn) (rowsPerSegment) (rowsPerTableSegment) (tableType) Mode Cnt Score Error Units
IndexedTableBenchmark.hashJoinCursorColumnValueSelectors dimZipf 6 dimUniform 50000 50000 segment avgt 5 20.060 ± 1.627 ms/op
```
I'm sure there are a lot more improvements that could be made, but will save that for future work.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r470285932
##########
File path: processing/src/main/java/org/apache/druid/segment/join/HashJoinEngine.java
##########
@@ -51,14 +52,16 @@ private HashJoinEngine()
* not be queryable through the returned Cursor. This happens even if the right-hand joinable doesn't actually have a
* column with this name.
*/
- public static Cursor makeJoinCursor(final Cursor leftCursor, final JoinableClause joinableClause)
+ public static Cursor makeJoinCursor(final Cursor leftCursor, final JoinableClause joinableClause, boolean descending, final Closer closer)
Review comment:
changed, also fixed formatting because line was too long
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] jihoonson commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
jihoonson commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r470300832
##########
File path: server/src/main/java/org/apache/druid/segment/join/BroadcastTableJoinableFactory.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.druid.segment.join;
+
+import com.google.common.collect.Iterators;
+import com.google.inject.Inject;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.GlobalTableDataSource;
+import org.apache.druid.query.planning.DataSourceAnalysis;
+import org.apache.druid.segment.join.table.IndexedTableJoinable;
+import org.apache.druid.segment.join.table.ReferenceCountingIndexedTable;
+import org.apache.druid.server.SegmentManager;
+
+import java.util.Iterator;
+import java.util.Optional;
+
+public class BroadcastTableJoinableFactory implements JoinableFactory
+{
+ private final SegmentManager segmentManager;
+
+ @Inject
+ public BroadcastTableJoinableFactory(SegmentManager segmentManager)
+ {
+ this.segmentManager = segmentManager;
+ }
+
+ @Override
+ public boolean isDirectlyJoinable(DataSource dataSource)
+ {
+ GlobalTableDataSource broadcastDatasource = (GlobalTableDataSource) dataSource;
+ return broadcastDatasource != null && segmentManager.hasIndexedTables(broadcastDatasource.getName());
+ }
+
+ @Override
+ public Optional<Joinable> build(
+ DataSource dataSource,
+ JoinConditionAnalysis condition
+ )
+ {
+ GlobalTableDataSource broadcastDatasource = (GlobalTableDataSource) dataSource;
+ if (condition.canHashJoin()) {
+ DataSourceAnalysis analysis = DataSourceAnalysis.forDataSource(broadcastDatasource);
+ return segmentManager.getIndexedTables(analysis).map(tables -> {
+ Iterator<ReferenceCountingIndexedTable> tableIterator = tables.iterator();
+ if (!tableIterator.hasNext()) {
+ return null;
Review comment:
Oops, you are correct.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r470285986
##########
File path: processing/src/main/java/org/apache/druid/segment/join/table/IndexedTableJoinable.java
##########
@@ -97,41 +103,49 @@ public JoinMatcher makeJoinMatcher(
if (filterColumnPosition < 0 || correlatedColumnPosition < 0) {
return Optional.empty();
}
+ Closer closer = Closer.create();
+ try {
+ Set<String> correlatedValues = new HashSet<>();
+ if (table.keyColumns().contains(searchColumnName)) {
+ IndexedTable.Index index = table.columnIndex(filterColumnPosition);
+ IndexedTable.Reader reader = table.columnReader(correlatedColumnPosition);
+ closer.register(reader);
+ IntList rowIndex = index.find(searchColumnValue);
+ for (int i = 0; i < rowIndex.size(); i++) {
+ int rowNum = rowIndex.getInt(i);
+ String correlatedDimVal = Objects.toString(reader.read(rowNum), null);
+ correlatedValues.add(correlatedDimVal);
- Set<String> correlatedValues = new HashSet<>();
- if (table.keyColumns().contains(searchColumnName)) {
- IndexedTable.Index index = table.columnIndex(filterColumnPosition);
- IndexedTable.Reader reader = table.columnReader(correlatedColumnPosition);
- IntList rowIndex = index.find(searchColumnValue);
- for (int i = 0; i < rowIndex.size(); i++) {
- int rowNum = rowIndex.getInt(i);
- String correlatedDimVal = Objects.toString(reader.read(rowNum), null);
- correlatedValues.add(correlatedDimVal);
-
- if (correlatedValues.size() > maxCorrelationSetSize) {
+ if (correlatedValues.size() > maxCorrelationSetSize) {
+ return Optional.empty();
+ }
+ }
+ return Optional.of(correlatedValues);
+ } else {
+ if (!allowNonKeyColumnSearch) {
return Optional.empty();
}
- }
- return Optional.of(correlatedValues);
- } else {
- if (!allowNonKeyColumnSearch) {
- return Optional.empty();
- }
- IndexedTable.Reader dimNameReader = table.columnReader(filterColumnPosition);
- IndexedTable.Reader correlatedColumnReader = table.columnReader(correlatedColumnPosition);
- for (int i = 0; i < table.numRows(); i++) {
- String dimVal = Objects.toString(dimNameReader.read(i), null);
- if (searchColumnValue.equals(dimVal)) {
- String correlatedDimVal = Objects.toString(correlatedColumnReader.read(i), null);
- correlatedValues.add(correlatedDimVal);
- if (correlatedValues.size() > maxCorrelationSetSize) {
- return Optional.empty();
+ IndexedTable.Reader dimNameReader = table.columnReader(filterColumnPosition);
+ IndexedTable.Reader correlatedColumnReader = table.columnReader(correlatedColumnPosition);
+ closer.register(dimNameReader);
+ closer.register(correlatedColumnReader);
+ for (int i = 0; i < table.numRows(); i++) {
+ String dimVal = Objects.toString(dimNameReader.read(i), null);
+ if (searchColumnValue.equals(dimVal)) {
+ String correlatedDimVal = Objects.toString(correlatedColumnReader.read(i), null);
+ correlatedValues.add(correlatedDimVal);
+ if (correlatedValues.size() > maxCorrelationSetSize) {
+ return Optional.empty();
+ }
}
}
- }
- return Optional.of(correlatedValues);
+ return Optional.of(correlatedValues);
+ }
+ }
+ finally {
+ CloseQuietly.close(closer);
Review comment:
removed all usage of `CloseQuietly` in this PR
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] abhishekagarwal87 commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
abhishekagarwal87 commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r471313578
##########
File path: processing/src/main/java/org/apache/druid/segment/join/table/BroadcastSegmentIndexedTable.java
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.druid.segment.join.table;
+
+import com.google.common.base.Preconditions;
+import it.unimi.dsi.fastutil.ints.IntArrayList;
+import it.unimi.dsi.fastutil.ints.IntList;
+import org.apache.druid.java.util.common.IAE;
+import org.apache.druid.java.util.common.granularity.Granularities;
+import org.apache.druid.java.util.common.guava.Sequence;
+import org.apache.druid.java.util.common.guava.Sequences;
+import org.apache.druid.java.util.common.io.Closer;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.segment.BaseObjectColumnValueSelector;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.NilColumnValueSelector;
+import org.apache.druid.segment.QueryableIndex;
+import org.apache.druid.segment.QueryableIndexColumnSelectorFactory;
+import org.apache.druid.segment.QueryableIndexSegment;
+import org.apache.druid.segment.QueryableIndexStorageAdapter;
+import org.apache.druid.segment.SimpleAscendingOffset;
+import org.apache.druid.segment.VirtualColumns;
+import org.apache.druid.segment.column.BaseColumn;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.segment.data.ReadableOffset;
+import org.apache.druid.segment.filter.Filters;
+import org.joda.time.chrono.ISOChronology;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class BroadcastSegmentIndexedTable implements IndexedTable
+{
+ private static final Logger LOG = new Logger(BroadcastSegmentIndexedTable.class);
+
+ private final QueryableIndexSegment segment;
+ private final QueryableIndexStorageAdapter adapter;
+ private final QueryableIndex queryableIndex;
+ private final Set<String> keyColumns;
+ private final RowSignature rowSignature;
+ private final String version;
+ private final List<Map<Object, IntList>> keyColumnsIndex;
+
+ public BroadcastSegmentIndexedTable(final QueryableIndexSegment theSegment, final Set<String> keyColumns, final String version)
+ {
+ this.keyColumns = keyColumns;
+ this.version = version;
+ this.segment = Preconditions.checkNotNull(theSegment, "Segment must not be null");
+ this.adapter = Preconditions.checkNotNull(
+ (QueryableIndexStorageAdapter) segment.asStorageAdapter(),
+ "Segment[%s] must have a QueryableIndexStorageAdapter",
+ segment.getId()
+ );
+ this.queryableIndex = Preconditions.checkNotNull(
+ segment.asQueryableIndex(),
+ "Segment[%s] must have a QueryableIndexSegment",
+ segment.getId()
+ );
+
+ RowSignature.Builder sigBuilder = RowSignature.builder();
+ sigBuilder.add(ColumnHolder.TIME_COLUMN_NAME, ValueType.LONG);
+ for (String column : queryableIndex.getColumnNames()) {
+ sigBuilder.add(column, adapter.getColumnCapabilities(column).getType());
+ }
+ this.rowSignature = sigBuilder.build();
+
+ // initialize keycolumn index maps
+ this.keyColumnsIndex = new ArrayList<>(rowSignature.size());
+ final List<String> keyColumnNames = new ArrayList<>(keyColumns.size());
+ for (int i = 0; i < rowSignature.size(); i++) {
+ final Map<Object, IntList> m;
+ final String columnName = rowSignature.getColumnName(i);
+ if (keyColumns.contains(columnName)) {
+ m = new HashMap<>();
+ keyColumnNames.add(columnName);
+ } else {
+ m = null;
+ }
+ keyColumnsIndex.add(m);
+ }
+
+ // sort of like the dump segment tool, but build key column indexes when reading the segment
+ final Sequence<Cursor> cursors = adapter.makeCursors(
+ Filters.toFilter(null),
+ queryableIndex.getDataInterval().withChronology(ISOChronology.getInstanceUTC()),
+ VirtualColumns.EMPTY,
+ Granularities.ALL,
+ false,
+ null
+ );
+
+ final Sequence<Integer> sequence = Sequences.map(
+ cursors,
+ cursor -> {
+ if (cursor == null) {
+ return 0;
+ }
+ int rowNumber = 0;
+ ColumnSelectorFactory columnSelectorFactory = cursor.getColumnSelectorFactory();
+
+ // this should really be optimized to use dimension selectors where possible to populate indexes from bitmap
+ // indexes, but, an optimization for another day
+ final List<BaseObjectColumnValueSelector> selectors = keyColumnNames
+ .stream()
+ .map(columnName -> {
+ // multi-value dimensions are not currently supported
+ if (adapter.getColumnCapabilities(columnName).hasMultipleValues().isMaybeTrue()) {
+ return NilColumnValueSelector.instance();
+ }
+ return columnSelectorFactory.makeColumnValueSelector(columnName);
+ })
+ .collect(Collectors.toList());
+
+ while (!cursor.isDone()) {
+ for (int keyColumnSelectorIndex = 0; keyColumnSelectorIndex < selectors.size(); keyColumnSelectorIndex++) {
+ final String keyColumnName = keyColumnNames.get(keyColumnSelectorIndex);
+ final int columnPosition = rowSignature.indexOf(keyColumnName);
+ final Map<Object, IntList> keyColumnValueIndex = keyColumnsIndex.get(columnPosition);
+ final Object key = selectors.get(keyColumnSelectorIndex).getObject();
+ if (key != null) {
+ final IntList array = keyColumnValueIndex.computeIfAbsent(key, k -> new IntArrayList());
+ array.add(rowNumber);
+ }
+ }
+
+ if (rowNumber % 100_000 == 0) {
+ if (rowNumber == 0) {
+ LOG.debug("Indexed first row for table %s", theSegment.getId());
+ } else {
+ LOG.debug("Indexed row %s for table %s", rowNumber, theSegment.getId());
+ }
+ }
+ rowNumber++;
+ cursor.advance();
+ }
+ return rowNumber;
+ }
+ );
+
+ Integer totalRows = sequence.accumulate(0, (accumulated, in) -> accumulated += in);
+ LOG.info("Created BroadcastSegmentIndexedTable with %s rows.", totalRows);
+ }
+
+ @Override
+ public String version()
+ {
+ return version;
+ }
+
+ @Override
+ public Set<String> keyColumns()
+ {
+ return keyColumns;
+ }
+
+ @Override
+ public RowSignature rowSignature()
+ {
+ return rowSignature;
+ }
+
+ @Override
+ public int numRows()
+ {
+ return adapter.getNumRows();
+ }
+
+ @Override
+ public Index columnIndex(int column)
+ {
+ return RowBasedIndexedTable.getKeyColumnIndex(column, keyColumnsIndex, rowSignature);
+ }
+
+ @Override
+ public Reader columnReader(int column)
+ {
+ if (column < 0 || rowSignature.getColumnName(0) == null) {
Review comment:
```suggestion
if (column < 0 || rowSignature.getColumnName(column) == null) {
```
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] jon-wei commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
jon-wei commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r466619530
##########
File path: processing/src/main/java/org/apache/druid/segment/join/table/RowBasedIndexedTable.java
##########
@@ -69,10 +68,6 @@ public RowBasedIndexedTable(
this.keyColumns = keyColumns;
this.version = version;
- if (new HashSet<>(keyColumns).size() != keyColumns.size()) {
Review comment:
Should this sanity check be retained?
##########
File path: processing/src/main/java/org/apache/druid/segment/join/MapJoinableFactory.java
##########
@@ -19,49 +19,64 @@
package org.apache.druid.segment.join;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.SetMultimap;
import com.google.inject.Inject;
+import org.apache.druid.java.util.common.ISE;
import org.apache.druid.query.DataSource;
-import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
/**
* A {@link JoinableFactory} that delegates to the appropriate factory based on the type of the datasource.
*
- * Datasources can register a factory via a DruidBinder
+ * Datasources can register a factory via a DruidBinder. Any number of factories can be bound to a datasource, the
+ * 'first' that matches will be returned to the caller, or none if no matches.
*/
public class MapJoinableFactory implements JoinableFactory
{
- private final Map<Class<? extends DataSource>, JoinableFactory> joinableFactories;
+ private final SetMultimap<Class<? extends DataSource>, JoinableFactory> joinableFactories;
@Inject
- public MapJoinableFactory(Map<Class<? extends DataSource>, JoinableFactory> joinableFactories)
+ public MapJoinableFactory(
+ Set<JoinableFactory> factories,
+ Map<Class<? extends JoinableFactory>, Class<? extends DataSource>> factoryToDataSource
+ )
{
- // Accesses to IdentityHashMap should be faster than to HashMap or ImmutableMap.
- // Class doesn't override Object.equals().
- this.joinableFactories = new IdentityHashMap<>(joinableFactories);
+ this.joinableFactories = HashMultimap.create();
+ factories.forEach(joinableFactory -> {
+ joinableFactories.put(factoryToDataSource.get(joinableFactory.getClass()), joinableFactory);
+ });
}
@Override
public boolean isDirectlyJoinable(DataSource dataSource)
{
- JoinableFactory factory = joinableFactories.get(dataSource.getClass());
- if (factory == null) {
- return false;
- } else {
- return factory.isDirectlyJoinable(dataSource);
+ Set<JoinableFactory> factories = joinableFactories.get(dataSource.getClass());
+ for (JoinableFactory factory : factories) {
+ if (factory.isDirectlyJoinable(dataSource)) {
+ return true;
+ }
}
+ return false;
}
@Override
public Optional<Joinable> build(DataSource dataSource, JoinConditionAnalysis condition)
{
- JoinableFactory factory = joinableFactories.get(dataSource.getClass());
- if (factory == null) {
- return Optional.empty();
- } else {
- return factory.build(dataSource, condition);
+ Set<JoinableFactory> factories = joinableFactories.get(dataSource.getClass());
+ Optional<Joinable> maybeJoinable = Optional.empty();
+ for (JoinableFactory factory : factories) {
+ Optional<Joinable> candidate = factory.build(dataSource, condition);
+ if (candidate.isPresent()) {
+ if (maybeJoinable.isPresent()) {
+ throw new ISE("Multiple joinable factories are valid for table[%s]", dataSource);
Review comment:
Can you explain why this is an error condition? From the comment at https://github.com/apache/druid/pull/10224/files#diff-51b09b44a8330d19728379390eef60a0R35 it sounds like multiple valid should be okay
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r470285387
##########
File path: server/src/main/java/org/apache/druid/server/SegmentManager.java
##########
@@ -258,6 +316,11 @@ public void dropSegment(final DataSegment segment)
log.info("Attempting to close segment %s", segment.getId());
oldQueryable.close();
+
+ final ReferenceCountingIndexedTable oldTable = dataSourceState.tablesLookup.remove(segment.getId());
+ if (oldTable != null) {
+ oldTable.close();
Review comment:
changed to use `Closer`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on pull request #10224:
URL: https://github.com/apache/druid/pull/10224#issuecomment-673863710
Thanks for the review @jon-wei and @jihoonson :metal:
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] jihoonson commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
jihoonson commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r463924917
##########
File path: processing/src/main/java/org/apache/druid/segment/join/table/BroadcastSegmentIndexedTable.java
##########
@@ -0,0 +1,218 @@
+/*
+ * 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.druid.segment.join.table;
+
+import it.unimi.dsi.fastutil.ints.IntArrayList;
+import it.unimi.dsi.fastutil.ints.IntList;
+import org.apache.druid.java.util.common.IAE;
+import org.apache.druid.java.util.common.granularity.Granularities;
+import org.apache.druid.java.util.common.guava.Sequence;
+import org.apache.druid.java.util.common.guava.Sequences;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.segment.BaseObjectColumnValueSelector;
+import org.apache.druid.segment.ColumnSelectorFactory;
+import org.apache.druid.segment.Cursor;
+import org.apache.druid.segment.DimensionHandlerUtils;
+import org.apache.druid.segment.QueryableIndex;
+import org.apache.druid.segment.QueryableIndexSegment;
+import org.apache.druid.segment.QueryableIndexStorageAdapter;
+import org.apache.druid.segment.SimpleAscendingOffset;
+import org.apache.druid.segment.VirtualColumns;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.segment.filter.Filters;
+import org.joda.time.chrono.ISOChronology;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class BroadcastSegmentIndexedTable implements IndexedTable
+{
+ private static final Logger LOG = new Logger(BroadcastSegmentIndexedTable.class);
+
+ private final QueryableIndexSegment segment;
+ private final QueryableIndexStorageAdapter adapter;
+ private final QueryableIndex queryableIndex;
+ private final Set<String> keyColumns;
+ private final RowSignature rowSignature;
+ private final String version;
+ private final List<Map<Object, IntList>> keyColumnsIndex;
+
+ public BroadcastSegmentIndexedTable(final QueryableIndexSegment theSegment, final Set<String> keyColumns, final String version)
+ {
+ this.keyColumns = keyColumns;
+ this.version = version;
+ this.segment = theSegment;
+ this.adapter = (QueryableIndexStorageAdapter) segment.asStorageAdapter();
+ this.queryableIndex = segment.asQueryableIndex();
+
+ RowSignature.Builder sigBuilder = RowSignature.builder();
+ sigBuilder.add(ColumnHolder.TIME_COLUMN_NAME, ValueType.LONG);
+ for (String column : queryableIndex.getColumnNames()) {
+ sigBuilder.add(column, adapter.getColumnCapabilities(column).getType());
+ }
+ this.rowSignature = sigBuilder.build();
+
+ // initialize keycolumn index maps
+ this.keyColumnsIndex = new ArrayList<>(rowSignature.size());
+ final List<String> keyColumnNames = new ArrayList<>(keyColumns.size());
+ for (int i = 0; i < rowSignature.size(); i++) {
+ final Map<Object, IntList> m;
+ final String columnName = rowSignature.getColumnName(i);
+ if (keyColumns.contains(columnName)) {
+ m = new HashMap<>();
+ keyColumnNames.add(columnName);
+ } else {
+ m = null;
+ }
+ keyColumnsIndex.add(m);
+ }
+
+ // sort of like the dump segment tool, but build key column indexes when reading the segment
+ final Sequence<Cursor> cursors = adapter.makeCursors(
+ Filters.toFilter(null),
+ queryableIndex.getDataInterval().withChronology(ISOChronology.getInstanceUTC()),
+ VirtualColumns.EMPTY,
+ Granularities.ALL,
+ false,
+ null
+ );
+
+ final Sequence<Integer> sequence = Sequences.map(
+ cursors,
+ cursor -> {
+ int rowNumber = 0;
+ ColumnSelectorFactory columnSelectorFactory = cursor.getColumnSelectorFactory();
+
+ // this should really be optimized to use dimension selectors where possible to populate indexes from bitmap
+ // indexes, but, an optimization for another day
+ final List<BaseObjectColumnValueSelector> selectors = keyColumnNames
+ .stream()
+ .map(columnSelectorFactory::makeColumnValueSelector)
+ .collect(Collectors.toList());
+
+ while (!cursor.isDone()) {
+ for (int keyColumnSelectorIndex = 0; keyColumnSelectorIndex < selectors.size(); keyColumnSelectorIndex++) {
+ final String keyColumnName = keyColumnNames.get(keyColumnSelectorIndex);
+ final int columnPosition = rowSignature.indexOf(keyColumnName);
+ final Map<Object, IntList> keyColumnValueIndex = keyColumnsIndex.get(columnPosition);
+
+ final Object value = selectors.get(keyColumnSelectorIndex).getObject();
+ final ValueType keyType = rowSignature.getColumnType(keyColumnName)
+ .orElse(IndexedTableJoinMatcher.DEFAULT_KEY_TYPE);
+ // is this actually necessary or is value already cool? (RowBasedIndexedTable cargo cult represent)
+ final Object key = DimensionHandlerUtils.convertObjectToType(value, keyType);
+
+ if (key != null) {
+ final IntList array = keyColumnValueIndex.computeIfAbsent(key, k -> new IntArrayList());
+ array.add(rowNumber);
+ }
+ }
+
+ if (rowNumber % 100_000 == 0) {
+ if (rowNumber == 0) {
+ LOG.info("Indexed first row for table %s", theSegment.getId());
+ } else {
+ LOG.info("Indexed row %s for table %s", rowNumber, theSegment.getId());
Review comment:
Should these be debug logs?
##########
File path: server/src/main/java/org/apache/druid/server/SegmentManager.java
##########
@@ -155,13 +172,44 @@ public boolean isSegmentCached(final DataSegment segment)
*/
public Optional<VersionedIntervalTimeline<String, ReferenceCountingSegment>> getTimeline(DataSourceAnalysis analysis)
{
- final TableDataSource tableDataSource =
- analysis.getBaseTableDataSource()
- .orElseThrow(() -> new ISE("Cannot handle datasource: %s", analysis.getDataSource()));
-
+ final TableDataSource tableDataSource = getTableDataSource(analysis);
return Optional.ofNullable(dataSources.get(tableDataSource.getName())).map(DataSourceState::getTimeline);
}
+ public List<ReferenceCountingIndexedTable> getIndexedTables(
+ DataSourceAnalysis analysis,
+ JoinConditionAnalysis joinCondition
Review comment:
Unused variable.
##########
File path: server/src/main/java/org/apache/druid/server/SegmentManager.java
##########
@@ -155,13 +172,44 @@ public boolean isSegmentCached(final DataSegment segment)
*/
public Optional<VersionedIntervalTimeline<String, ReferenceCountingSegment>> getTimeline(DataSourceAnalysis analysis)
{
- final TableDataSource tableDataSource =
- analysis.getBaseTableDataSource()
- .orElseThrow(() -> new ISE("Cannot handle datasource: %s", analysis.getDataSource()));
-
+ final TableDataSource tableDataSource = getTableDataSource(analysis);
return Optional.ofNullable(dataSources.get(tableDataSource.getName())).map(DataSourceState::getTimeline);
}
+ public List<ReferenceCountingIndexedTable> getIndexedTables(
+ DataSourceAnalysis analysis,
+ JoinConditionAnalysis joinCondition
+ )
+ {
+ return getTimeline(analysis).map(timeline -> {
+ // join doesn't currently consider intervals, so just consider all segments
+ final Collection<ReferenceCountingSegment> segments =
+ timeline.lookup(Intervals.ETERNITY)
+ .stream()
+ .flatMap(x -> StreamSupport.stream(x.getObject().payloads().spliterator(), false))
+ .collect(Collectors.toList());
Review comment:
nit: you don't have materialize `segments` here. Instead, you can call `map` on the stream directly in the below.
##########
File path: processing/src/test/java/org/apache/druid/segment/join/table/BroadcastSegmentIndexedTableTest.java
##########
@@ -0,0 +1,274 @@
+/*
+ * 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.druid.segment.join.table;
+
+import com.fasterxml.jackson.databind.InjectableValues;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import it.unimi.dsi.fastutil.ints.IntList;
+import org.apache.druid.common.config.NullHandling;
+import org.apache.druid.jackson.DefaultObjectMapper;
+import org.apache.druid.jackson.SegmentizerModule;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.IAE;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.expression.TestExprMacroTable;
+import org.apache.druid.segment.BaseObjectColumnValueSelector;
+import org.apache.druid.segment.IndexIO;
+import org.apache.druid.segment.IndexMerger;
+import org.apache.druid.segment.IndexMergerV9;
+import org.apache.druid.segment.IndexSpec;
+import org.apache.druid.segment.QueryableIndexSegment;
+import org.apache.druid.segment.SimpleAscendingOffset;
+import org.apache.druid.segment.TestIndex;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.incremental.IncrementalIndex;
+import org.apache.druid.segment.loading.MMappedQueryableSegmentizerFactory;
+import org.apache.druid.segment.loading.SegmentLoadingException;
+import org.apache.druid.segment.loading.SegmentizerFactory;
+import org.apache.druid.segment.writeout.OffHeapMemorySegmentWriteOutMediumFactory;
+import org.apache.druid.testing.InitializedNullHandlingTest;
+import org.apache.druid.timeline.DataSegment;
+import org.joda.time.Interval;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+public class BroadcastSegmentIndexedTableTest extends InitializedNullHandlingTest
+{
+ private static final String STRING_COL_1 = "market";
+ private static final String LONG_COL_1 = "longNumericNull";
+ private static final String DOUBLE_COL_1 = "doubleNumericNull";
+ private static final String FLOAT_COL_1 = "floatNumericNull";
+ private static final String STRING_COL_2 = "partial_null_column";
+ private static final String MULTI_VALUE_COLUMN = "placementish";
+ private static final String DIM_NOT_EXISTS = "DIM_NOT_EXISTS";
+ private static final String DATASOURCE = "DATASOURCE";
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ private QueryableIndexSegment backingSegment;
+ private BroadcastSegmentIndexedTable broadcastTable;
+ private List<String> columnNames;
+ private final Set<String> keyColumns = ImmutableSet.<String>builder()
+ .add(STRING_COL_1)
+ .add(STRING_COL_2)
+ .add(LONG_COL_1)
+ .add(DOUBLE_COL_1)
+ .add(FLOAT_COL_1)
+ .add(MULTI_VALUE_COLUMN)
+ .add(DIM_NOT_EXISTS)
+ .build();
+
+ @Before
+ public void setup() throws IOException, SegmentLoadingException
+ {
+ NullHandling.initializeForTests();
Review comment:
Seems unnecessary since this test extends `InitializeNullHandlingTest`.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r470285566
##########
File path: server/src/main/java/org/apache/druid/segment/join/BroadcastTableJoinableFactory.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.druid.segment.join;
+
+import com.google.common.collect.Iterators;
+import com.google.inject.Inject;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.GlobalTableDataSource;
+import org.apache.druid.query.planning.DataSourceAnalysis;
+import org.apache.druid.segment.join.table.IndexedTableJoinable;
+import org.apache.druid.segment.join.table.ReferenceCountingIndexedTable;
+import org.apache.druid.server.SegmentManager;
+
+import java.util.Iterator;
+import java.util.Optional;
+
+public class BroadcastTableJoinableFactory implements JoinableFactory
+{
+ private final SegmentManager segmentManager;
+
+ @Inject
+ public BroadcastTableJoinableFactory(SegmentManager segmentManager)
+ {
+ this.segmentManager = segmentManager;
+ }
+
+ @Override
+ public boolean isDirectlyJoinable(DataSource dataSource)
+ {
+ GlobalTableDataSource broadcastDatasource = (GlobalTableDataSource) dataSource;
+ return broadcastDatasource != null && segmentManager.hasIndexedTables(broadcastDatasource.getName());
+ }
+
+ @Override
+ public Optional<Joinable> build(
+ DataSource dataSource,
+ JoinConditionAnalysis condition
+ )
+ {
+ GlobalTableDataSource broadcastDatasource = (GlobalTableDataSource) dataSource;
+ if (condition.canHashJoin()) {
+ DataSourceAnalysis analysis = DataSourceAnalysis.forDataSource(broadcastDatasource);
+ return segmentManager.getIndexedTables(analysis).map(tables -> {
+ Iterator<ReferenceCountingIndexedTable> tableIterator = tables.iterator();
+ if (!tableIterator.hasNext()) {
+ return null;
Review comment:
No, since this is inside a `Optional.map`, the function needs to return the thing that goes in the `Optional`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] jihoonson commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
jihoonson commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r463926773
##########
File path: server/src/main/java/org/apache/druid/server/SegmentManager.java
##########
@@ -155,13 +172,44 @@ public boolean isSegmentCached(final DataSegment segment)
*/
public Optional<VersionedIntervalTimeline<String, ReferenceCountingSegment>> getTimeline(DataSourceAnalysis analysis)
{
- final TableDataSource tableDataSource =
- analysis.getBaseTableDataSource()
- .orElseThrow(() -> new ISE("Cannot handle datasource: %s", analysis.getDataSource()));
-
+ final TableDataSource tableDataSource = getTableDataSource(analysis);
return Optional.ofNullable(dataSources.get(tableDataSource.getName())).map(DataSourceState::getTimeline);
}
+ public List<ReferenceCountingIndexedTable> getIndexedTables(
+ DataSourceAnalysis analysis,
+ JoinConditionAnalysis joinCondition
+ )
+ {
+ return getTimeline(analysis).map(timeline -> {
+ // join doesn't currently consider intervals, so just consider all segments
+ final Collection<ReferenceCountingSegment> segments =
+ timeline.lookup(Intervals.ETERNITY)
+ .stream()
+ .flatMap(x -> StreamSupport.stream(x.getObject().payloads().spliterator(), false))
+ .collect(Collectors.toList());
Review comment:
nit: you don't have to materialize `segments` here. Instead, you can call `map` on the stream directly in the below.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] jihoonson commented on a change in pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
jihoonson commented on a change in pull request #10224:
URL: https://github.com/apache/druid/pull/10224#discussion_r470266457
##########
File path: processing/src/main/java/org/apache/druid/segment/join/table/IndexedTableJoinable.java
##########
@@ -97,41 +103,49 @@ public JoinMatcher makeJoinMatcher(
if (filterColumnPosition < 0 || correlatedColumnPosition < 0) {
return Optional.empty();
}
+ Closer closer = Closer.create();
+ try {
+ Set<String> correlatedValues = new HashSet<>();
+ if (table.keyColumns().contains(searchColumnName)) {
+ IndexedTable.Index index = table.columnIndex(filterColumnPosition);
+ IndexedTable.Reader reader = table.columnReader(correlatedColumnPosition);
+ closer.register(reader);
+ IntList rowIndex = index.find(searchColumnValue);
+ for (int i = 0; i < rowIndex.size(); i++) {
+ int rowNum = rowIndex.getInt(i);
+ String correlatedDimVal = Objects.toString(reader.read(rowNum), null);
+ correlatedValues.add(correlatedDimVal);
- Set<String> correlatedValues = new HashSet<>();
- if (table.keyColumns().contains(searchColumnName)) {
- IndexedTable.Index index = table.columnIndex(filterColumnPosition);
- IndexedTable.Reader reader = table.columnReader(correlatedColumnPosition);
- IntList rowIndex = index.find(searchColumnValue);
- for (int i = 0; i < rowIndex.size(); i++) {
- int rowNum = rowIndex.getInt(i);
- String correlatedDimVal = Objects.toString(reader.read(rowNum), null);
- correlatedValues.add(correlatedDimVal);
-
- if (correlatedValues.size() > maxCorrelationSetSize) {
+ if (correlatedValues.size() > maxCorrelationSetSize) {
+ return Optional.empty();
+ }
+ }
+ return Optional.of(correlatedValues);
+ } else {
+ if (!allowNonKeyColumnSearch) {
return Optional.empty();
}
- }
- return Optional.of(correlatedValues);
- } else {
- if (!allowNonKeyColumnSearch) {
- return Optional.empty();
- }
- IndexedTable.Reader dimNameReader = table.columnReader(filterColumnPosition);
- IndexedTable.Reader correlatedColumnReader = table.columnReader(correlatedColumnPosition);
- for (int i = 0; i < table.numRows(); i++) {
- String dimVal = Objects.toString(dimNameReader.read(i), null);
- if (searchColumnValue.equals(dimVal)) {
- String correlatedDimVal = Objects.toString(correlatedColumnReader.read(i), null);
- correlatedValues.add(correlatedDimVal);
- if (correlatedValues.size() > maxCorrelationSetSize) {
- return Optional.empty();
+ IndexedTable.Reader dimNameReader = table.columnReader(filterColumnPosition);
+ IndexedTable.Reader correlatedColumnReader = table.columnReader(correlatedColumnPosition);
+ closer.register(dimNameReader);
+ closer.register(correlatedColumnReader);
+ for (int i = 0; i < table.numRows(); i++) {
+ String dimVal = Objects.toString(dimNameReader.read(i), null);
+ if (searchColumnValue.equals(dimVal)) {
+ String correlatedDimVal = Objects.toString(correlatedColumnReader.read(i), null);
+ correlatedValues.add(correlatedDimVal);
+ if (correlatedValues.size() > maxCorrelationSetSize) {
+ return Optional.empty();
+ }
}
}
- }
- return Optional.of(correlatedValues);
+ return Optional.of(correlatedValues);
+ }
+ }
+ finally {
+ CloseQuietly.close(closer);
Review comment:
Can we use try-with-resources instead of `CloseQuiently`? It would be more aligned with https://github.com/apache/druid/pull/10247 as well.
##########
File path: server/src/main/java/org/apache/druid/segment/join/BroadcastTableJoinableFactory.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.druid.segment.join;
+
+import com.google.common.collect.Iterators;
+import com.google.inject.Inject;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.query.DataSource;
+import org.apache.druid.query.GlobalTableDataSource;
+import org.apache.druid.query.planning.DataSourceAnalysis;
+import org.apache.druid.segment.join.table.IndexedTableJoinable;
+import org.apache.druid.segment.join.table.ReferenceCountingIndexedTable;
+import org.apache.druid.server.SegmentManager;
+
+import java.util.Iterator;
+import java.util.Optional;
+
+public class BroadcastTableJoinableFactory implements JoinableFactory
+{
+ private final SegmentManager segmentManager;
+
+ @Inject
+ public BroadcastTableJoinableFactory(SegmentManager segmentManager)
+ {
+ this.segmentManager = segmentManager;
+ }
+
+ @Override
+ public boolean isDirectlyJoinable(DataSource dataSource)
+ {
+ GlobalTableDataSource broadcastDatasource = (GlobalTableDataSource) dataSource;
+ return broadcastDatasource != null && segmentManager.hasIndexedTables(broadcastDatasource.getName());
+ }
+
+ @Override
+ public Optional<Joinable> build(
+ DataSource dataSource,
+ JoinConditionAnalysis condition
+ )
+ {
+ GlobalTableDataSource broadcastDatasource = (GlobalTableDataSource) dataSource;
+ if (condition.canHashJoin()) {
+ DataSourceAnalysis analysis = DataSourceAnalysis.forDataSource(broadcastDatasource);
+ return segmentManager.getIndexedTables(analysis).map(tables -> {
+ Iterator<ReferenceCountingIndexedTable> tableIterator = tables.iterator();
+ if (!tableIterator.hasNext()) {
+ return null;
Review comment:
Should it return `Optional.empty()` instead?
##########
File path: processing/src/main/java/org/apache/druid/segment/join/HashJoinEngine.java
##########
@@ -51,14 +52,16 @@ private HashJoinEngine()
* not be queryable through the returned Cursor. This happens even if the right-hand joinable doesn't actually have a
* column with this name.
*/
- public static Cursor makeJoinCursor(final Cursor leftCursor, final JoinableClause joinableClause)
+ public static Cursor makeJoinCursor(final Cursor leftCursor, final JoinableClause joinableClause, boolean descending, final Closer closer)
Review comment:
super nit: would you add `final` for `descending` as well just to be consistent?
##########
File path: server/src/main/java/org/apache/druid/server/SegmentManager.java
##########
@@ -258,6 +316,11 @@ public void dropSegment(final DataSegment segment)
log.info("Attempting to close segment %s", segment.getId());
oldQueryable.close();
+
+ final ReferenceCountingIndexedTable oldTable = dataSourceState.tablesLookup.remove(segment.getId());
+ if (oldTable != null) {
+ oldTable.close();
Review comment:
Hmm, should we use `Closer` to close `oldTable` and `oldQueryable` so that both can be closed even when any potential errors is thrown?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
[GitHub] [druid] clintropolis merged pull request #10224: Segment backed broadcast join IndexedTable
Posted by GitBox <gi...@apache.org>.
clintropolis merged pull request #10224:
URL: https://github.com/apache/druid/pull/10224
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org