You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by ne...@apache.org on 2019/08/02 15:58:17 UTC
[incubator-pinot] branch master updated: An auto recommendation for
inverted index (#4474)
This is an automated email from the ASF dual-hosted git repository.
nehapawar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-pinot.git
The following commit(s) were added to refs/heads/master by this push:
new 4fea0d4 An auto recommendation for inverted index (#4474)
4fea0d4 is described below
commit 4fea0d4b0afb73715abd8934263b8dd30006684f
Author: JasperJiaGuo <gu...@osu.edu>
AuthorDate: Fri Aug 2 08:58:10 2019 -0700
An auto recommendation for inverted index (#4474)
IndexTunerCommand - Tool for recommendation of inverted/sorted indexes, given a broker log and segment metadata.
CollectMetadataForIndexTuning - Tool for collecting metadata from Pinot segments required by IndexTunerCommand
---
pinot-tools/pom.xml | 4 +
.../pinot/tools/admin/PinotAdministrator.java | 5 +-
.../tools/tuner/CollectMetadataForIndexTuning.java | 97 +++++
.../tools/tuner/EntriesScannedQuantileReport.java | 89 ++++
.../pinot/tools/tuner/IndexTunerCommand.java | 199 +++++++++
.../pinot/tools/tuner/driver/TunerDriver.java | 209 ++++++++++
.../meta/manager/JsonFileMetaManagerImpl.java | 247 +++++++++++
.../tools/tuner/meta/manager/MetaManager.java | 59 +++
.../manager/collector/ColStatsAccumulatorObj.java | 156 +++++++
.../manager/collector/CompressedFilePathIter.java | 123 ++++++
.../tuner/meta/manager/collector/PathWrapper.java | 74 ++++
.../collector/SegmentMetadataCollector.java | 272 +++++++++++++
.../pinot/tools/tuner/query/src/InputIterator.java | 41 ++
.../tuner/query/src/LogInputIteratorImpl.java | 165 ++++++++
.../query/src/parser/BrokerLogParserImpl.java | 76 ++++
.../tools/tuner/query/src/parser/QueryParser.java | 37 ++
.../src/stats/wrapper/AbstractQueryStats.java | 29 ++
.../stats/wrapper/IndexSuggestQueryStatsImpl.java | 117 ++++++
.../tools/tuner/strategy/AbstractAccumulator.java | 64 +++
.../tools/tuner/strategy/FrequencyAccumulator.java | 54 +++
.../pinot/tools/tuner/strategy/FrequencyImpl.java | 200 +++++++++
.../tuner/strategy/ParseBasedAccumulator.java | 62 +++
.../tools/tuner/strategy/ParserBasedImpl.java | 453 +++++++++++++++++++++
.../strategy/QuantileAnalysisAccumulator.java | 88 ++++
.../tools/tuner/strategy/QuantileAnalysisImpl.java | 351 ++++++++++++++++
.../pinot/tools/tuner/strategy/TuningStrategy.java | 60 +++
26 files changed, 3330 insertions(+), 1 deletion(-)
diff --git a/pinot-tools/pom.xml b/pinot-tools/pom.xml
index 43b7afa..55c2ecd 100644
--- a/pinot-tools/pom.xml
+++ b/pinot-tools/pom.xml
@@ -94,6 +94,10 @@
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-math3</artifactId>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/admin/PinotAdministrator.java b/pinot-tools/src/main/java/org/apache/pinot/tools/admin/PinotAdministrator.java
index 0664ac2..24e97b8 100644
--- a/pinot-tools/src/main/java/org/apache/pinot/tools/admin/PinotAdministrator.java
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/admin/PinotAdministrator.java
@@ -50,6 +50,9 @@ import org.apache.pinot.tools.admin.command.VerifyClusterStateCommand;
import org.apache.pinot.tools.admin.command.VerifySegmentState;
import org.apache.pinot.tools.segment.converter.PinotSegmentConvertCommand;
import org.apache.pinot.tools.segment.converter.SegmentMergeCommand;
+import org.apache.pinot.tools.tuner.CollectMetadataForIndexTuning;
+import org.apache.pinot.tools.tuner.EntriesScannedQuantileReport;
+import org.apache.pinot.tools.tuner.IndexTunerCommand;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
@@ -80,7 +83,7 @@ public class PinotAdministrator {
// @formatter:off
@Argument(handler = SubCommandHandler.class, metaVar = "<subCommand>")
- @SubCommands({@SubCommand(name = "GenerateData", impl = GenerateDataCommand.class), @SubCommand(name = "CreateSegment", impl = CreateSegmentCommand.class), @SubCommand(name = "StartZookeeper", impl = StartZookeeperCommand.class), @SubCommand(name = "StartKafka", impl = StartKafkaCommand.class), @SubCommand(name = "StreamAvroIntoKafka", impl = StreamAvroIntoKafkaCommand.class), @SubCommand(name = "StartController", impl = StartControllerCommand.class), @SubCommand(name = "StartBroker", [...]
+ @SubCommands({@SubCommand(name = "GenerateData", impl = GenerateDataCommand.class), @SubCommand(name = "CreateSegment", impl = CreateSegmentCommand.class), @SubCommand(name = "StartZookeeper", impl = StartZookeeperCommand.class), @SubCommand(name = "StartKafka", impl = StartKafkaCommand.class), @SubCommand(name = "StreamAvroIntoKafka", impl = StreamAvroIntoKafkaCommand.class), @SubCommand(name = "StartController", impl = StartControllerCommand.class), @SubCommand(name = "StartBroker", [...]
Command _subCommand;
// @formatter:on
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/CollectMetadataForIndexTuning.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/CollectMetadataForIndexTuning.java
new file mode 100644
index 0000000..7dd91b8
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/CollectMetadataForIndexTuning.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.pinot.tools.tuner;
+
+import java.io.FileNotFoundException;
+import java.util.Arrays;
+import java.util.HashSet;
+import org.apache.pinot.tools.AbstractBaseCommand;
+import org.apache.pinot.tools.Command;
+import org.apache.pinot.tools.tuner.driver.TunerDriver;
+import org.apache.pinot.tools.tuner.meta.manager.collector.SegmentMetadataCollector;
+import org.apache.pinot.tools.tuner.meta.manager.collector.CompressedFilePathIter;
+import org.kohsuke.args4j.Option;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Used to collect relevant fields metadata.properties and index_map from tarred segments,
+ * And packed them into a json file
+ */
+public class CollectMetadataForIndexTuning extends AbstractBaseCommand implements Command {
+ private static final Logger LOGGER = LoggerFactory.getLogger(CollectMetadataForIndexTuning.class);
+
+ @Option(name = "-out", required = true, metaVar = "<String>", usage = "An empty directory to work on, for tmp files and output metadata.json file,must have r/w access")
+ private String _workDir;
+
+ @Option(name = "-segments", required = true, metaVar = "<String>", usage = "The directory containing /tableNamesWithoutType/{tarred segments}")
+ private String _segmentsDir;
+
+ @Option(name = "-tables", required = false, usage = "Comma separated list of table names to work on without type (unset to run on all tables)")
+ private String _tableNamesWithoutType = null;
+
+ @Option(name = "-help", required = false, help = true, aliases = {"-h", "--h",
+ "--help"}, usage = "Print this message.")
+ private boolean _help;
+
+ @Override
+ public boolean execute() throws Exception {
+ HashSet<String> tableNamesWithoutType = new HashSet<>();
+ if (_tableNamesWithoutType != null && !_tableNamesWithoutType.trim().equals("")) {
+ tableNamesWithoutType.addAll(Arrays.asList(_tableNamesWithoutType.split(",")));
+ }
+ String tableNamesWithoutTypeStr;
+ if (tableNamesWithoutType.isEmpty()) {
+ tableNamesWithoutTypeStr = "All tables";
+ } else {
+ tableNamesWithoutTypeStr = tableNamesWithoutType.toString();
+ }
+ LOGGER.info("\nTables{}\n", tableNamesWithoutTypeStr);
+
+ try {
+ TunerDriver metaFetch = new TunerDriver().setThreadPoolSize(Runtime.getRuntime().availableProcessors() - 1)
+ .setTuningStrategy(new SegmentMetadataCollector.Builder().setTableNamesWithoutType(tableNamesWithoutType)
+ .setOutputDir(_workDir)
+ .build())
+ .setInputIterator(new CompressedFilePathIter.Builder().setDirectory(_segmentsDir).build())
+ .setMetaManager(null);
+ metaFetch.execute();
+ } catch (FileNotFoundException e) {
+ LOGGER.error("Invalid tarred segments dir: {}", _segmentsDir);
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String description() {
+ return "A tool to extract and pack metadata and index info to a json file, from tarred segments.";
+ }
+
+ @Override
+ public String getName() {
+ return "CollectMetadataForIndexTuning";
+ }
+
+ @Override
+ public boolean getHelp() {
+ return _help;
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/EntriesScannedQuantileReport.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/EntriesScannedQuantileReport.java
new file mode 100644
index 0000000..28b3c17
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/EntriesScannedQuantileReport.java
@@ -0,0 +1,89 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import org.apache.pinot.tools.AbstractBaseCommand;
+import org.apache.pinot.tools.Command;
+import org.apache.pinot.tools.tuner.driver.TunerDriver;
+import org.apache.pinot.tools.tuner.query.src.LogInputIteratorImpl;
+import org.apache.pinot.tools.tuner.query.src.parser.BrokerLogParserImpl;
+import org.apache.pinot.tools.tuner.strategy.QuantileAnalysisImpl;
+import org.kohsuke.args4j.Option;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A command to scan through broker log (containing time of execution, numEntriesScannedInFilter, numEntriesScannedPostFilter) and give percentile of numEntriesScannedInFilter
+ */
+public class EntriesScannedQuantileReport extends AbstractBaseCommand implements Command {
+ private static final Logger LOGGER = LoggerFactory.getLogger(EntriesScannedQuantileReport.class);
+
+ @Option(name = "-log", required = true, metaVar = "<String>", usage = "Path to broker log file.")
+ private String _brokerLog;
+
+ @Option(name = "-tables", required = false, usage = "Comma separated list of table names to work on without type (unset run on all tables)")
+ private String _tableNamesWithoutType = null;
+
+ @Option(name = "-help", required = false, help = true, aliases = {"-h", "--h",
+ "--help"}, usage = "Print this message.")
+ private boolean _help;
+
+ @Override
+ public boolean execute() throws Exception {
+ HashSet<String> tableNamesWithoutType = new HashSet<>();
+ if (_tableNamesWithoutType != null && !_tableNamesWithoutType.trim().equals("")) {
+ tableNamesWithoutType.addAll(Arrays.asList(_tableNamesWithoutType.split(",")));
+ }
+ String tableNamesWithoutTypeStr;
+ if (tableNamesWithoutType.isEmpty()) {
+ tableNamesWithoutTypeStr = "All tables";
+ } else {
+ tableNamesWithoutTypeStr = tableNamesWithoutType.toString();
+ }
+ LOGGER.info("\nTables{}\n", tableNamesWithoutTypeStr);
+
+
+ TunerDriver fitModel = new TunerDriver().setThreadPoolSize(Runtime.getRuntime().availableProcessors() - 1)
+ .setTuningStrategy(new QuantileAnalysisImpl.Builder().setTableNamesWithoutType(tableNamesWithoutType).build())
+ .setInputIterator(new LogInputIteratorImpl.Builder()
+ .setParser(new BrokerLogParserImpl())
+ .setPath(_brokerLog)
+ .build());
+ fitModel.execute();
+ return true;
+ }
+
+ @Override
+ public String description() {
+ return "Scan through broker log (containing time of execution, numEntriesScannedInFilter, numEntriesScannedPostFilter) and give percentile of numEntriesScannedInFilter";
+ }
+
+ @Override
+ public String getName() {
+ return "EntriesScannedQuantileReport";
+ }
+
+ @Override
+ public boolean getHelp() {
+ return _help;
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/IndexTunerCommand.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/IndexTunerCommand.java
new file mode 100644
index 0000000..e891d33
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/IndexTunerCommand.java
@@ -0,0 +1,199 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import org.apache.pinot.common.utils.JsonUtils;
+import org.apache.pinot.tools.AbstractBaseCommand;
+import org.apache.pinot.tools.Command;
+import org.apache.pinot.tools.tuner.driver.TunerDriver;
+import org.apache.pinot.tools.tuner.meta.manager.JsonFileMetaManagerImpl;
+import org.apache.pinot.tools.tuner.query.src.LogInputIteratorImpl;
+import org.apache.pinot.tools.tuner.query.src.parser.BrokerLogParserImpl;
+import org.apache.pinot.tools.tuner.strategy.FrequencyImpl;
+import org.apache.pinot.tools.tuner.strategy.ParserBasedImpl;
+import org.kohsuke.args4j.Option;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A command to give indexing recommendation for inverted and sorted indices
+ */
+public class IndexTunerCommand extends AbstractBaseCommand implements Command {
+ private static final Logger LOGGER = LoggerFactory.getLogger(IndexTunerCommand.class);
+
+ private static final long DEFAULT_NUM_ENTRIES_SCANNED_THRESHOLD = 0;
+ private static final long DEFAULT_NUM_QUERIES_TO_GIVE_RECOMMENDATION = 0;
+ public static final int DEFAULT_SELECTIVITY_THRESHOLD = 1;
+
+ private static final String INVERTED_INDEX = "inverted";
+ private static final String SORTED_INDEX = "sorted";
+ private static final String STRATEGY_PARSER_BASED = "parser";
+
+ @Option(name = "-metadata", required = true, metaVar = "<String>", usage = "Path to packed metadata file (json), CollectMetadataForIndexTuning can be used to create this.")
+ private String _metadata;
+
+ @Option(name = "-log", required = true, metaVar = "<String>", usage = "Path to broker log file.")
+ private String _brokerLog;
+
+ @Option(name = "-index", required = true, metaVar = "<inverted/sorted>", usage = "Select target index.")
+ private String _indexType;
+
+ @Option(name = "-strategy", required = true, metaVar = "<freq/parser>", usage = "Select tuning strategy.")
+ private String _strategy;
+
+ @Option(name = "-selectivityThreshold", required = false, metaVar = "<long>", usage = "Selectivity threshold (>1), default to 1, ")
+ private int _selectivityThreshold = DEFAULT_SELECTIVITY_THRESHOLD;
+
+ @Option(name = "-entriesScannedThreshold", required = false, metaVar = "<long>", usage = "Log lines with numEntriesScannedInFilter below this threshold will be excluded.")
+ private long _numEntriesScannedThreshold = DEFAULT_NUM_ENTRIES_SCANNED_THRESHOLD;
+
+ @Option(name = "-numQueriesThreshold", required = false, metaVar = "<long>", usage = "Tables with log lines scanned threshold will be excluded.")
+ private long _numQueriesThreshold = DEFAULT_NUM_QUERIES_TO_GIVE_RECOMMENDATION;
+
+ @Option(name = "-tables", required = false, usage = "Comma separated list of table names to work on without type (unset run on all tables)")
+ private String _tableNamesWithoutType = null;
+
+ @Option(name = "-untrackedInvertedIndex", required = false, usage = "\"{\\\"tabelNameWithoutType1\\\": [\\\"colName1\\\",\\\"colName2\\\"]}\"")
+ private String _untrackedInvertedIndex = null;
+
+ @Option(name = "-help", required = false, help = true, aliases = {"-h", "--h", "--help"}, usage = "Print this message.")
+ private boolean _help;
+
+ @Override
+ public boolean execute() {
+ Map<String, Set<String>> untrackedInvertedIndexMap;
+ try {
+ JsonNode untrackedInvertedIndexNode = JsonUtils.stringToJsonNode(_untrackedInvertedIndex);
+ LOGGER.info(untrackedInvertedIndexNode.toString());
+ untrackedInvertedIndexMap = new HashMap<>();
+ Map<String, Set<String>> finalUntrackedInvertedIndexMap = untrackedInvertedIndexMap;
+ untrackedInvertedIndexNode.fields().forEachRemaining(tableNameToJson -> {
+ HashSet<String> colNames = new HashSet<String>();
+ tableNameToJson.getValue().elements().forEachRemaining(colNode -> {
+ colNames.add(colNode.textValue());
+ });
+ finalUntrackedInvertedIndexMap.put(tableNameToJson.getKey(), colNames);
+ });
+ } catch (Exception e) {
+ LOGGER.error("Invalid untrackedInvertedIndex: {}", _untrackedInvertedIndex);
+ untrackedInvertedIndexMap = Collections.EMPTY_MAP;
+ }
+
+ Set<String> tableNamesWithoutType = new HashSet<>();
+ if (_tableNamesWithoutType != null && !_tableNamesWithoutType.trim().equals("")) {
+ tableNamesWithoutType.addAll(Arrays.asList(_tableNamesWithoutType.split(",")));
+ }
+ String tableNamesWithoutTypeStr;
+ if (tableNamesWithoutType.isEmpty()) {
+ tableNamesWithoutTypeStr = "All tables";
+ } else {
+ tableNamesWithoutTypeStr = tableNamesWithoutType.toString();
+ }
+ if (_selectivityThreshold < 1) {
+ _selectivityThreshold = 1;
+ }
+
+ LOGGER.info(
+ "Index: {}\nstrategy: {}\nmetadata file: {}\nbroker log: {}\ntables: {}\ntrackingIndexOn: {}\nselectivityThreshold: {}\n",
+ _indexType, _strategy, _metadata, _brokerLog, tableNamesWithoutTypeStr, untrackedInvertedIndexMap,
+ _selectivityThreshold);
+
+ try {
+ if (_strategy.equals(STRATEGY_PARSER_BASED)) {
+ if (_indexType.equals(INVERTED_INDEX)) {
+ TunerDriver parserBased = new TunerDriver().setThreadPoolSize(Runtime.getRuntime().availableProcessors() - 1)
+ .setTuningStrategy(new ParserBasedImpl.Builder().setTableNamesWithoutType(tableNamesWithoutType)
+ .setNumQueriesThreshold(_numQueriesThreshold)
+ .setAlgorithmOrder(ParserBasedImpl.SECOND_ORDER)
+ .setNumEntriesScannedThreshold(_numEntriesScannedThreshold)
+ .setSelectivityThreshold(_selectivityThreshold)
+ .build())
+ .setInputIterator(
+ new LogInputIteratorImpl.Builder().setParser(new BrokerLogParserImpl()).setPath(_brokerLog).build())
+ .setMetaManager(new JsonFileMetaManagerImpl.Builder().setAdditionalMaskingCols(untrackedInvertedIndexMap)
+ .setPath(_metadata)
+ .build());
+ parserBased.execute();
+ } else if (_indexType.equals(SORTED_INDEX)) {
+ TunerDriver parserBased = new TunerDriver().setThreadPoolSize(Runtime.getRuntime().availableProcessors() - 1)
+ .setTuningStrategy(new ParserBasedImpl.Builder().setTableNamesWithoutType(tableNamesWithoutType)
+ .setNumQueriesThreshold(_numQueriesThreshold)
+ .setAlgorithmOrder(ParserBasedImpl.THIRD_ORDER)
+ .setNumEntriesScannedThreshold(_numEntriesScannedThreshold)
+ .setSelectivityThreshold(_selectivityThreshold)
+ .build())
+ .setInputIterator(
+ new LogInputIteratorImpl.Builder().setParser(new BrokerLogParserImpl()).setPath(_brokerLog).build())
+ .setMetaManager(new JsonFileMetaManagerImpl.Builder().setAdditionalMaskingCols(untrackedInvertedIndexMap)
+ .setPath(_metadata)
+ .build());
+ parserBased.execute();
+ } else {
+ return false;
+ }
+ } else {
+ if (_indexType.equals(SORTED_INDEX)) {
+ LOGGER.error("Simple frequency strategy is for inverted index only!");
+ return false;
+ }
+ TunerDriver freqBased = new TunerDriver().setThreadPoolSize(Runtime.getRuntime().availableProcessors() - 1)
+ .setTuningStrategy(new FrequencyImpl.Builder().setNumQueriesThreshold(_numQueriesThreshold)
+ .setNumEntriesScannedThreshold(_numEntriesScannedThreshold)
+ .setTableNamesWithoutType(tableNamesWithoutType)
+ .setCardinalityThreshold(_selectivityThreshold)
+ .build())
+ .setInputIterator(
+ new LogInputIteratorImpl.Builder().setParser(new BrokerLogParserImpl()).setPath(_brokerLog).build())
+ .setMetaManager(new JsonFileMetaManagerImpl.Builder().setAdditionalMaskingCols(untrackedInvertedIndexMap)
+ .setPath(_metadata)
+ .build());
+ freqBased.execute();
+ }
+ } catch (FileNotFoundException e) {
+ LOGGER.error("FileNotFoundException: ", e);
+ }
+ return true;
+ }
+
+ @Override
+ public String description() {
+ return "Give optimization boundary analysis and indexing recommendation to specific tables, based on packed segment metadata (containing the weighted sum of cardinality, number of documents, number of entries, etc.) and broker logs (containing time of execution, numEntriesScannedInFilter, numEntriesScannedPostFilter, query text).";
+ }
+
+ @Override
+ public String getName() {
+ return "IndexTunerCommand";
+ }
+
+ @Override
+ public boolean getHelp() {
+ return _help;
+ }
+}
\ No newline at end of file
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/driver/TunerDriver.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/driver/TunerDriver.java
new file mode 100644
index 0000000..cb2183b
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/driver/TunerDriver.java
@@ -0,0 +1,209 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.driver;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.apache.pinot.tools.tuner.meta.manager.JsonFileMetaManagerImpl;
+import org.apache.pinot.tools.tuner.meta.manager.MetaManager;
+import org.apache.pinot.tools.tuner.query.src.InputIterator;
+import org.apache.pinot.tools.tuner.query.src.LogInputIteratorImpl;
+import org.apache.pinot.tools.tuner.query.src.parser.QueryParser;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.apache.pinot.tools.tuner.strategy.AbstractAccumulator;
+import org.apache.pinot.tools.tuner.strategy.FrequencyImpl;
+import org.apache.pinot.tools.tuner.strategy.QuantileAnalysisImpl;
+import org.apache.pinot.tools.tuner.strategy.ParserBasedImpl;
+import org.apache.pinot.tools.tuner.strategy.TuningStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ *TunerDriver is an executable interface, has three pluggable modules:
+ * {@link MetaManager}: A manager for metadata, which is an interface to access segment metadata.
+ * {@link InputIterator}: An iterator interface over input source, has a pluggable {@link QueryParser}, who parses each item in input source, and returns {@link AbstractQueryStats}, a wrapper of relevant fields input.
+ * {@link TuningStrategy}: Strategy, which has four user defined functions operating on a map of Map<ThreadID:Long, Map<TableName:String, Map<ColumnName:String, AbstractMergerObj>>>:
+ * Filter: A function to filter AbstractQueryStats, by table name, number of entries scanned in filters, number of entries scanned post filter, etc. The relevant AbstractQueryStats will be feed to Accumulator.
+ * Accumulate: A function to process AbstractQueryStats and MetaManager; then accumulate stats to corresponding AbstractMergerObj entry.
+ * Merge: A function to merge two AbstractMergerObj entries having the same TableName/ColumnName from different threads.
+ * Report: A function to postprocess and print(email) out the final results of a table.
+ */
+public class TunerDriver {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TunerDriver.class);
+ public static final int NO_CONCURRENCY = 0;
+
+ private InputIterator _inputIterator = null;
+ private MetaManager _metaManager = null;
+ private TuningStrategy _tuningStrategy = null;
+ private int _threadPoolSize = 0;
+
+ /**
+ * Set the number of threads used in action
+ * @param threadPoolSize The number of threads used in action
+ * @return this
+ */
+ public TunerDriver setThreadPoolSize(int threadPoolSize) {
+ _threadPoolSize = threadPoolSize;
+ return this;
+ }
+
+ /**
+ * Set the query source, e.g. {@link LogInputIteratorImpl}
+ * @param inputIterator E.g. {@link LogInputIteratorImpl}
+ * @return this
+ */
+ public TunerDriver setInputIterator(InputIterator inputIterator) {
+ _inputIterator = inputIterator;
+ return this;
+ }
+
+ /**
+ * Set the metaManager for caching and query cardinality e.g. {@link JsonFileMetaManagerImpl}
+ * @param metaManager E.g. {@link JsonFileMetaManagerImpl}
+ * @return this
+ */
+ public TunerDriver setMetaManager(MetaManager metaManager) {
+ _metaManager = metaManager;
+ return this;
+ }
+
+ /**
+ * Set the strategy for the recommendation, e.g. {@link FrequencyImpl}, {@link QuantileAnalysisImpl}, {@link ParserBasedImpl}
+ * @return this
+ */
+ public TunerDriver setTuningStrategy(TuningStrategy tuningStrategy) {
+ _tuningStrategy = tuningStrategy;
+ return this;
+ }
+
+ private Map<Long, Map<String, Map<String, AbstractAccumulator>>> _threadToTableAccumulators = null;
+ private Map<String, Map<String, AbstractAccumulator>> _tableToColMergers;
+
+ /**
+ * Execute strategy
+ */
+ public void execute() {
+ // Accumulate all the query results to _threadAccumulator:/threadID/table/column/AbstractMergerObj
+ _threadToTableAccumulators = new HashMap<>();
+ LOGGER.info("Setting up executor for accumulation: {} threads", this._threadPoolSize);
+ ThreadPoolExecutor accumulateExecutor = null;
+ // setup threadpool, NO_CONCURRENCY for debugging
+ if (_threadPoolSize != NO_CONCURRENCY) {
+ accumulateExecutor = new ThreadPoolExecutor(this._threadPoolSize, this._threadPoolSize, 365, TimeUnit.DAYS,
+ new LinkedBlockingQueue<>(Integer.MAX_VALUE), new ThreadPoolExecutor.CallerRunsPolicy());
+ }
+ while (_inputIterator.hasNext()) {
+ AbstractQueryStats abstractQueryStats = _inputIterator.next();
+ if (abstractQueryStats != null && _tuningStrategy.filter(abstractQueryStats)) {
+ LOGGER.debug("Master thread {} submitting: {}", Thread.currentThread().getId(), abstractQueryStats.toString());
+ if (_threadPoolSize != NO_CONCURRENCY) {
+ accumulateExecutor.execute(() -> {
+ long threadID = Thread.currentThread().getId();
+ LOGGER.debug("Thread {} accumulating: {}", threadID, abstractQueryStats.toString());
+ _threadToTableAccumulators.putIfAbsent(threadID, new HashMap<>());
+ _tuningStrategy.accumulate(abstractQueryStats, _metaManager, _threadToTableAccumulators.get(threadID));
+ });
+ } else {
+ long threadID = Thread.currentThread().getId();
+ LOGGER.debug("Thread {} accumulating: {}", threadID, abstractQueryStats.toString());
+ _threadToTableAccumulators.putIfAbsent(threadID, new HashMap<>());
+ _tuningStrategy.accumulate(abstractQueryStats, _metaManager, _threadToTableAccumulators.get(threadID));
+ }
+ }
+ }
+ try {
+ _inputIterator.close();
+ } catch (IOException e) {
+ LOGGER.error("Error closing query src ", e);
+ }
+
+ if (_threadPoolSize != NO_CONCURRENCY) {
+ accumulateExecutor.shutdown();
+ LOGGER.info("All queries queued for accumulation");
+ try {
+ accumulateExecutor.awaitTermination(365, TimeUnit.DAYS);
+ } catch (InterruptedException e) {
+ LOGGER.error("Accumulator Interrupted!", e);
+ }
+ LOGGER.info("All accumulation done");
+ }
+
+ // Merge corresponding entries
+ LOGGER.info("Setting up mergedResults for merging");
+ _tableToColMergers = new HashMap<>();
+ _threadToTableAccumulators.forEach((threadID, perThreadTableToColAccumulators) -> {
+ perThreadTableToColAccumulators.keySet()
+ .forEach(tableNameWithoutType -> _tableToColMergers.putIfAbsent(tableNameWithoutType, new HashMap<>()));
+ });
+ LOGGER.info("tableNames: {}", _tableToColMergers.keySet().toString());
+
+ LOGGER.info("Setting up executor for merging: {} threads", this._threadPoolSize);
+ ThreadPoolExecutor mergeExecutor = null;
+ if (_threadPoolSize != NO_CONCURRENCY) {
+ mergeExecutor = new ThreadPoolExecutor(this._threadPoolSize, this._threadPoolSize, 365, TimeUnit.DAYS,
+ new LinkedBlockingQueue<>(Integer.MAX_VALUE), new ThreadPoolExecutor.CallerRunsPolicy());
+ }
+ for (String tableNameWithoutType : _tableToColMergers.keySet()) {
+ if (_threadPoolSize != NO_CONCURRENCY) {
+ mergeExecutor.execute(() -> {
+ LOGGER.debug("Thread {} working on table {}", Thread.currentThread().getId(), tableNameWithoutType);
+ _threadToTableAccumulators.forEach(
+ (threadID, perThreadTableToColAccumulators) -> perThreadTableToColAccumulators.getOrDefault(
+ tableNameWithoutType, new HashMap<>()).forEach((colName, mergerObj) -> {
+ try {
+ _tableToColMergers.get(tableNameWithoutType).putIfAbsent(colName, mergerObj.getClass().newInstance());
+ _tuningStrategy.merge(_tableToColMergers.get(tableNameWithoutType).get(colName), mergerObj);
+ } catch (Exception e) {
+ LOGGER.error("Instantiation Exception in Merger!", e);
+ }
+ }));
+ });
+ } else {
+ _threadToTableAccumulators.forEach(
+ (threadID, perThreadTableToColAccumulators) -> perThreadTableToColAccumulators.getOrDefault(
+ tableNameWithoutType, new HashMap<>()).forEach((colName, mergerObj) -> {
+ try {
+ _tableToColMergers.get(tableNameWithoutType).putIfAbsent(colName, mergerObj.getClass().newInstance());
+ _tuningStrategy.merge(_tableToColMergers.get(tableNameWithoutType).get(colName), mergerObj);
+ } catch (Exception e) {
+ LOGGER.error("Instantiation Exception in Merger!", e);
+ }
+ }));
+ }
+ }
+ if (_threadPoolSize != NO_CONCURRENCY) {
+ LOGGER.info("All tables waiting for merge");
+ mergeExecutor.shutdown();
+ try {
+ mergeExecutor.awaitTermination(365, TimeUnit.DAYS);
+ } catch (InterruptedException e) {
+ LOGGER.error("Interruption of merger", e);
+ }
+ LOGGER.info("All merge done");
+ }
+
+ //Report
+ _tuningStrategy.report(_tableToColMergers);
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/JsonFileMetaManagerImpl.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/JsonFileMetaManagerImpl.java
new file mode 100644
index 0000000..3c63449
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/JsonFileMetaManagerImpl.java
@@ -0,0 +1,247 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.meta.manager;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+import javax.annotation.Nonnull;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.math.fraction.BigFraction;
+import org.apache.pinot.common.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The implementation of {@link MetaManager} to read formatted data from Json file
+ */
+public class JsonFileMetaManagerImpl implements MetaManager {
+ private static final Logger LOGGER = LoggerFactory.getLogger(JsonFileMetaManagerImpl.class);
+
+ public static final Boolean IGNORE_EXISTING_INDEX = false;
+ public static final Boolean USE_EXISTING_INDEX = true;
+ public static final Boolean DONT_USE_EXISTING_INDEX = false;
+
+ /*Meta data type:
+ *COL_META: Aggregated (sum and weighted sum of metadata)
+ *SEGMENT_META: Individually stored metadata of each segment
+ */
+ private static final String COL_META = "col_meta";
+ private static final String SEGMENT_META = "segment_meta";
+ private static final String TYPE_REALTIME = "_REALTIME";
+ private static final String TYPE_OFFLINE = "_OFFLINE";
+ private static final String TYPE_HYBRID = "_HYBRID";
+ private static final String TYPE_REGEX = "(_REALTIME|_OFFLINE|_HYBRID)";
+ private String _path;
+ private Boolean _useExistingIndex;
+ private Map<String, Set<String>> _additionalMaskingCols;
+
+ private JsonNode _aggregatedMap = null;
+ private JsonNode _segmentMap = null;
+
+ private JsonFileMetaManagerImpl(Builder builder) {
+ _path = builder._path;
+ _useExistingIndex = builder._useExistingIndex;
+ _additionalMaskingCols = builder._additionalMaskingCols;
+ }
+
+ public static final class Builder {
+ private String _path;
+ private Boolean _useExistingIndex = USE_EXISTING_INDEX;
+ private Map<String, Set<String>> _additionalMaskingCols = new HashMap<>();
+
+ public Builder() {
+ }
+
+ /**
+ *
+ * @param val The path to the json file storing the segment metadata
+ * @return this
+ */
+ @Nonnull
+ public Builder setPath(@Nonnull String val) {
+ _path = val;
+ return this;
+ }
+
+ /**
+ *
+ * @param val If this is set the already applied index will not be considered again
+ * @return this
+ */
+ @Nonnull
+ public Builder setUseExistingIndex(@Nonnull Boolean val) {
+ _useExistingIndex = val;
+ return this;
+ }
+
+ /**
+ *
+ * @param val For research and debug purpose only, the cardinality of /tableName/colName passed in will be considered as 1
+ * @return this
+ */
+ @Nonnull
+ public Builder setAdditionalMaskingCols(@Nonnull Map<String, Set<String>> val) {
+ _additionalMaskingCols = val;
+ return this;
+ }
+
+ @Nonnull
+ public JsonFileMetaManagerImpl build() throws FileNotFoundException {
+ return new JsonFileMetaManagerImpl(this).fetch();
+ }
+ }
+
+ /**
+ * fetch the metadata from file
+ * @return this
+ */
+ public JsonFileMetaManagerImpl fetch() throws FileNotFoundException {
+ File file = new File(this._path);
+ String metaBytes = "";
+ try {
+ metaBytes = FileUtils.readFileToString(file);
+ } catch (IOException e) {
+ LOGGER.error("Can't read json file! ", e);
+ throw new FileNotFoundException();
+ }
+ try {
+ JsonNode jnode = JsonUtils.stringToJsonNode(metaBytes);
+ _aggregatedMap = jnode.get(COL_META);
+ _segmentMap = jnode.get(SEGMENT_META);
+ } catch (IOException e) {
+ LOGGER.error("Can not parse Json file!");
+ throw new FileNotFoundException();
+ }
+ return this;
+ }
+
+ /**
+ * If there is already inverted index on a column
+ */
+ public boolean hasInvertedIndex(String tableNameWithoutType, String columnName) {
+ if (_additionalMaskingCols.getOrDefault(tableNameWithoutType, new HashSet<>()).contains(columnName)) {
+ return true;
+ }
+ if (_useExistingIndex) {
+ String _numHasInv = getColField(tableNameWithoutType, columnName, SUM_SEGMENTS_HAS_INVERTED_INDEX);
+ return _numHasInv != null && Integer.parseInt(_numHasInv) > 0;
+ }
+ return false;
+ }
+
+ public BigFraction getAverageNumEntriesPerDoc(String tableNameWithoutType, String columnName) {
+ try {
+ BigInteger entriesNumerator = new BigInteger(getColField(tableNameWithoutType, columnName, SUM_TOTAL_ENTRIES));
+ BigInteger entriesDenominator = new BigInteger(getColField(tableNameWithoutType, columnName, SUM_DOCS));
+ if (entriesNumerator.compareTo(entriesDenominator) < 0 || entriesDenominator.equals(BigInteger.ZERO)) {
+ throw new Exception("Invalid state: SUM_DOCS < SUM_TOTAL_ENTRIES or SUM_DOCS is 0!");
+ }
+ return new BigFraction(entriesNumerator, entriesDenominator);
+ } catch (Exception e) {
+ LOGGER.trace("Set average entries to 1 {} {}", tableNameWithoutType, columnName);
+ return BigFraction.ONE;
+ }
+ }
+
+ /**
+ * Get the Sum_across_segments(cardinality*totalDocs)/Sum_across_segments(totalDocs), i.e. the weighted average cardinality
+ * At the same time, fix this value by numSegmentsNotSorted/numSegments
+ */
+ public BigFraction getColumnSelectivity(String tableNameWithoutType, String columnName) {
+ LOGGER.debug("Getting cardinality from: {} {}", tableNameWithoutType, columnName);
+
+ if (_additionalMaskingCols.getOrDefault(tableNameWithoutType, new HashSet<>()).contains(columnName)) {
+ return BigFraction.ONE;
+ }
+ if (_useExistingIndex) {
+ if (hasInvertedIndex(tableNameWithoutType, columnName)) {
+ return BigFraction.ONE;
+ }
+ }
+
+ String nSortedNumerator = getColField(tableNameWithoutType, columnName, SUM_SEGMENTS_SORTED);
+ String nSortedDenominator = getColField(tableNameWithoutType, columnName, SUM_SEGMENTS_COUNT);
+ String cardNumerator = getColField(tableNameWithoutType, columnName, WEIGHTED_SUM_CARDINALITY);
+ String cardDenominator = getColField(tableNameWithoutType, columnName, SUM_DOCS);
+
+ LOGGER.debug("Cardinality table:{} column:{} card: {}/{}, sort: {}/{}", tableNameWithoutType, columnName,
+ cardNumerator, cardDenominator, nSortedNumerator, nSortedDenominator);
+
+ if (cardNumerator == null || cardDenominator == null) {
+ LOGGER.error("{} {}'s cardinality does not exist!", tableNameWithoutType, columnName);
+ return BigFraction.ONE;
+ }
+
+ BigFraction sorted_ratio;
+ if (nSortedNumerator == null || nSortedDenominator == null) {
+ LOGGER.error("{} {}'s sort info does not exist!", tableNameWithoutType, columnName);
+ sorted_ratio = BigFraction.ZERO;
+ } else if (nSortedNumerator.equals(nSortedDenominator)) {
+ return BigFraction.ONE;
+ } else {
+ sorted_ratio = new BigFraction(new BigInteger(nSortedNumerator), new BigInteger(nSortedDenominator));
+ }
+
+ sorted_ratio = BigFraction.ONE.subtract(sorted_ratio);
+ BigFraction averageCard = new BigFraction(new BigInteger(cardNumerator), new BigInteger(cardDenominator));
+
+ return averageCard.multiply(sorted_ratio);
+ }
+
+ public String getSegmentField(String tableNameWithoutType, String columnName, String segmentName, String fieldName) {
+ tableNameWithoutType = Pattern.compile(TYPE_REGEX).matcher(tableNameWithoutType).replaceFirst("");
+ JsonNode ret;
+ try {
+ ret = _segmentMap.get(tableNameWithoutType).get(columnName).get(segmentName).get(fieldName);
+ if (ret == null) {
+ throw new NullPointerException();
+ }
+ } catch (NullPointerException e) {
+ LOGGER.debug("tableNameWithoutType:{} columnName:{} segmentName:{} field:{} Does not exist!",
+ tableNameWithoutType, columnName, segmentName, fieldName);
+ return null;
+ }
+ return ret.asText();
+ }
+
+ public String getColField(String tableNameWithoutType, String columnName, String fieldName) {
+ tableNameWithoutType = Pattern.compile(TYPE_REGEX).matcher(tableNameWithoutType).replaceFirst("");
+ JsonNode ret;
+ try {
+ ret = _aggregatedMap.get(tableNameWithoutType).get(columnName).get(fieldName);
+ if (ret == null) {
+ throw new NullPointerException();
+ }
+ } catch (NullPointerException e) {
+ LOGGER.debug("tableNameWithoutType:{} columnName:{} fieldName:{} Does not exist!", tableNameWithoutType,
+ columnName, fieldName);
+ return null;
+ }
+ return ret.asText();
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/MetaManager.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/MetaManager.java
new file mode 100644
index 0000000..c300f4b
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/MetaManager.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.meta.manager;
+
+import org.apache.commons.math.fraction.BigFraction;
+
+
+/**
+ * Load and access fields of metadata.properties
+ */
+public interface MetaManager {
+ String WEIGHTED_SUM_CARDINALITY = "w_cardinality";
+ String SUM_DOCS = "n_totalDocs";
+ String SUM_SEGMENTS_HAS_INVERTED_INDEX = "n_hasInvertedIndex";
+ String SUM_SEGMENTS_SORTED = "n_isSorted";
+ String SUM_SEGMENTS_COUNT = "n_segmentCount";
+ String SUM_TOTAL_ENTRIES = "n_totalNumberOfEntries";
+
+ /**
+ * Get aggregated (sum and weighted sum) of metadata
+ * @param fieldName one of {WEIGHTED_SUM_CARDINALITY, SUM_DOCS, NUM_SEGMENTS_HAS_INVERTED_INDEX, NUM_SEGMENTS_SORTED, NUM_SEGMENTS_COUNT}
+ */
+ String getColField(String tableNameWithoutType, String columnName, String fieldName);
+
+ /**
+ * Getter to certain fields for a specific column, for forward compatibility precise inverted index prediction.
+ */
+ String getSegmentField(String tableNameWithoutType, String columnName, String segmentName,
+ String fieldName); //get metadata of individual segment
+
+ /**
+ * Get the selectivity calculated by weighted average of cardinality.
+ * @return Selectivity, a BigFraction.
+ */
+ BigFraction getColumnSelectivity(String tableNameWithoutType, String columnName);
+
+ /**
+ * Get the average num of entries per doc.
+ */
+ BigFraction getAverageNumEntriesPerDoc(String tableNameWithoutType, String columnName);
+
+ boolean hasInvertedIndex(String tableNameWithoutType, String columnName);
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/ColStatsAccumulatorObj.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/ColStatsAccumulatorObj.java
new file mode 100644
index 0000000..7c3f04d
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/ColStatsAccumulatorObj.java
@@ -0,0 +1,156 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.meta.manager.collector;
+
+import java.math.BigInteger;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.pinot.tools.tuner.meta.manager.MetaManager;
+import org.apache.pinot.tools.tuner.strategy.AbstractAccumulator;
+
+
+/**
+ * Accumulator for relevant fields in metadata.properties and index_map
+ */
+public class ColStatsAccumulatorObj extends AbstractAccumulator {
+
+ private Map<String, BigInteger> _accumulatedStats = new HashMap<>();
+ private Map<String, Map<String, String>> _segmentStats = new HashMap<>();
+
+ private static final String CARDINALITY = "cardinality";
+ private static final String TOTAL_DOCS = "totalDocs";
+ private static final String TOTAL_NUMBER_OF_ENTRIES = "totalNumberOfEntries";
+ private static final String IS_SORTED = "isSorted";
+ private static final String INVERTED_INDEX_SIZE = "invertedIndexSize";
+
+ @Override
+ public String toString() {
+ return "ColStatsAccumulatorObj{" + "accumulatedStats=" + _accumulatedStats + ", segmentStats=" + _segmentStats
+ + '}';
+ }
+
+ private String _segmentName;
+ private String _cardinality;
+ private String _totalDocs;
+ private String _totalNumberOfEntries;
+ private String _isSorted;
+ private String _invertedIndexSize;
+
+ Map<String, BigInteger> getAccumulatedStats() {
+ return _accumulatedStats;
+ }
+
+ Map<String, Map<String, String>> getSegmentStats() {
+ return _segmentStats;
+ }
+
+ ColStatsAccumulatorObj setInvertedIndexSize(String invertedIndexSize) {
+ _invertedIndexSize = invertedIndexSize;
+ return this;
+ }
+
+ ColStatsAccumulatorObj setSegmentName(String segmentName) {
+ _segmentName = segmentName;
+ return this;
+ }
+
+ ColStatsAccumulatorObj setCardinality(String cardinality) {
+ _cardinality = cardinality;
+ return this;
+ }
+
+ ColStatsAccumulatorObj setTotalDocs(String totalDocs) {
+ _totalDocs = totalDocs;
+ return this;
+ }
+
+ ColStatsAccumulatorObj setTotalNumberOfEntries(String totalNumberOfEntries) {
+ _totalNumberOfEntries = totalNumberOfEntries;
+ return this;
+ }
+
+ ColStatsAccumulatorObj setIsSorted(String isSorted) {
+ _isSorted = isSorted;
+ return this;
+ }
+
+ /**
+ * Merge the fields of a particular segment, set by set*
+ */
+ public void merge() {
+ _accumulatedStats.put(MetaManager.WEIGHTED_SUM_CARDINALITY,
+ _accumulatedStats.getOrDefault(MetaManager.WEIGHTED_SUM_CARDINALITY, BigInteger.ZERO).add(new BigInteger(_cardinality).multiply(new BigInteger(_totalDocs))));
+
+ _accumulatedStats.put(MetaManager.SUM_SEGMENTS_COUNT,
+ _accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_COUNT, BigInteger.ZERO).add(BigInteger.ONE));
+
+ _accumulatedStats.put(MetaManager.SUM_SEGMENTS_HAS_INVERTED_INDEX,
+ _accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_HAS_INVERTED_INDEX, BigInteger.ZERO).add(Integer.parseInt(_invertedIndexSize) > 0 ? BigInteger.ONE : BigInteger.ZERO));
+
+ _accumulatedStats.put(MetaManager.SUM_SEGMENTS_SORTED,
+ _accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_SORTED, BigInteger.ZERO).add(_isSorted.trim().toLowerCase().equals("true") ? BigInteger.ONE : BigInteger.ZERO));
+
+ _accumulatedStats.put(MetaManager.SUM_TOTAL_ENTRIES,
+ _accumulatedStats.getOrDefault(MetaManager.SUM_TOTAL_ENTRIES, BigInteger.ZERO).add(new BigInteger(_totalNumberOfEntries)));
+
+ _accumulatedStats.put(MetaManager.SUM_DOCS,
+ _accumulatedStats.getOrDefault(MetaManager.SUM_DOCS, BigInteger.ZERO).add(new BigInteger(_totalDocs)));
+
+ HashMap<String, String> segmentMeta = new HashMap<>();
+ segmentMeta.put(CARDINALITY, _cardinality);
+ segmentMeta.put(TOTAL_DOCS, _totalDocs);
+ segmentMeta.put(TOTAL_NUMBER_OF_ENTRIES, _totalNumberOfEntries);
+ segmentMeta.put(IS_SORTED, _isSorted);
+ segmentMeta.put(INVERTED_INDEX_SIZE, _invertedIndexSize);
+ _segmentStats.put(_segmentName, segmentMeta);
+ }
+
+ public void merge(ColStatsAccumulatorObj colStatsAccumulatorObj) {
+ _accumulatedStats.put(MetaManager.WEIGHTED_SUM_CARDINALITY,
+ this._accumulatedStats.getOrDefault(MetaManager.WEIGHTED_SUM_CARDINALITY, BigInteger.ZERO)
+ .add(colStatsAccumulatorObj._accumulatedStats.getOrDefault(MetaManager.WEIGHTED_SUM_CARDINALITY,
+ BigInteger.ZERO)));
+
+ _accumulatedStats.put(MetaManager.SUM_SEGMENTS_COUNT,
+ this._accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_COUNT, BigInteger.ZERO)
+ .add(colStatsAccumulatorObj._accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_COUNT,
+ BigInteger.ZERO)));
+
+ _accumulatedStats.put(MetaManager.SUM_SEGMENTS_HAS_INVERTED_INDEX,
+ this._accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_HAS_INVERTED_INDEX, BigInteger.ZERO)
+ .add(colStatsAccumulatorObj._accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_HAS_INVERTED_INDEX,
+ BigInteger.ZERO)));
+
+ _accumulatedStats.put(MetaManager.SUM_SEGMENTS_SORTED,
+ this._accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_SORTED, BigInteger.ZERO)
+ .add(colStatsAccumulatorObj._accumulatedStats.getOrDefault(MetaManager.SUM_SEGMENTS_SORTED,
+ BigInteger.ZERO)));
+
+ _accumulatedStats.put(MetaManager.SUM_TOTAL_ENTRIES,
+ this._accumulatedStats.getOrDefault(MetaManager.SUM_TOTAL_ENTRIES, BigInteger.ZERO)
+ .add(
+ colStatsAccumulatorObj._accumulatedStats.getOrDefault(MetaManager.SUM_TOTAL_ENTRIES, BigInteger.ZERO)));
+
+ _accumulatedStats.put(MetaManager.SUM_DOCS,
+ this._accumulatedStats.getOrDefault(MetaManager.SUM_DOCS, BigInteger.ZERO)
+ .add(colStatsAccumulatorObj._accumulatedStats.getOrDefault(MetaManager.SUM_DOCS, BigInteger.ZERO)));
+
+ this._segmentStats.putAll(colStatsAccumulatorObj._segmentStats);
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/CompressedFilePathIter.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/CompressedFilePathIter.java
new file mode 100644
index 0000000..3af77c9
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/CompressedFilePathIter.java
@@ -0,0 +1,123 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.meta.manager.collector;
+
+import io.vavr.Tuple2;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import javax.annotation.Nonnull;
+import org.apache.pinot.tools.tuner.query.src.InputIterator;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The iterator over all tarred segments in _directory/tableName/
+ */
+public class CompressedFilePathIter implements InputIterator {
+ private static final Logger LOGGER = LoggerFactory.getLogger(CompressedFilePathIter.class);
+ private Iterator<Tuple2<String, File>> _iterator;
+
+ private String _segmentTarDir;
+
+ private CompressedFilePathIter(Builder builder) {
+ _segmentTarDir = builder._directory;
+ }
+
+ private CompressedFilePathIter openDirectory() throws FileNotFoundException {
+ File dir = new File(_segmentTarDir);
+ if (!dir.exists() || dir.isFile()) {
+ LOGGER.error("Wrong input directory!");
+ throw new FileNotFoundException();
+ }
+
+ ArrayList<Tuple2<String, File>> validTableNameWithoutTypeSegmentFile = new ArrayList<>();
+
+ Arrays.stream(Objects.requireNonNull(dir.listFiles()))
+ .filter(tableDir -> (tableDir.isDirectory() && !tableDir.getName().startsWith(".") && !tableDir.getName()
+ .equals("Deleted_Segments")))
+ .forEach(tableDir -> Arrays.stream(Objects.requireNonNull(tableDir.listFiles()))
+ .filter(file -> (file.isFile() && !file.getName().startsWith(".")))
+ .forEach(file -> validTableNameWithoutTypeSegmentFile.add(new Tuple2<>(tableDir.getName(), file))));
+
+ _iterator = validTableNameWithoutTypeSegmentFile.iterator();
+ return this;
+ }
+
+ /**
+ *
+ * @return If the input has next path
+ */
+ @Override
+ public boolean hasNext() {
+ return _iterator.hasNext();
+ }
+
+ /**
+ *
+ * @return The next path from directory
+ */
+ @Override
+ public AbstractQueryStats next() throws NoSuchElementException {
+ Tuple2<String, File> nextTuple = _iterator.next();
+ return new PathWrapper.Builder().setTableNameWithoutType(nextTuple._1()).setFile(nextTuple._2()).build();
+ }
+
+ /**
+ * Closes this stream and releases any system resources associated
+ * with it. If the stream is already closed then invoking this
+ * method has no effect.
+ *
+ * <p> As noted in {@link AutoCloseable#close()}, cases where the
+ * close may fail require careful attention. It is strongly advised
+ * to relinquish the underlying resources and to internally
+ * <em>mark</em> the {@code Closeable} as closed, prior to throwing
+ * the {@code IOException}.
+ *
+ * @throws IOException if an I/O error occurs
+ */
+ @Override
+ public void close() throws IOException {
+ }
+
+ public static final class Builder {
+ private String _directory;
+
+ public Builder() {
+ }
+
+ @Nonnull
+ public Builder setDirectory(@Nonnull String val) {
+ _directory = val;
+ return this;
+ }
+
+ @Nonnull
+ public CompressedFilePathIter build() throws FileNotFoundException {
+ return new CompressedFilePathIter(this).openDirectory();
+ }
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/PathWrapper.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/PathWrapper.java
new file mode 100644
index 0000000..0899e48
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/PathWrapper.java
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.meta.manager.collector;
+
+import java.io.File;
+import javax.annotation.Nonnull;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+
+
+/**
+ * The path wrapper used to feed the tarred segment path to the worker threads
+ */
+public class PathWrapper extends AbstractQueryStats {
+ private File _file;
+
+ @Override
+ public String toString() {
+ return "PathWrapper{" + "_path='" + _file + '\'' + ", _tableNameWithoutType='" + _tableNameWithoutType + '\'' + '}';
+ }
+
+ public File getFile() {
+ return _file;
+ }
+
+ public String getTableNameWithoutType() {
+ return _tableNameWithoutType;
+ }
+
+ private PathWrapper(Builder builder) {
+ _tableNameWithoutType = builder._tableNameWithoutType;
+ _file = builder._file;
+ }
+
+ public static final class Builder {
+ private String _tableNameWithoutType;
+ private File _file;
+
+ public Builder() {
+ }
+
+ @Nonnull
+ public Builder setTableNameWithoutType(@Nonnull String val) {
+ _tableNameWithoutType = val;
+ return this;
+ }
+
+ @Nonnull
+ public Builder setFile(@Nonnull File val) {
+ _file = val;
+ return this;
+ }
+
+ @Nonnull
+ public PathWrapper build() {
+ return new PathWrapper(this);
+ }
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/SegmentMetadataCollector.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/SegmentMetadataCollector.java
new file mode 100644
index 0000000..daa726e
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/meta/manager/collector/SegmentMetadataCollector.java
@@ -0,0 +1,272 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.meta.manager.collector;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.io.File;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.annotation.Nonnull;
+import org.apache.commons.io.FileUtils;
+import org.apache.pinot.common.utils.JsonUtils;
+import org.apache.pinot.tools.tuner.meta.manager.MetaManager;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.apache.pinot.tools.tuner.strategy.AbstractAccumulator;
+import org.apache.pinot.tools.tuner.strategy.TuningStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Extract relevant fields in metadata.properties and index_map from tarred segments in controller
+ * And pack them into a json file
+ */
+public class SegmentMetadataCollector implements TuningStrategy {
+ private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMetadataCollector.class);
+ private static final String UNTAR = "tar -xf ";
+ private static final String TMP_THREAD_FILE_PREFIX = "/tmpThreadFile";
+ private static final String EXCLUDE_DATA = " --exclude columns.psf ";
+ private static final String STRIP_PATHS = " --xform s#^.+/##x ";
+ private static final String OUT_PUT_PATH = " -C ";
+ private static final String RM_RF = "rm -rf ";
+
+ private static final int REGEX_FIRST_GROUP = 1;
+ private static final String REGEX_COL_EXTRACT = "column\\.(.*)\\.columnType = (DIMENSION|TIME)";
+ private static final String REGEX_COLUMN = "column\\.";
+ private static final String REGEX_CARDINALITY = "\\.cardinality = (.*)";
+ private static final String REGEX_TOTAL_DOCS = "\\.totalDocs = (.*)";
+ private static final String REGEX_IS_SORTED = "\\.isSorted = (.*)";
+ private static final String REGEX_TOTAL_NUMBER_OF_ENTRIES = "\\.totalNumberOfEntries = (.*)";
+ private static final String REGEX_INVERTED_INDEX_SIZE = "\\.inverted_index\\.size = (.*)";
+
+ private HashSet<String> _tableNamesWithoutType;
+ private File _outputDir;
+
+ public SegmentMetadataCollector(Builder builder) {
+ _tableNamesWithoutType = builder._tableNamesWithoutType;
+
+ if (builder._outputDir == null) {
+ LOGGER.error("No output path specified!");
+ return;
+ }
+ _outputDir = new File(builder._outputDir);
+ if (!_outputDir.exists() || _outputDir.isFile() || !_outputDir.canRead() || !_outputDir.canWrite()) {
+ LOGGER.error("Error in output path specified!");
+ return;
+ }
+ }
+
+ /**
+ * Filter out irrelevant tables' segments.
+ * @param filePaths the (tableNamesWithoutType,segmentPaths) extracted and parsed from directory
+ */
+ @Override
+ public boolean filter(AbstractQueryStats filePaths) {
+ return _tableNamesWithoutType == null || _tableNamesWithoutType.isEmpty() || _tableNamesWithoutType.contains(((PathWrapper) filePaths).getTableNameWithoutType());
+ }
+
+ /**
+ * Accumulate the parsed metadata.properties and index_map to corresponding entry
+ * @param filePaths input, {@link PathWrapper}
+ * @param metaManager null,
+ * @param AccumulatorOut output, map of /tableMame: String/columnName: String/{@link AbstractAccumulator}
+ */
+ @Override
+ public void accumulate(AbstractQueryStats filePaths, MetaManager metaManager, Map<String, Map<String, AbstractAccumulator>> AccumulatorOut) {
+ PathWrapper pathWrapper = ((PathWrapper) filePaths);
+
+ File tmpFolder = new File(
+ _outputDir.getAbsolutePath() + TMP_THREAD_FILE_PREFIX + Thread.currentThread().getId() + "_" + (System.currentTimeMillis() % 1000000));
+ LOGGER.info("Extracting: " + pathWrapper.getFile().getAbsolutePath() + " to " + tmpFolder.getAbsolutePath());
+
+ try {
+ try {
+ tmpFolder.mkdirs();
+ Process p = Runtime.getRuntime()
+ .exec(
+ (UNTAR + pathWrapper.getFile().getAbsolutePath() + EXCLUDE_DATA + STRIP_PATHS + OUT_PUT_PATH + tmpFolder
+ .getAbsolutePath()));
+ p.waitFor();
+ } catch (IOException | InterruptedException e) {
+ LOGGER.error("Error while extracting {}", pathWrapper.getFile().getAbsolutePath());
+ return;
+ }
+
+ File metaDataProperties;
+ File indexMap;
+ try {
+ metaDataProperties = tmpFolder.listFiles((dir, name) -> name.equals("metadata.properties"))[0];
+ if (!metaDataProperties.exists()) {
+ throw new NullPointerException();
+ }
+ } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
+ LOGGER.error("No metadata.properties file for {}!", pathWrapper.getFile().getAbsolutePath());
+ return;
+ }
+
+ try {
+ indexMap = tmpFolder.listFiles((dir, name) -> name.equals("index_map"))[0];
+ if (!indexMap.exists()) {
+ throw new NullPointerException();
+ }
+ } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
+ LOGGER.error("No index_map file for {}!", pathWrapper.getFile().getAbsolutePath());
+ indexMap = null;
+ }
+
+ String metadataString = "";
+ try {
+ metadataString = FileUtils.readFileToString(metaDataProperties);
+ } catch (IOException | NullPointerException e) {
+ LOGGER.error("No metadata.properties for {}!", pathWrapper.getFile().getAbsolutePath());
+ return;
+ }
+
+ String indexMapString = "";
+ try {
+ indexMapString = FileUtils.readFileToString(indexMap);
+ } catch (IOException | NullPointerException e) {
+ LOGGER.error("No index_map for {}!", pathWrapper.getFile().getAbsolutePath());
+ indexMapString = "";
+ }
+
+ Matcher colMatcher = Pattern.compile(REGEX_COL_EXTRACT).matcher(metadataString);
+ while (colMatcher.find()) {
+ String colName = colMatcher.group(REGEX_FIRST_GROUP);
+ AccumulatorOut.putIfAbsent(pathWrapper.getTableNameWithoutType(), new HashMap<>());
+ AccumulatorOut.get(pathWrapper.getTableNameWithoutType()).putIfAbsent(colName, new ColStatsAccumulatorObj());
+
+ Matcher cardinalityMatcher =
+ Pattern.compile(REGEX_COLUMN + colName + REGEX_CARDINALITY).matcher(metadataString);
+ String cardinality = cardinalityMatcher.find() ? cardinalityMatcher.group(REGEX_FIRST_GROUP) : "1";
+
+ Matcher totalDocsMatcher = Pattern.compile(REGEX_COLUMN + colName + REGEX_TOTAL_DOCS).matcher(metadataString);
+ String totalDocs = totalDocsMatcher.find() ? totalDocsMatcher.group(REGEX_FIRST_GROUP) : "0";
+
+ Matcher isSortedMatcher = Pattern.compile(REGEX_COLUMN + colName + REGEX_IS_SORTED).matcher(metadataString);
+ String isSorted = isSortedMatcher.find() ? isSortedMatcher.group(REGEX_FIRST_GROUP) : "false";
+
+ Matcher totalNumberOfEntriesMatcher =
+ Pattern.compile(REGEX_COLUMN + colName + REGEX_TOTAL_NUMBER_OF_ENTRIES).matcher(metadataString);
+ String totalNumberOfEntries =
+ totalNumberOfEntriesMatcher.find() ? totalNumberOfEntriesMatcher.group(REGEX_FIRST_GROUP) : "0";
+
+ Matcher invertedIndexSizeMatcher = Pattern.compile(colName + REGEX_INVERTED_INDEX_SIZE).matcher(indexMapString);
+ String invertedIndexSize =
+ invertedIndexSizeMatcher.find() ? invertedIndexSizeMatcher.group(REGEX_FIRST_GROUP) : "0";
+
+ ((ColStatsAccumulatorObj) AccumulatorOut.get(pathWrapper.getTableNameWithoutType())
+ .get(colName)).setCardinality(cardinality)
+ .setInvertedIndexSize(invertedIndexSize)
+ .setIsSorted(isSorted)
+ .setSegmentName(pathWrapper.getFile().getName())
+ .setTotalDocs(totalDocs)
+ .setTotalNumberOfEntries(totalNumberOfEntries)
+ .merge();
+ }
+ } finally {
+ deleteTmp(tmpFolder);
+ }
+ }
+
+ private void deleteTmp(File tmpFolder) {
+ try {
+ FileUtils.deleteDirectory(tmpFolder);
+ } catch (IOException e) {
+ LOGGER.error(e.getMessage());
+ }
+ }
+
+ /**
+ * merge two {@link ColStatsAccumulatorObj} with same /tableName/colName
+ * @param abstractAccumulator input
+ * @param abstractAccumulatorToMerge input
+ */
+ @Override
+ public void merge(AbstractAccumulator abstractAccumulator, AbstractAccumulator abstractAccumulatorToMerge) {
+ ((ColStatsAccumulatorObj) abstractAccumulator).merge((ColStatsAccumulatorObj) abstractAccumulatorToMerge);
+ }
+
+ /**
+ * Generate a json packing all metadata properties.
+ * @param tableResults input
+ */
+ @Override
+ public void report(Map<String, Map<String, AbstractAccumulator>> tableResults) {
+ Map<String, Map> packedFile = new HashMap<>();
+ Map<String, Map<String, Map<String, BigInteger>>> colMeta = new HashMap<>();
+ Map<String, Map<String, Map<String, Map<String, String>>>> segmentMeta = new HashMap<>();
+
+ tableResults.forEach((tableNameNoType, colMap) -> colMap.forEach((colName, obj) -> {
+ colMeta.putIfAbsent(tableNameNoType, new HashMap<>());
+ colMeta.get(tableNameNoType).put(colName, ((ColStatsAccumulatorObj) obj).getAccumulatedStats());
+
+ segmentMeta.putIfAbsent(tableNameNoType, new HashMap<>());
+ segmentMeta.get(tableNameNoType).put(colName, ((ColStatsAccumulatorObj) obj).getSegmentStats());
+ }));
+
+ packedFile.put("col_meta", colMeta);
+ packedFile.put("segment_meta", segmentMeta);
+
+ String json = null;
+ try {
+ json = JsonUtils.objectToString(packedFile);
+ } catch (JsonProcessingException e) {
+ LOGGER.error("Cannot convert to json!");
+ }
+
+ File file = new File(_outputDir.getAbsolutePath() + "/metadata.json");
+ try {
+ file.createNewFile();
+ FileUtils.writeStringToFile(file, json);
+ } catch (IOException e) {
+ LOGGER.error("Error writing to the json file: {}", file.getAbsolutePath());
+ }
+ }
+
+ public static final class Builder {
+ private HashSet<String> _tableNamesWithoutType = new HashSet<>();
+ private String _outputDir = null;
+
+ public Builder() {
+ }
+
+ @Nonnull
+ public Builder setTableNamesWithoutType(@Nonnull HashSet<String> val) {
+ _tableNamesWithoutType = val;
+ return this;
+ }
+
+ @Nonnull
+ public Builder setOutputDir(@Nonnull String val) {
+ _outputDir = val;
+ return this;
+ }
+
+ @Nonnull
+ public SegmentMetadataCollector build() {
+ return new SegmentMetadataCollector(this);
+ }
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/InputIterator.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/InputIterator.java
new file mode 100644
index 0000000..f4dcfbd
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/InputIterator.java
@@ -0,0 +1,41 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.query.src;
+
+import java.io.Closeable;
+import java.util.NoSuchElementException;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+
+
+/**
+ * Iterator interface for query text & related stats
+ */
+public interface InputIterator extends Closeable {
+ /**
+ *
+ * @return If the input has next stats obj
+ */
+ boolean hasNext();
+
+ /**
+ *
+ * @return The next obj parsed from input
+ */
+ AbstractQueryStats next() throws NoSuchElementException;
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/LogInputIteratorImpl.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/LogInputIteratorImpl.java
new file mode 100644
index 0000000..2d9637d
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/LogInputIteratorImpl.java
@@ -0,0 +1,165 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.query.src;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.NoSuchElementException;
+import java.util.regex.Pattern;
+import javax.annotation.Nonnull;
+import org.apache.pinot.tools.tuner.query.src.parser.BrokerLogParserImpl;
+import org.apache.pinot.tools.tuner.query.src.parser.QueryParser;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Generic class to iterate over lines in file
+ */
+public class LogInputIteratorImpl implements InputIterator {
+ private static final Logger LOGGER = LoggerFactory.getLogger(LogInputIteratorImpl.class);
+
+ public static final String REGEX_VALID_LINE_STANDALONE = "^(Processed requestId|RequestId).*$";
+ public static final String REGEX_VALID_LINE_TIME = "^(\\d{4})/(\\d{2})/(\\d{2}) [\\d:.].*$";
+
+ private FileInputStream _fileInputStream = null;
+ private BufferedReader _bufferedReader = null;
+ private String _stringBufferNext = null;
+ private Pattern _validLinePrefixPattern;
+
+ private QueryParser _parser;
+ private String _path;
+
+ private LogInputIteratorImpl(Builder builder) {
+ _parser = builder._parser;
+ _path = builder._path;
+ String _validLinePrefixRegex = builder._validLinePrefixRegex;
+ _validLinePrefixPattern = Pattern.compile(_validLinePrefixRegex);
+ }
+
+ /**
+ * Closes this stream and releases any system resources associated
+ * with it. If the stream is already closed then invoking this
+ * method has no effect.
+ *
+ * <p> As noted in {@link AutoCloseable#close()}, cases where the
+ * close may fail require careful attention. It is strongly advised
+ * to relinquish the underlying resources and to internally
+ * <em>mark</em> the {@code Closeable} as closed, prior to throwing
+ * the {@code IOException}.
+ *
+ * @throws IOException if an I/O error occurs
+ */
+ @Override
+ public void close() throws IOException {
+ _fileInputStream.close();
+ _bufferedReader.close();
+ }
+
+ public static final class Builder {
+ private QueryParser _parser;
+ private String _path;
+ private String _validLinePrefixRegex = REGEX_VALID_LINE_TIME;
+
+ public Builder() {
+ }
+
+ /**
+ * Choose a parser
+ * @param val A parser, e.g. {@link BrokerLogParserImpl}
+ */
+ @Nonnull
+ public Builder setParser(@Nonnull QueryParser val) {
+ _parser = val;
+ return this;
+ }
+
+ /**
+ *
+ * @param val Path to the log file
+ */
+ @Nonnull
+ public Builder setPath(@Nonnull String val) {
+ _path = val;
+ return this;
+ }
+
+ /**
+ *
+ * @param val Starting pattern of a log line, default to REGEX_VALID_LINE_TIME = "^(\\d{4})/(\\d{2})/(\\d{2}) [\\d:.].*$"
+ */
+ @Nonnull
+ public Builder setValidLinePrefixRegex(@Nonnull String val) {
+ _validLinePrefixRegex = val;
+ return this;
+ }
+
+ @Nonnull
+ public LogInputIteratorImpl build() throws FileNotFoundException {
+ LOGGER.info("Line prefix pattern is set to:{}", this._validLinePrefixRegex);
+ return new LogInputIteratorImpl(this).init();
+ }
+ }
+
+ private LogInputIteratorImpl init() throws FileNotFoundException {
+ try {
+ _fileInputStream = new FileInputStream(this._path);
+ _bufferedReader = new BufferedReader(new InputStreamReader(_fileInputStream));
+ _stringBufferNext = _bufferedReader.readLine();
+ } catch (IOException e) {
+ LOGGER.error("Can't open log file: {}", _path, e);
+ throw new FileNotFoundException();
+ }
+ return this;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return this._stringBufferNext != null;
+ }
+
+ @Override
+ public AbstractQueryStats next() throws NoSuchElementException {
+ if (_stringBufferNext == null) {
+ throw new NoSuchElementException();
+ }
+ StringBuilder stringBuffer = new StringBuilder(_stringBufferNext);
+ try {
+ /*
+ * There can be linebreaks in a query, therefore we want to concatenate the log lines if we do not see
+ * and EOF or a valid beginner of a line
+ */
+ while ((_stringBufferNext = _bufferedReader.readLine()) != null && !_validLinePrefixPattern.matcher(
+ _stringBufferNext).find()) {
+ stringBuffer.append(_stringBufferNext);
+ _stringBufferNext = null;
+ }
+ } catch (IOException e) {
+ LOGGER.error("Exception while reading lines from the file", e);
+ _stringBufferNext = null;
+ } finally {
+ LOGGER.trace("FileReader returning: {}", stringBuffer.toString());
+ return _parser.parse(stringBuffer.toString());
+ }
+ }
+}
\ No newline at end of file
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/parser/BrokerLogParserImpl.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/parser/BrokerLogParserImpl.java
new file mode 100644
index 0000000..18eaa45
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/parser/BrokerLogParserImpl.java
@@ -0,0 +1,76 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.query.src.parser;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.annotation.Nullable;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.IndexSuggestQueryStatsImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Implementation of {@link QueryParser}, to parse complete lines of broker log text
+ */
+public class BrokerLogParserImpl implements QueryParser {
+ private static final Logger LOGGER = LoggerFactory.getLogger(BrokerLogParserImpl.class);
+
+ //Regex to parse Broker Log
+ private static final String BROKER_LOG_REGEX =
+ "^.*?table:(.+?)(?:_OFFLINE|_REALTIME|_HYBRID|)?, timeMs:(\\d+), docs:(\\d+)/(\\d+).*, entries:(\\d+)/(\\d+),.*, query:(.+)$";
+
+ private static final Pattern COMPILED_PATTERN = Pattern.compile(BROKER_LOG_REGEX);
+
+ private enum GroupNames {
+ ALL,
+ TABLE_NAME_WITHOUT_TYPE,
+ TOTAL_TIME,
+ DOCS_SCANNED_AGGREGATE,
+ TOTAL_DOCS,
+ NUM_ENTRIES_SCANNED_IN_FILTER,
+ NUM_ENTRIES_SCANNED_POST_FILTER,
+ QUERY
+ }
+
+ @Nullable
+ @Override
+ public AbstractQueryStats parse(String line) {
+ try {
+ Matcher match = COMPILED_PATTERN.matcher(line);
+ LOGGER.trace("Original line: " + line);
+ if (match.find()) {
+ IndexSuggestQueryStatsImpl ret =
+ new IndexSuggestQueryStatsImpl.Builder().setTime(match.group(GroupNames.TOTAL_TIME.ordinal()))
+ .setTableNameWithoutType(match.group(GroupNames.TABLE_NAME_WITHOUT_TYPE.ordinal()))
+ .setNumEntriesScannedInFilter(match.group(GroupNames.NUM_ENTRIES_SCANNED_IN_FILTER.ordinal()))
+ .setNumEntriesScannedPostFilter(match.group(GroupNames.NUM_ENTRIES_SCANNED_POST_FILTER.ordinal()))
+ .setQuery(match.group(GroupNames.QUERY.ordinal()))
+ .build();
+ LOGGER.debug("Parsed line: " + ret.toString());
+ return ret;
+ }
+ return null;
+ } catch (Exception e) {
+ LOGGER.error("Exception while parsing line {}", line, e);
+ return null;
+ }
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/parser/QueryParser.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/parser/QueryParser.java
new file mode 100644
index 0000000..6f2963d
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/parser/QueryParser.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.pinot.tools.tuner.query.src.parser;
+
+import javax.annotation.Nullable;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+
+
+/**
+ * Parser interface for a query line
+ */
+public interface QueryParser {
+ /**
+ * parse the the complete log line to a parsed obj
+ * @param line the complete log line to be parsed, InputIterator should put broken lines together
+ * @return the parsed log line obj
+ */
+ @Nullable
+ AbstractQueryStats parse(String line);
+}
+
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/stats/wrapper/AbstractQueryStats.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/stats/wrapper/AbstractQueryStats.java
new file mode 100644
index 0000000..337784a
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/stats/wrapper/AbstractQueryStats.java
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.query.src.stats.wrapper;
+
+/**
+ * Wrapper for query stats fields, for ex, time, entriesScannedInFilter, etc.
+ */
+public abstract class AbstractQueryStats {
+ public abstract String toString();
+
+ protected String _query;
+ protected String _tableNameWithoutType;
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/stats/wrapper/IndexSuggestQueryStatsImpl.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/stats/wrapper/IndexSuggestQueryStatsImpl.java
new file mode 100644
index 0000000..2d13ed2
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/query/src/stats/wrapper/IndexSuggestQueryStatsImpl.java
@@ -0,0 +1,117 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.query.src.stats.wrapper;
+
+import javax.annotation.Nonnull;
+
+
+/**
+ * The query stats used for inverted index study and recommendation
+ */
+public class IndexSuggestQueryStatsImpl extends AbstractQueryStats {
+
+ private String _time;
+ private String _numEntriesScannedInFilter;
+ private String _numEntriesScannedPostFilter;
+
+ public static final class Builder {
+ private String _tableNameWithoutType = null;
+ private String _numEntriesScannedInFilter = null;
+ private String _numEntriesScannedPostFilter = null;
+ private String _query = null;
+ private String _time = null;
+
+ public Builder() {
+ }
+
+ /**
+ *
+ * @param val Query text
+ */
+ @Nonnull
+ public Builder setQuery(@Nonnull String val) {
+ _query = val;
+ return this;
+ }
+
+ @Nonnull
+ public Builder setTableNameWithoutType(@Nonnull String val) {
+ _tableNameWithoutType = val;
+ return this;
+ }
+
+ @Nonnull
+ public Builder setNumEntriesScannedInFilter(String val) {
+ _numEntriesScannedInFilter = val;
+ return this;
+ }
+
+ @Nonnull
+ public Builder setNumEntriesScannedPostFilter(String val) {
+ _numEntriesScannedPostFilter = val;
+ return this;
+ }
+
+ @Nonnull
+ public IndexSuggestQueryStatsImpl build() {
+ return new IndexSuggestQueryStatsImpl(this);
+ }
+
+ @Nonnull
+ public Builder setTime(@Nonnull String val) {
+ _time = val;
+ return this;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "IndexSuggestQueryStatsImpl{" + "_time='" + _time + '\'' + ", _tableNameWithoutType='"
+ + _tableNameWithoutType + '\'' + ", _numEntriesScannedInFilter='" + _numEntriesScannedInFilter + '\''
+ + ", _numEntriesScannedPostFilter='" + _numEntriesScannedPostFilter + '\'' + ", _query='" + _query + '\'' + '}';
+ }
+
+ private IndexSuggestQueryStatsImpl(Builder builder) {
+ _time = builder._time;
+ _tableNameWithoutType = builder._tableNameWithoutType;
+ _numEntriesScannedInFilter = builder._numEntriesScannedInFilter;
+ _numEntriesScannedPostFilter = builder._numEntriesScannedPostFilter;
+ _query = builder._query;
+ }
+
+ public String getQuery() {
+ return _query;
+ }
+
+ public String getTime() {
+ return _time;
+ }
+
+ public String getTableNameWithoutType() {
+ return _tableNameWithoutType;
+ }
+
+ public String getNumEntriesScannedInFilter() {
+ return _numEntriesScannedInFilter;
+ }
+
+ public String getNumEntriesScannedPostFilter() {
+ return _numEntriesScannedPostFilter;
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/AbstractAccumulator.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/AbstractAccumulator.java
new file mode 100644
index 0000000..7762f21
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/AbstractAccumulator.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.pinot.tools.tuner.strategy;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.annotation.concurrent.NotThreadSafe;
+
+
+/**
+ * Abstract accumulator for column stats.
+ */
+@NotThreadSafe
+public abstract class AbstractAccumulator {
+ public static AbstractAccumulator putAccumulatorToMapIfAbsent(
+ Map<String, Map<String, AbstractAccumulator>> tableToColAccumulators, String tableNameWithoutType, String colName,
+ AbstractAccumulator abstractAccumulator) {
+ tableToColAccumulators.putIfAbsent(tableNameWithoutType, new HashMap<>());
+ tableToColAccumulators.get(tableNameWithoutType).putIfAbsent(colName, abstractAccumulator);
+ return tableToColAccumulators.get(tableNameWithoutType).get(colName);
+ }
+
+ public abstract String toString();
+
+ /**
+ * Get the default count for the number of {@link AbstractAccumulator} merged to this.
+ */
+ public long getCount() {
+ return _count;
+ }
+
+ private long _count = 0;
+
+ /**
+ * Increase default counter by one
+ */
+ public void increaseCount() {
+ _count += 1;
+ }
+
+ /**
+ * Merge the default counter of two {@link AbstractAccumulator}
+ * @param abstractAccumulator {@link AbstractAccumulator} to merge to this {@link AbstractAccumulator}
+ */
+ public void mergeCount(AbstractAccumulator abstractAccumulator) {
+ this._count += abstractAccumulator._count;
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/FrequencyAccumulator.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/FrequencyAccumulator.java
new file mode 100644
index 0000000..62c1057
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/FrequencyAccumulator.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.strategy;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+
+/**
+ * An implementation of {@link AbstractAccumulator}, count the frequency of dimension appearance for {@link FrequencyImpl}
+ */
+@NotThreadSafe
+public class FrequencyAccumulator extends AbstractAccumulator {
+
+ public FrequencyAccumulator() {
+ _frequency = 0;
+ }
+
+ private long _frequency;
+
+ public long getFrequency() {
+ return _frequency;
+ }
+
+ public void incrementFrequency() {
+ super.increaseCount();
+ this._frequency += 1;
+ }
+
+ public void merge(FrequencyAccumulator fobj) {
+ super.mergeCount(fobj);
+ this._frequency += fobj._frequency;
+ }
+
+ @Override
+ public String toString() {
+ return "ParseBasedMergerObj{" + "_frequency=" + _frequency + '}';
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/FrequencyImpl.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/FrequencyImpl.java
new file mode 100644
index 0000000..041e434
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/FrequencyImpl.java
@@ -0,0 +1,200 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.strategy;
+
+import io.vavr.Tuple2;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.annotation.Nonnull;
+import org.apache.commons.math.fraction.BigFraction;
+import org.apache.pinot.tools.tuner.meta.manager.MetaManager;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.IndexSuggestQueryStatsImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A strategy of simply counting the number of appearances of each dimension and rank them.
+ */
+public class FrequencyImpl implements TuningStrategy {
+ private static final Logger LOGGER = LoggerFactory.getLogger(FrequencyImpl.class);
+
+ private static final String NUM_QUERIES_COUNT = "PINOT_TUNER_COUNT*";
+
+ public final static String DIMENSION_REGEX = "(?:(\\w+) ((?:NOT )?IN) (\\(.+?\\)))|(?:(\\w+) (=|<>|!=) (.+?)[ |$)])";
+
+ public final static long DEFAULT_IN_FILTER_THRESHOLD = 0;
+ public final static long DEFAULT_CARDINALITY_THRESHOLD = 1;
+ public final static long DEFAULT_NUM_QUERIES_THRESHOLD = 0;
+ public static final int MATCHER_GROUP_DIMENSION_IN = 1;
+ public static final int MATCHER_GROUP_DIMENSION_COMP = 4;
+
+ public final static Pattern _dimensionPattern = Pattern.compile(DIMENSION_REGEX);
+ private Set<String> _tableNamesWithoutType;
+ private long _numEntriesScannedThreshold;
+ private long _cardinalityThreshold;
+ private long _numQueriesThreshold;
+ private boolean _skipTableCheck;
+
+ private FrequencyImpl(Builder builder) {
+ _tableNamesWithoutType = builder._tableNamesWithoutType;
+ _numEntriesScannedThreshold = builder._numEntriesScannedThreshold;
+ _cardinalityThreshold = builder._cardinalityThreshold;
+ _numQueriesThreshold = builder._numQueriesThreshold;
+ _skipTableCheck = (_tableNamesWithoutType == null) || _tableNamesWithoutType.isEmpty();
+ }
+
+ public static final class Builder {
+ private Set<String> _tableNamesWithoutType = Collections.EMPTY_SET;
+ private long _numEntriesScannedThreshold = DEFAULT_IN_FILTER_THRESHOLD;
+ private long _cardinalityThreshold = DEFAULT_CARDINALITY_THRESHOLD;
+ private long _numQueriesThreshold = DEFAULT_NUM_QUERIES_THRESHOLD;
+
+ public Builder() {
+ }
+
+ @Nonnull
+ public FrequencyImpl build() {
+ return new FrequencyImpl(this);
+ }
+
+ /**
+ * set the tables to work on, other tables will be filtered out
+ * @param val set of table names without type
+ */
+ @Nonnull
+ public Builder setTableNamesWithoutType(@Nonnull Set<String> val) {
+ _tableNamesWithoutType = val;
+ return this;
+ }
+
+ /**
+ * set the threshold for _numEntriesScannedInFilter, the queries with _numEntriesScannedInFilter below this will be filtered out
+ * @param val threshold for _numEntriesScannedInFilter, default to 0
+ */
+ @Nonnull
+ public Builder setNumEntriesScannedThreshold(long val) {
+ _numEntriesScannedThreshold = val;
+ return this;
+ }
+
+ /**
+ * set the cardinality threshold, column with cardinality below this will be ignored,
+ * setting a high value will force the system to ignore low card columns
+ * @param val cardinality threshold, default to 1
+ */
+ @Nonnull
+ public Builder setCardinalityThreshold(long val) {
+ _cardinalityThreshold = val;
+ return this;
+ }
+
+ /**
+ * set the minimum number of records scanned to give a recommendation
+ * @param val minimum number of records scanned to give a recommendation, default to 0
+ */
+ @Nonnull
+ public Builder setNumQueriesThreshold(long val) {
+ _numQueriesThreshold = val;
+ return this;
+ }
+ }
+
+ @Override
+ public boolean filter(AbstractQueryStats queryStats) {
+ IndexSuggestQueryStatsImpl indexSuggestQueryStatsImpl = (IndexSuggestQueryStatsImpl) queryStats;
+ long numEntriesScannedInFilter = Long.parseLong(indexSuggestQueryStatsImpl.getNumEntriesScannedInFilter());
+ return (_skipTableCheck || _tableNamesWithoutType.contains(
+ indexSuggestQueryStatsImpl.getTableNameWithoutType())) && (numEntriesScannedInFilter > _numEntriesScannedThreshold);
+ }
+
+ @Override
+ public void accumulate(AbstractQueryStats queryStats, MetaManager metaManager, Map<String, Map<String, AbstractAccumulator>> accumulatorOut) {
+
+ IndexSuggestQueryStatsImpl indexSuggestQueryStatsImpl = (IndexSuggestQueryStatsImpl) queryStats;
+ String tableNameWithoutType = indexSuggestQueryStatsImpl.getTableNameWithoutType();
+ String numEntriesScannedInFilter = indexSuggestQueryStatsImpl.getNumEntriesScannedInFilter();
+ String query = indexSuggestQueryStatsImpl.getQuery();
+ LOGGER.debug("Accumulator: scoring query {}", query);
+ HashSet<String> counted = new HashSet<>();
+
+ AbstractAccumulator.putAccumulatorToMapIfAbsent(accumulatorOut, tableNameWithoutType, NUM_QUERIES_COUNT,
+ new FrequencyAccumulator()).increaseCount();
+
+ Matcher matcher = _dimensionPattern.matcher(query);
+ while (matcher.find()) {
+ if (matcher.group(MATCHER_GROUP_DIMENSION_IN) != null) {
+ counted.add(matcher.group(MATCHER_GROUP_DIMENSION_IN));
+ } else if (matcher.group(MATCHER_GROUP_DIMENSION_COMP) != null) {
+ counted.add(matcher.group(MATCHER_GROUP_DIMENSION_COMP));
+ }
+ }
+
+ counted.stream()
+ .filter(colName -> metaManager.getColumnSelectivity(tableNameWithoutType, colName).compareTo(new BigFraction(_cardinalityThreshold)) > 0)
+ .forEach(colName -> {
+ ((FrequencyAccumulator) AbstractAccumulator.putAccumulatorToMapIfAbsent(accumulatorOut, tableNameWithoutType,
+ colName, new FrequencyAccumulator())).incrementFrequency();
+ });
+ }
+
+ @Override
+ public void merge(AbstractAccumulator p1, AbstractAccumulator p2) {
+ ((FrequencyAccumulator) p1).merge((FrequencyAccumulator) p2);
+ }
+
+ /**
+ * Generate a report for recommendation using tableResults:tableName/colName/AbstractMergerObj
+ * @param tableResults input
+ */
+ public void report(Map<String, Map<String, AbstractAccumulator>> tableResults) {
+ tableResults.forEach((table, map) -> {
+ reportTable(table, map);
+ });
+ }
+
+ private void reportTable(String tableNameWithoutType, Map<String, AbstractAccumulator> columnStats) {
+ String reportOut = "\n**********************Report For Table: " + tableNameWithoutType + "**********************\n";
+ long totalCount = columnStats.remove(NUM_QUERIES_COUNT).getCount();
+ if (totalCount < _numQueriesThreshold) {
+ reportOut += "No enough data accumulated for this table!\n";
+ LOGGER.info(reportOut);
+ return;
+ }
+
+ reportOut += MessageFormat.format("\nTotal lines accumulated: {0}\n\n", totalCount);
+ List<Tuple2<String, Long>> sortedPure = new ArrayList<>();
+ columnStats.forEach(
+ (colName, score) -> sortedPure.add(new Tuple2<>(colName, ((FrequencyAccumulator) score).getFrequency())));
+ sortedPure.sort((p1, p2) -> (p2._2().compareTo(p1._2())));
+ for (Tuple2<String, Long> tuple2 : sortedPure) {
+ reportOut += "Dimension: " + tuple2._1() + " " + tuple2._2().toString() + "\n";
+ }
+ LOGGER.info(reportOut);
+ }
+}
+
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/ParseBasedAccumulator.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/ParseBasedAccumulator.java
new file mode 100644
index 0000000..d0a0a24
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/ParseBasedAccumulator.java
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.strategy;
+
+import java.math.BigInteger;
+import javax.annotation.concurrent.NotThreadSafe;
+
+
+/**
+ * An implementation of {@link AbstractAccumulator}, to count the score for {@link ParserBasedImpl}
+ */
+@NotThreadSafe
+public class ParseBasedAccumulator extends AbstractAccumulator {
+ private long _pureScore; //the appearance of a dimension as the top pick for a query
+ private BigInteger _weightedScore; //the appearance weighted by numEntriesScannedInFilter
+
+ public long getPureScore() {
+ return _pureScore;
+ }
+
+ public BigInteger getWeightedScore() {
+ return _weightedScore;
+ }
+
+ public ParseBasedAccumulator() {
+ _pureScore = 0;
+ _weightedScore = BigInteger.ZERO;
+ }
+
+ public void merge(int _pureScore, BigInteger _weightedScore) {
+ super.increaseCount();
+ this._pureScore += _pureScore;
+ this._weightedScore = this._weightedScore.add(_weightedScore);
+ }
+
+ public void merge(ParseBasedAccumulator pb) {
+ super.mergeCount(pb);
+ this._pureScore += pb._pureScore;
+ this._weightedScore = this._weightedScore.add(pb._weightedScore);
+ }
+
+ @Override
+ public String toString() {
+ return "ParseBasedMergerObj{" + "_pureScore=" + _pureScore + ", _weightedScore=" + _weightedScore + '}';
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/ParserBasedImpl.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/ParserBasedImpl.java
new file mode 100644
index 0000000..065d25a
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/ParserBasedImpl.java
@@ -0,0 +1,453 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.strategy;
+
+import io.vavr.Tuple2;
+import java.math.BigInteger;
+import java.math.RoundingMode;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.MessageFormat;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.annotation.Nonnull;
+import javax.validation.constraints.NotNull;
+import org.antlr.v4.runtime.ANTLRInputStream;
+import org.antlr.v4.runtime.CommonTokenStream;
+import org.antlr.v4.runtime.tree.ParseTree;
+import org.apache.commons.math.fraction.BigFraction;
+import org.apache.pinot.pql.parsers.PQL2Lexer;
+import org.apache.pinot.pql.parsers.PQL2Parser;
+import org.apache.pinot.tools.tuner.meta.manager.MetaManager;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.IndexSuggestQueryStatsImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A parser based implementation of {@link TuningStrategy} to give recommendation to inverted and sorted index
+ * by recursively scoring each sub predicate
+ */
+public class ParserBasedImpl implements TuningStrategy {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ParserBasedImpl.class);
+ private static final String NUM_QUERIES_COUNT = "PINOT_TUNER_COUNT*";
+
+ public final static int FIRST_ORDER = 1;
+ public final static int SECOND_ORDER = 2;
+ public final static int THIRD_ORDER = 3;
+
+ public final static long DEFAULT_NUM_ENTRIES_IN_FILTER_THRESHOLD = 0;
+ public final static long DEFAULT_NUM_QUERIES_THRESHOLD = 0;
+ public final static int DEFAULT_CARDINALITY_THRESHOLD = 1;
+
+ private int _algorithmOrder;
+ private Set<String> _tableNamesWithoutType;
+ private long _numEntriesScannedThreshold;
+ private long _numQueriesThreshold;
+ private int _selectivityThreshold;
+ private boolean _skipTableCheck;
+
+ private ParserBasedImpl(Builder builder) {
+ _algorithmOrder = builder._algorithmOrder;
+ _tableNamesWithoutType = builder._tableNamesWithoutType;
+ _numEntriesScannedThreshold = builder._numEntriesScannedThreshold;
+ _numQueriesThreshold = builder._numQueriesThreshold;
+ _selectivityThreshold = builder._selectivityThreshold;
+ _skipTableCheck = (_tableNamesWithoutType == null) || _tableNamesWithoutType.isEmpty();
+ }
+
+ public static final class Builder {
+ private int _algorithmOrder = FIRST_ORDER;
+ private Set<String> _tableNamesWithoutType = Collections.EMPTY_SET;
+ private long _numEntriesScannedThreshold = DEFAULT_NUM_ENTRIES_IN_FILTER_THRESHOLD;
+ private long _numQueriesThreshold = DEFAULT_NUM_QUERIES_THRESHOLD;
+ private int _selectivityThreshold = DEFAULT_CARDINALITY_THRESHOLD;
+
+ public Builder() {
+ }
+
+ @Nonnull
+ public ParserBasedImpl build() {
+ return new ParserBasedImpl(this);
+ }
+
+ /**
+ * Lower order(FIRST_ORDER) for inverted index, higher order(SECOND_ORDER) for sorted (broad coverage), default to FIRST_ORDER
+ */
+ @Nonnull
+ public Builder setAlgorithmOrder(int val) {
+ _algorithmOrder = val;
+ return this;
+ }
+
+ /**
+ * Set the tables to work on, other tables will be filtered out
+ * @param val set of table names without type
+ */
+ @Nonnull
+ public Builder setTableNamesWithoutType(@Nonnull Set<String> val) {
+ _tableNamesWithoutType = val;
+ return this;
+ }
+
+ /**
+ * Set the threshold for _numEntriesScannedInFilter, the queries with _numEntriesScannedInFilter below this will be filtered out
+ */
+ @Nonnull
+ public Builder setNumEntriesScannedThreshold(long val) {
+ _numEntriesScannedThreshold = val;
+ return this;
+ }
+
+ /**
+ * Set the minimum number of records scanned to give a recommendation
+ * @param val minimum number of records scanned to give a recommendation, default to 0
+ */
+ @Nonnull
+ public Builder setNumQueriesThreshold(long val) {
+ _numQueriesThreshold = val;
+ return this;
+ }
+
+ /**
+ * Set the selectivity threshold, column with selectivity below this will be ignored;
+ * setting a high value will force the system to ignore low selectivity columns
+ * @param val selectivity threshold, default to 1
+ */
+ @Nonnull
+ public Builder setSelectivityThreshold(int val) {
+ _selectivityThreshold = val;
+ return this;
+ }
+ }
+
+ @Override
+ public boolean filter(AbstractQueryStats queryStats) {
+ IndexSuggestQueryStatsImpl indexSuggestQueryStatsImpl = (IndexSuggestQueryStatsImpl) queryStats;
+ long numEntriesScannedInFilter = Long.parseLong(indexSuggestQueryStatsImpl.getNumEntriesScannedInFilter());
+ return (_skipTableCheck || _tableNamesWithoutType.contains(indexSuggestQueryStatsImpl.getTableNameWithoutType()))
+ && (numEntriesScannedInFilter > _numEntriesScannedThreshold);
+ }
+
+ @Override
+ public void accumulate(AbstractQueryStats queryStats, MetaManager metaManager,
+ Map<String, Map<String, AbstractAccumulator>> accumulatorOut) {
+
+ IndexSuggestQueryStatsImpl indexSuggestQueryStatsImpl = (IndexSuggestQueryStatsImpl) queryStats;
+ String tableNameWithoutType = indexSuggestQueryStatsImpl.getTableNameWithoutType();
+ String numEntriesScannedInFilter = indexSuggestQueryStatsImpl.getNumEntriesScannedInFilter();
+ String query = indexSuggestQueryStatsImpl.getQuery();
+
+ AbstractAccumulator.putAccumulatorToMapIfAbsent(accumulatorOut, tableNameWithoutType, NUM_QUERIES_COUNT,
+ new ParseBasedAccumulator()).increaseCount();
+
+ LOGGER.debug("Accumulator: scoring query {}", query);
+
+ DimensionScoring dimensionScoring = new DimensionScoring(tableNameWithoutType, metaManager, query);
+ List<Tuple2<List<String>, BigFraction>> columnScores = dimensionScoring.parseQuery();
+ LOGGER.debug("Accumulator: query score: {}", columnScores.toString());
+
+ Set<String> counted = new HashSet<>();
+ //Discard if the effective selectivity is less than _selectivityThreshold
+ BigFraction selectivityThresholdFraction = new BigFraction(_selectivityThreshold);
+ Stream<Tuple2<List<String>, BigFraction>> filteredColumnScores = columnScores.stream()
+ .filter(tupleNamesScore -> tupleNamesScore._2().compareTo(selectivityThresholdFraction) > 0);
+ filteredColumnScores.forEach(tupleNamesScore -> {
+ //Do not count if already counted
+ tupleNamesScore._1().stream().filter(colName -> !counted.contains(colName)).forEach(colName -> {
+ counted.add(colName);
+ BigFraction weightedScore = BigFraction.ONE.subtract(tupleNamesScore._2().reciprocal())
+ .multiply(new BigInteger(numEntriesScannedInFilter));
+ ParseBasedAccumulator accumulatorToMergeTo =
+ ((ParseBasedAccumulator) AbstractAccumulator.putAccumulatorToMapIfAbsent(accumulatorOut,
+ tableNameWithoutType, colName, new ParseBasedAccumulator()));
+ accumulatorToMergeTo.merge(1, weightedScore.bigDecimalValue(RoundingMode.DOWN.ordinal()).toBigInteger());
+ });
+ });
+ }
+
+ @Override
+ public void merge(AbstractAccumulator p1, AbstractAccumulator p2) {
+ ((ParseBasedAccumulator) p1).merge((ParseBasedAccumulator) p2);
+ }
+
+ /**
+ * Generate a report for recommendation using tableResults:tableName/colName/AbstractMergerObj
+ * @param tableResults input
+ */
+ public void report(Map<String, Map<String, AbstractAccumulator>> tableResults) {
+ tableResults.forEach((table, map) -> {
+ reportTable(table, map);
+ });
+ }
+
+ private void reportTable(String tableNameWithoutType, Map<String, AbstractAccumulator> columnStats) {
+ String reportOut = "\n**********************Report For Table: " + tableNameWithoutType + "**********************\n";
+ long totalCount = columnStats.remove(NUM_QUERIES_COUNT).getCount();
+ if (totalCount < _numQueriesThreshold) {
+ reportOut += "No enough data accumulated for this table!\n";
+ LOGGER.info(reportOut);
+ return;
+ }
+ NumberFormat formatter = new DecimalFormat("0.######E0", DecimalFormatSymbols.getInstance(Locale.ROOT));
+ List<Tuple2<String, Long>> sortedPure = new ArrayList<>();
+ List<Tuple2<String, BigInteger>> sortedWeighted = new ArrayList<>();
+ reportOut += MessageFormat.format("\nTotal lines accumulated: {0}\n\n", totalCount);
+ columnStats.forEach((colName, score) -> {
+ sortedPure.add(new Tuple2<>(colName, ((ParseBasedAccumulator) score).getPureScore()));
+ sortedWeighted.add(new Tuple2<>(colName, ((ParseBasedAccumulator) score).getWeightedScore()));
+ });
+ sortedPure.sort((p1, p2) -> (p2._2().compareTo(p1._2())));
+ sortedWeighted.sort((p1, p2) -> (p2._2().compareTo(p1._2())));
+ reportOut += "________________________________Score_______________________________________\n";
+ reportOut += "The overall goodness of a index, the score is the overall goodness of index:\n\n";
+ for (Tuple2<String, BigInteger> tuple2 : sortedWeighted) {
+ reportOut += "Dimension: " + tuple2._1() + " " + formatter.format(tuple2._2()) + "\n";
+ }
+ reportOut += "\n________________________________Coverage___________________________________\n";
+ reportOut += "At least % of queries will benefit from a given index, for reference only:\n\n";
+ for (Tuple2<String, Long> tuple2 : sortedPure) {
+ reportOut += "Dimension: " + tuple2._1() + " " + String.valueOf(
+ Double.parseDouble(tuple2._2().toString()) / totalCount * 100) + "%\n";
+ }
+ LOGGER.info(reportOut);
+ }
+
+ /**
+ * Parse and score the dimensions in a query
+ */
+ class DimensionScoring {
+ static final String AND = "AND";
+ static final String OR = "OR";
+ private String _tableNameWithoutType;
+ private MetaManager _metaManager;
+ private String _queryString;
+ private final Logger LOGGER = LoggerFactory.getLogger(DimensionScoring.class);
+
+ DimensionScoring(String tableNameWithoutType, MetaManager metaManager, String queryString) {
+ _tableNameWithoutType = tableNameWithoutType;
+ _metaManager = metaManager;
+ _queryString = queryString;
+ }
+
+ /**
+ * Navigate from root to predicateListContext of whereClauseContext, where all the filtering happens
+ * @return a list of sorted tuples List<Tuple2<List<colName>, Score>>
+ */
+ @NotNull List<Tuple2<List<String>, BigFraction>> parseQuery() {
+ LOGGER.debug("Parsing query: {}", _queryString);
+ PQL2Parser.OptionalClauseContext optionalClauseContext;
+ PQL2Parser.WhereClauseContext whereClauseContext = null;
+
+ if (_queryString == null) {
+ return Collections.EMPTY_LIST;
+ }
+
+ try {
+ PQL2Lexer lexer = new PQL2Lexer(new ANTLRInputStream(_queryString));
+ PQL2Parser parser = new PQL2Parser(new CommonTokenStream(lexer));
+ ParseTree selectStatement = parser.root().statement().selectStatement();
+ LOGGER.debug("selectStatement: {}", selectStatement.getText());
+
+ for (int i = 0; i < selectStatement.getChildCount(); i++) {
+ if (selectStatement.getChild(i) instanceof PQL2Parser.OptionalClauseContext) {
+ optionalClauseContext = (PQL2Parser.OptionalClauseContext) selectStatement.getChild(i);
+ LOGGER.debug("optionalClauseContext: {}", optionalClauseContext.getText());
+ if (optionalClauseContext.getChild(0) instanceof PQL2Parser.WhereClauseContext) {
+ whereClauseContext = (PQL2Parser.WhereClauseContext) optionalClauseContext.getChild(0);
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ return Collections.EMPTY_LIST;
+ }
+ if (whereClauseContext == null) {
+ return Collections.EMPTY_LIST;
+ }
+
+ LOGGER.debug("whereClauseContext: {}", whereClauseContext.getText());
+
+ List<Tuple2<List<String>, BigFraction>> results = parsePredicateList(whereClauseContext.predicateList());
+ return results.stream().limit(_algorithmOrder).collect(Collectors.toList());
+ }
+
+ /**
+ * Parse predicate list connected by AND and OR (recursively)
+ * The score is calculated as:
+ * AND connected: pick the top _algorithmOrder of sorted([([colName],Score(predicate)) for predicate in predicateList])
+ * OR connected: ([colName1]+[colName2]+[colName3], 1/(1/Score(predicate1)+1/Score(predicate2)+1/Score(predicate3))) i.e. Harmonic mean of scores
+ * @param predicateListContext the leaf predicate context where the score are generated from selectivity
+ * @return a list of sorted tuples List<Tuple2<List<colName>, Score>>
+ */
+ List<Tuple2<List<String>, BigFraction>> parsePredicateList(PQL2Parser.PredicateListContext predicateListContext) {
+ LOGGER.debug("Parsing predicate list: {}", predicateListContext.getText());
+ if (predicateListContext.getChildCount() == 1) {
+ LOGGER.debug("Parsing parenthesis group/a leaf predicate");
+ return parsePredicate((PQL2Parser.PredicateContext) predicateListContext.getChild(0));
+ } else if (predicateListContext.getChild(1).getText().toUpperCase().equals(AND)) {
+ LOGGER.debug("Parsing AND list {}", predicateListContext.getText());
+ List<Tuple2<List<String>, BigFraction>> childResults = new ArrayList<>();
+
+ for (int i = 0; i < predicateListContext.getChildCount(); i += 2) {
+ List<Tuple2<List<String>, BigFraction>> childResult =
+ parsePredicate((PQL2Parser.PredicateContext) predicateListContext.getChild(i));
+ if (childResult != null) {
+ childResults.addAll(childResult);
+ }
+ }
+
+ childResults.sort(
+ Comparator.comparing((Function<Tuple2<List<String>, BigFraction>, BigFraction>) Tuple2::_2).reversed());
+ LOGGER.debug("AND rank: {}", childResults.toString());
+ return childResults.stream().limit(_algorithmOrder).collect(Collectors.toList());
+ } else if (predicateListContext.getChild(1).getText().toUpperCase().equals(OR)) {
+ LOGGER.debug("Parsing OR list: {}", predicateListContext.getText());
+ BigFraction weight = BigFraction.ZERO;
+ List<String> colNames = new ArrayList<>();
+ List<Tuple2<List<String>, BigFraction>> childResults = new ArrayList<>();
+
+ for (int i = 0; i < predicateListContext.getChildCount(); i += 2) {
+ List<Tuple2<List<String>, BigFraction>> childResult =
+ parsePredicate((PQL2Parser.PredicateContext) predicateListContext.getChild(i));
+ if (childResult != null && childResult.size() > 0
+ && childResult.get(0)._2().compareTo(BigFraction.ZERO) > 0) {
+ colNames.addAll(childResult.get(0)._1());
+ weight = weight.add(childResult.get(0)._2().reciprocal());
+ }
+ }
+ LOGGER.debug("OR rank sum weight: {}", weight);
+
+ if (weight.compareTo(BigFraction.ZERO) <= 0) {
+ return childResults;
+ }
+
+ weight = weight.reciprocal();
+ childResults.add(new Tuple2<>(colNames, weight));
+ LOGGER.debug("OR rank: {}", childResults.toString());
+ return childResults;
+ } else {
+ LOGGER.error("Query: " + _queryString + " parsing exception: " + predicateListContext.getText());
+ return Collections.EMPTY_LIST;
+ }
+ }
+
+ private BigFraction equivalentSelectivity(Boolean invertSelection, BigFraction selectivity, int numSelectedValues) {
+ BigFraction equivalentLen = new BigFraction(numSelectedValues);
+ if (!invertSelection) { // not invertSelection
+ return selectivity.divide(equivalentLen);
+ // return selectivity/equivalentLen; equivalentLen=len(literals to match)*len(avgEntries)
+ } else { // invertSelection
+ BigFraction complementary = selectivity.subtract(equivalentLen); // complementary=(selectivity-equivalentLen)
+ if (complementary.compareTo(BigFraction.ONE) <= 0) { // if (selectivity-equivalentLen)<=1
+ return selectivity; // return selectivity/1
+ } else {
+ return selectivity.divide(complementary); // return selectivity/(selectivity-equivalentLen)
+ }
+ }
+ }
+
+ /**
+ * Parse leaf predicates
+ * The score is calculated as:
+ * IN clause:
+ * IN: selectivity/len(literals to match)
+ * NOT IN: selectivity/(selectivity-len(literals to match)*len(avgEntries))
+ * Comparison clause:
+ * '=': selectivity
+ * '!=' '<>' selectivity/(selectivity-1*len(avgEntries))
+ *
+ * Other Predicates have no scoring for now
+ * TODO:
+ * Range ( <d<, BETWEEN AND) clause:
+ * average_values_hit/selectivity
+ * Moreover, if average_values_hit is made available, prediction for In clause can be optimized
+ * @param predicateContext the leaf predicate context where the score are generated from selectivity
+ * @return a list of tuples List<Tuple2<List<colName>, Score>>
+ */
+ List<Tuple2<List<String>, BigFraction>> parsePredicate(PQL2Parser.PredicateContext predicateContext) {
+ LOGGER.debug("Parsing predicate: {}", predicateContext.getText());
+ ArrayList<Tuple2<List<String>, BigFraction>> ret = new ArrayList<>();
+
+ if (predicateContext instanceof PQL2Parser.PredicateParenthesisGroupContext) {
+ PQL2Parser.PredicateParenthesisGroupContext predicateParenthesisGroupContext =
+ (PQL2Parser.PredicateParenthesisGroupContext) predicateContext;
+ return parsePredicateList(predicateParenthesisGroupContext.predicateList());
+ } else if (predicateContext instanceof PQL2Parser.InPredicateContext) {
+ LOGGER.debug("Entering IN clause!");
+ String colName = ((PQL2Parser.InPredicateContext) predicateContext).inClause().expression().getText();
+ BigFraction selectivity = _metaManager.getColumnSelectivity(_tableNameWithoutType, colName);
+ LOGGER.debug("Avg Cardinality: {} {} {}", selectivity, _tableNameWithoutType, colName);
+
+ if (selectivity.compareTo(BigFraction.ONE) <= 0) {
+ return ret;
+ }
+
+ List<String> colNameList = new ArrayList<>();
+ colNameList.add(colName);
+ int numValuesSelected = ((PQL2Parser.InPredicateContext) predicateContext).inClause().literal().size();
+ Boolean isInvertIn = ((PQL2Parser.InPredicateContext) predicateContext).inClause().NOT() != null;
+ LOGGER.debug("Length of in clause: {}", numValuesSelected);
+ ret.add(new Tuple2<>(colNameList, equivalentSelectivity(isInvertIn, selectivity, numValuesSelected)));
+
+ LOGGER.debug("IN clause ret {}", ret.toString());
+ return ret;
+ } else if (predicateContext instanceof PQL2Parser.ComparisonPredicateContext) {
+ LOGGER.debug("Entering COMP clause!");
+ String colName =
+ ((PQL2Parser.ComparisonPredicateContext) predicateContext).comparisonClause().expression(0).getText();
+ BigFraction selectivity = _metaManager.getColumnSelectivity(_tableNameWithoutType, colName);
+ LOGGER.debug("Avg Cardinality: {} {} {}", selectivity, _tableNameWithoutType, colName);
+
+ if (selectivity.compareTo(BigFraction.ONE) <= 0) {
+ return ret;
+ }
+
+ List<String> colNameList = new ArrayList<>();
+ colNameList.add(colName);
+
+ String comparisonOperator = ((PQL2Parser.ComparisonPredicateContext) predicateContext).comparisonClause()
+ .comparisonOperator()
+ .getText();
+ LOGGER.debug("COMP operator {}", comparisonOperator);
+ if (comparisonOperator.equals("=")) {
+ ret.add(new Tuple2<>(colNameList, equivalentSelectivity(false, selectivity, 1)));
+ LOGGER.debug("COMP clause ret {}", ret.toString());
+ return ret;
+ } else if (comparisonOperator.equals("!=") || comparisonOperator.equals("<>")) {
+ ret.add(new Tuple2<>(colNameList, equivalentSelectivity(true, selectivity, 1)));
+ LOGGER.debug("COMP clause ret {}", ret.toString());
+ return ret;
+ }
+ }
+ return ret;
+ }
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/QuantileAnalysisAccumulator.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/QuantileAnalysisAccumulator.java
new file mode 100644
index 0000000..248cf75
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/QuantileAnalysisAccumulator.java
@@ -0,0 +1,88 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.strategy;
+
+import io.vavr.Tuple2;
+import java.util.ArrayList;
+import java.util.HashMap;
+import javax.annotation.concurrent.NotThreadSafe;
+
+
+/**
+ * An implementation of {@link AbstractAccumulator}, to implement minimum pulling for {@link QuantileAnalysisImpl}
+ */
+@NotThreadSafe
+public class QuantileAnalysisAccumulator extends AbstractAccumulator {
+
+ private ArrayList<Long> _timeList;
+ private ArrayList<Long> _inFilterList;
+ private HashMap<Tuple2<Long, Long>, Tuple2<Long, Long>> _minBin;
+
+ public ArrayList<Long> getTimeList() {
+ return _timeList;
+ }
+
+ public ArrayList<Long> getInFilterList() {
+ return _inFilterList;
+ }
+
+ public HashMap<Tuple2<Long, Long>, Tuple2<Long, Long>> getMinBin() {
+ return _minBin;
+ }
+
+ public QuantileAnalysisAccumulator() {
+ _timeList = new ArrayList<>();
+ _inFilterList = new ArrayList<>();
+ _minBin = new HashMap<>();
+ }
+
+ public void merge(long time, long inFilter, long postFilter, long indexUsed, long binLen) {
+ super.increaseCount();
+ _timeList.add(time);
+ _inFilterList.add(inFilter);
+ Tuple2<Long, Long> key = new Tuple2<>(inFilter / binLen, postFilter / binLen);
+ if (_minBin.containsKey(key)) {
+ if (_minBin.get(key)._2() > time) {
+ _minBin.put(key, new Tuple2<>(indexUsed, time));
+ }
+ } else {
+ _minBin.put(new Tuple2<>(inFilter / binLen, postFilter / binLen), new Tuple2<>(indexUsed, time));
+ }
+ }
+
+ public void merge(QuantileAnalysisAccumulator o2) {
+ super.mergeCount(o2);
+ _timeList.addAll(o2._timeList);
+ _inFilterList.addAll(o2._inFilterList);
+ o2._minBin.forEach((key, val) -> {
+ if (_minBin.containsKey(key)) {
+ if (_minBin.get(key)._2() > val._2()) {
+ _minBin.put(key, val);
+ }
+ } else {
+ _minBin.put(key, val);
+ }
+ });
+ }
+
+ @Override
+ public String toString() {
+ return "OLSMergerObj{" + "_timeList=" + _timeList + ", _inFilterList=" + _inFilterList + ", _minBin=" + _minBin + '}';
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/QuantileAnalysisImpl.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/QuantileAnalysisImpl.java
new file mode 100644
index 0000000..246f5a0
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/QuantileAnalysisImpl.java
@@ -0,0 +1,351 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.strategy;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.annotation.Nonnull;
+import javax.validation.constraints.NotNull;
+import org.antlr.v4.runtime.ANTLRInputStream;
+import org.antlr.v4.runtime.CommonTokenStream;
+import org.antlr.v4.runtime.tree.ParseTree;
+import org.apache.commons.math3.exception.MathArithmeticException;
+import org.apache.commons.math3.exception.MathIllegalArgumentException;
+import org.apache.commons.math3.stat.descriptive.rank.Percentile;
+import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
+import org.apache.pinot.pql.parsers.PQL2Lexer;
+import org.apache.pinot.pql.parsers.PQL2Parser;
+import org.apache.pinot.tools.tuner.meta.manager.MetaManager;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.IndexSuggestQueryStatsImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A report generator to show the quantile of numEntriesScanned, and give the estimated time used in filtering if possible
+ */
+public class QuantileAnalysisImpl implements TuningStrategy {
+ private static final Logger LOGGER = LoggerFactory.getLogger(QuantileAnalysisImpl.class);
+
+ private static final String NUM_QUERIES_COUNT = "PINOT_TUNER_COUNT*";
+ public static final float MODEL_R_SQUARE_THRESHOLD = 0.7f;
+ private static final String QUANTILE_REPORT_KEY = "PINOT_QUANTILE_REPORT";
+
+ private HashSet<String> _tableNamesWithoutType;
+ private long _lenBin;
+
+ private QuantileAnalysisImpl(Builder builder) {
+ _tableNamesWithoutType = builder._tableNamesWithoutType;
+ _lenBin = builder._lenBin;
+ }
+
+ public static final class Builder {
+
+ private HashSet<String> _tableNamesWithoutType = new HashSet<>();
+ private long _lenBin = 100;
+
+ public Builder() {
+ }
+
+ @Nonnull
+ public QuantileAnalysisImpl build() {
+ return new QuantileAnalysisImpl(this);
+ }
+
+ @Nonnull
+ public Builder setTableNamesWithoutType(@Nonnull HashSet<String> val) {
+ _tableNamesWithoutType = val;
+ return this;
+ }
+
+ @Nonnull
+ public Builder setLenBin(long val) {
+ _lenBin = val;
+ return this;
+ }
+ }
+
+ @Override
+ public boolean filter(AbstractQueryStats queryStats) {
+ IndexSuggestQueryStatsImpl indexSuggestQueryStatsImpl = (IndexSuggestQueryStatsImpl) queryStats;
+ return (_tableNamesWithoutType == null || _tableNamesWithoutType.isEmpty() || _tableNamesWithoutType.contains(
+ indexSuggestQueryStatsImpl.getTableNameWithoutType()));
+ }
+
+ @Override
+ public void accumulate(AbstractQueryStats queryStats, MetaManager metaManager, Map<String, Map<String, AbstractAccumulator>> accumulatorOut) {
+
+ IndexSuggestQueryStatsImpl indexSuggestQueryStatsImpl = (IndexSuggestQueryStatsImpl) queryStats;
+ String tableNameWithoutType = indexSuggestQueryStatsImpl.getTableNameWithoutType();
+ String time = indexSuggestQueryStatsImpl.getTime();
+ String numEntriesScannedInFilter = indexSuggestQueryStatsImpl.getNumEntriesScannedInFilter();
+ String numEntriesScannedPostFilter = indexSuggestQueryStatsImpl.getNumEntriesScannedPostFilter();
+ String query = indexSuggestQueryStatsImpl.getQuery();
+ LOGGER.debug("Accumulator: scoring query {}", query);
+
+ AbstractAccumulator.putAccumulatorToMapIfAbsent(accumulatorOut, tableNameWithoutType, NUM_QUERIES_COUNT,
+ new QuantileAnalysisAccumulator()).increaseCount();
+
+ ((QuantileAnalysisAccumulator) AbstractAccumulator.putAccumulatorToMapIfAbsent(accumulatorOut, tableNameWithoutType,
+ QUANTILE_REPORT_KEY, new QuantileAnalysisAccumulator())).merge(Long.parseLong(time),
+ Long.parseLong(numEntriesScannedInFilter), Long.parseLong(numEntriesScannedPostFilter), 0, _lenBin);
+ }
+
+ @Override
+ public void merge(AbstractAccumulator p1, AbstractAccumulator p2) {
+ ((QuantileAnalysisAccumulator) p1).merge((QuantileAnalysisAccumulator) p2);
+ }
+
+ /**
+ * Generate a report for recommendation using tableResults:tableName/colName/AbstractMergerObj
+ * @param tableResults input
+ */
+ @Override
+ public void report(Map<String, Map<String, AbstractAccumulator>> tableResults) {
+ tableResults.forEach((table, map) -> reportTable(table, map));
+ }
+
+ private void reportTable(String tableNameWithoutType, Map<String, AbstractAccumulator> columnStats) {
+ String reportOut = "\n**********************Report For Table: " + tableNameWithoutType + "**********************\n";
+
+ long totalCount = columnStats.remove(NUM_QUERIES_COUNT).getCount();
+ reportOut += MessageFormat.format("\nTotal lines accumulated: {0}\n\n", totalCount);
+
+ if (!columnStats.containsKey(QUANTILE_REPORT_KEY)) {
+ reportOut += "No valid data accumulated!\n";
+ LOGGER.info(reportOut);
+ return;
+ }
+
+ QuantileAnalysisAccumulator olsMergerObj = (QuantileAnalysisAccumulator) columnStats.get(QUANTILE_REPORT_KEY);
+ LOGGER.debug(olsMergerObj.getMinBin().toString());
+
+ double[] timeAll = new double[olsMergerObj.getTimeList().size()];
+ double[] inFilterAll = new double[olsMergerObj.getInFilterList().size()];
+
+ ArrayList<Long> timeList = olsMergerObj.getTimeList();
+ ArrayList<Long> inFilterList = olsMergerObj.getInFilterList();
+ for (int i = 0; i < timeList.size(); i++) {
+ timeAll[i] = timeList.get(i);
+ inFilterAll[i] = inFilterList.get(i);
+ }
+
+ double[] timePercentile = new double[10];
+ Percentile percentile = new Percentile();
+ percentile.setData(timeAll);
+
+ timePercentile[0] = percentile.evaluate(10);
+ timePercentile[1] = percentile.evaluate(20);
+ timePercentile[2] = percentile.evaluate(30);
+ timePercentile[3] = percentile.evaluate(40);
+ timePercentile[4] = percentile.evaluate(50);
+ timePercentile[5] = percentile.evaluate(60);
+ timePercentile[6] = percentile.evaluate(70);
+ timePercentile[7] = percentile.evaluate(80);
+ timePercentile[8] = percentile.evaluate(90);
+ timePercentile[9] = percentile.evaluate(95);
+
+ double[] numEntriesScannedInFilterPercentile = new double[10];
+ percentile = new Percentile();
+ percentile.setData(inFilterAll);
+
+ numEntriesScannedInFilterPercentile[0] = percentile.evaluate(10);
+ numEntriesScannedInFilterPercentile[1] = percentile.evaluate(20);
+ numEntriesScannedInFilterPercentile[2] = percentile.evaluate(30);
+ numEntriesScannedInFilterPercentile[3] = percentile.evaluate(40);
+ numEntriesScannedInFilterPercentile[4] = percentile.evaluate(50);
+ numEntriesScannedInFilterPercentile[5] = percentile.evaluate(60);
+ numEntriesScannedInFilterPercentile[6] = percentile.evaluate(70);
+ numEntriesScannedInFilterPercentile[7] = percentile.evaluate(80);
+ numEntriesScannedInFilterPercentile[8] = percentile.evaluate(90);
+ numEntriesScannedInFilterPercentile[9] = percentile.evaluate(95);
+
+ reportOut += "numEntriesScannedInFilter:\n";
+ reportOut += MessageFormat.format(
+ "10%:{0} | 20%:{1} | 30%:{2} | 40%:{3} | 50%:{4} | 60%:{5} | 70%:{6} | 80%:{7} | 90%:{8} | 95%:{9}\n", String.format("%.0f", numEntriesScannedInFilterPercentile[0]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[1]), String.format("%.0f", numEntriesScannedInFilterPercentile[2]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[3]), String.format("%.0f", numEntriesScannedInFilterPercentile[4]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[5]), String.format("%.0f", numEntriesScannedInFilterPercentile[6]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[7]), String.format("%.0f", numEntriesScannedInFilterPercentile[8]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[9]));
+
+ reportOut += "\nLatency (ms):\n";
+ reportOut += MessageFormat.format(
+ "10%:{0} | 20%:{1} | 30%:{2} | 40%:{3} | 50%:{4} | 60%:{5} | 70%:{6} | 80%:{7} | 90%:{8} | 95%:{9}\n", String.format("%.0f", timePercentile[0]), String.format("%.0f", timePercentile[1]),
+ String.format("%.0f", timePercentile[2]), String.format("%.0f", timePercentile[3]), String.format("%.0f", timePercentile[4]), String.format("%.0f", timePercentile[5]),
+ String.format("%.0f", timePercentile[6]), String.format("%.0f", timePercentile[7]), String.format("%.0f", timePercentile[8]), String.format("%.0f", timePercentile[9]));
+
+ OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
+ regression.setNoIntercept(true);
+
+ double[] time = new double[olsMergerObj.getMinBin().size()];
+ double[][] x_arr = new double[olsMergerObj.getMinBin().size()][2];
+ AtomicInteger iter = new AtomicInteger(0);
+
+ olsMergerObj.getMinBin().forEach((key, val) -> {
+ time[iter.get()] = val._2();
+ x_arr[iter.get()][0] = key._1() * _lenBin + _lenBin / 2;
+ x_arr[iter.get()][1] = key._2() * _lenBin + _lenBin / 2;
+ iter.incrementAndGet();
+ });
+
+ try {
+ regression.newSampleData(time, x_arr);
+ double[] params = regression.estimateRegressionParameters();
+ double rSquared = regression.calculateRSquared();
+ if (rSquared > MODEL_R_SQUARE_THRESHOLD) {
+ reportOut += "\nMaximum Optimization(ms):\n";
+ reportOut += MessageFormat.format(
+ "10%:{0} | 20%:{1} | 30%:{2} | 40%:{3} | 50%:{4} | 60%:{5} | 70%:{6} | 80%:{7} | 90%:{8} | 95%:{9}\n",
+ String.format("%.0f", numEntriesScannedInFilterPercentile[0] * params[0]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[1] * params[0]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[2] * params[0]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[3] * params[0]), String.format("%.0f", numEntriesScannedInFilterPercentile[4] * params[0]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[5] * params[0]), String.format("%.0f", numEntriesScannedInFilterPercentile[6] * params[0]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[7] * params[0]), String.format("%.0f", numEntriesScannedInFilterPercentile[8] * params[0]),
+ String.format("%.0f", numEntriesScannedInFilterPercentile[9] * params[0]));
+ reportOut += MessageFormat.format("\nR-square: {0}\n", rSquared);
+ reportOut += String.format("Params: %s %s\n", Double.toString(params[0]), Double.toString(params[1]));
+ } else {
+ reportOut += "\nunable to predict the optimization boundary of this table!";
+ }
+ } catch (MathIllegalArgumentException | MathArithmeticException e) {
+ reportOut += "\nunable to predict the optimization boundary of this table!";
+ }
+ LOGGER.info(reportOut);
+ }
+
+ /**
+ * Parse and count the total bitmaps used in a query
+ */
+ class DimensionScoring {
+ static final String AND = "AND";
+ static final String OR = "OR";
+ private String _tableNameWithoutType;
+ private MetaManager _metaManager;
+ private String _queryString;
+ private final Logger LOGGER = LoggerFactory.getLogger(DimensionScoring.class);
+
+ DimensionScoring(String tableNameWithoutType, MetaManager metaManager, String queryString) {
+ _tableNameWithoutType = tableNameWithoutType;
+ _metaManager = metaManager;
+ _queryString = queryString;
+ }
+
+ /*
+ * Navigate from root to predicateListContext of whereClauseContext, where all the filtering happens
+ */
+ @NotNull int parseQuery() {
+ LOGGER.debug("Parsing query: {}", _queryString);
+ PQL2Parser.OptionalClauseContext optionalClauseContext = null;
+ PQL2Parser.WhereClauseContext whereClauseContext = null;
+ if (_queryString == null) {
+ return 0;
+ }
+ try {
+ PQL2Lexer lexer = new PQL2Lexer(new ANTLRInputStream(_queryString));
+ PQL2Parser parser = new PQL2Parser(new CommonTokenStream(lexer));
+ ParseTree selectStatement = parser.root().statement().selectStatement();
+ LOGGER.debug("selectStatement: {}", selectStatement.getText());
+
+ for (int i = 0; i < selectStatement.getChildCount(); i++) {
+ if (selectStatement.getChild(i) instanceof PQL2Parser.OptionalClauseContext) {
+ optionalClauseContext = (PQL2Parser.OptionalClauseContext) selectStatement.getChild(i);
+ LOGGER.debug("optionalClauseContext: {}", optionalClauseContext.getText());
+ if (optionalClauseContext.getChild(0) instanceof PQL2Parser.WhereClauseContext) {
+ whereClauseContext = (PQL2Parser.WhereClauseContext) optionalClauseContext.getChild(0);
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ return 0;
+ }
+ if (whereClauseContext == null) {
+ return 0;
+ }
+ LOGGER.debug("whereClauseContext: {}", whereClauseContext.getText());
+
+ return parsePredicateList(whereClauseContext.predicateList());
+ }
+
+ /*
+ * Parse predicate list connected by AND and OR (recursively)
+ * Sum the results of children
+ */
+ int parsePredicateList(PQL2Parser.PredicateListContext predicateListContext) {
+ LOGGER.debug("Parsing predicate list: {}", predicateListContext.getText());
+ if (predicateListContext.getChildCount() == 1) {
+ LOGGER.debug("Parsing parenthesis group");
+ return parsePredicate((PQL2Parser.PredicateContext) predicateListContext.getChild(0));
+ } else if (predicateListContext.getChild(1).getText().toUpperCase().equals(AND) || predicateListContext.getChild(1).getText().toUpperCase().equals(OR)) {
+ LOGGER.debug("Parsing AND/OR list {}", predicateListContext.getText());
+ int childResults = 0;
+ for (int i = 0; i < predicateListContext.getChildCount(); i += 2) {
+ childResults += parsePredicate((PQL2Parser.PredicateContext) predicateListContext.getChild(i));
+ }
+ LOGGER.debug("AND/OR rank: {}", childResults);
+ return childResults;
+ } else {
+ LOGGER.error("Query: " + _queryString + " parsing exception: " + predicateListContext.getText());
+ return 0;
+ }
+ }
+
+ /*
+ * Parse leaf predicates
+ * Count the inverted indices used
+ */
+ int parsePredicate(PQL2Parser.PredicateContext predicateContext) {
+ LOGGER.debug("Parsing predicate: {}", predicateContext.getText());
+ if (predicateContext instanceof PQL2Parser.PredicateParenthesisGroupContext) {
+ PQL2Parser.PredicateParenthesisGroupContext predicateParenthesisGroupContext = (PQL2Parser.PredicateParenthesisGroupContext) predicateContext;
+ return parsePredicateList(predicateParenthesisGroupContext.predicateList());
+ } else if (predicateContext instanceof PQL2Parser.InPredicateContext) {
+ LOGGER.debug("Entering IN clause!");
+ String colName = ((PQL2Parser.InPredicateContext) predicateContext).inClause().expression().getText();
+ if (_metaManager.hasInvertedIndex(_tableNameWithoutType, colName)) {
+ return ((PQL2Parser.InPredicateContext) predicateContext).inClause().literal().size();
+ }
+ return 0;
+ } else if (predicateContext instanceof PQL2Parser.ComparisonPredicateContext) {
+ String colName =
+ ((PQL2Parser.ComparisonPredicateContext) predicateContext).comparisonClause().expression(0).getText();
+ LOGGER.debug("Entering COMP clause!");
+ String comparisonOp = ((PQL2Parser.ComparisonPredicateContext) predicateContext).comparisonClause()
+ .comparisonOperator()
+ .getText();
+ LOGGER.debug("COMP operator {}", comparisonOp);
+ if (comparisonOp.equals("=") || comparisonOp.equals("!=") || comparisonOp.equals("<>")) {
+ if (_metaManager.hasInvertedIndex(_tableNameWithoutType, colName)) {
+ return 1;
+ }
+ }
+ return 0;
+ } else {
+ return 0;
+ }
+ }
+ }
+}
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/TuningStrategy.java b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/TuningStrategy.java
new file mode 100644
index 0000000..7c1980b
--- /dev/null
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/tuner/strategy/TuningStrategy.java
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.tools.tuner.strategy;
+
+import java.util.Map;
+import org.apache.pinot.tools.tuner.meta.manager.MetaManager;
+import org.apache.pinot.tools.tuner.query.src.stats.wrapper.AbstractQueryStats;
+
+
+/**
+ * Recommendation strategy interface.
+ */
+public interface TuningStrategy {
+
+ /**
+ * Filter out irrelevant query stats to target a specific table or specific range of nESI
+ * @param queryStats the stats extracted and parsed from InputIterator
+ */
+ boolean filter(AbstractQueryStats queryStats);
+
+ /**
+ * Accumulate the parsed queryStats to corresponding entry in MapperOut
+ * @param queryStats input, the stats extracted and parsed from InputIterator
+ * @param metaManager input, the metaManager where cardinality info can be get from
+ * @param accumulatorOut output, map of /tableMame: String/columnName: String/AbstractMergerObj
+ */
+ void accumulate(AbstractQueryStats queryStats, MetaManager metaManager,
+ Map<String, Map<String, AbstractAccumulator>> accumulatorOut);
+
+ /**
+ * merge two AbstractMergerObj with same /tableName/colName
+ * @param abstractAccumulator input
+ * @param abstractAccumulatorToMerge input
+ */
+ void merge(AbstractAccumulator abstractAccumulator, AbstractAccumulator abstractAccumulatorToMerge);
+ //Merge two AbstractMergerObj from same /table/column
+
+ /**
+ * Generate a report for recommendation using tableResults:tableName/colName/AbstractMergerObj
+ * @param tableResults input
+ */
+ void report(Map<String, Map<String, AbstractAccumulator>> tableResults);
+ //print results
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org