You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by ai...@apache.org on 2026/10/23 10:36:50 UTC
(doris) branch master updated: [fix](nereids) Support minimum score filters without TopN (#69292)
This is an automated email from the ASF dual-hosted git repository.
airborne12 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new 2524893ea30 [fix](nereids) Support minimum score filters without TopN (#69292)
2524893ea30 is described below
commit 2524893ea30e35d20bfcf81cc819d8a4b7e9d603
Author: Jack <ji...@selectdb.com>
AuthorDate: Fri Oct 23 18:36:40 2026 +0800
[fix](nereids) Support minimum score filters without TopN (#69292)
### What problem does this PR solve?
Issue Number: N/A
Related PR: #69399 (merged; the plan copier fix this PR needs), #69419
(merged; fixes the pre-existing MATCH predicate inference that review of
this PR found)
Problem Summary:
`score()` only worked as `ORDER BY score() LIMIT n` directly above the
scan whose MATCH defines it. A minimum score filter without that TopN
evaluated the unbound `score()` placeholder as zero and silently dropped
every row:
```sql
SELECT id FROM documents
WHERE content MATCH 'apple' AND score() > 0.00001; -- returned nothing
```
`score()` is computed by the olap scan that evaluates the MATCH and
SEARCH predicates of its SELECT. This PR binds `score()` to that scan at
the start of rewrite, makes the scan's expressions read the score, and
rejects every other use with an error that names the rule.
**Supported.** A SELECT that reads one table and has a MATCH or SEARCH
predicate in its WHERE clause can use `score()`:
- in the WHERE clause, as one minimum score: `score() > x` or `score()
>= x` (also `x < score()`, `x <= score()`, and with a FLOAT or DOUBLE
cast);
- in the select list, window functions and ORDER BY, if the SELECT does
not aggregate (with GROUP BY, including GROUPING SETS, ROLLUP and CUBE,
aggregate functions or DISTINCT, `score()` can only be the minimum
score).
A scored SELECT in a subquery, view, CTE or set operation still needs
`ORDER BY score() LIMIT n`, as before. The TopN keeps the predicates of
the outer query out of its scan, e.g. an outer MATCH cannot add to its
score. A correlated subquery cannot call `score()`, because
decorrelation removes that TopN.
**Rejected.** A join, a subquery or a lateral view in the scored SELECT;
a view, CTE or other relation that is not an olap table (a table stream
fails during planning, because its scan is replaced by scans of the
table and of its changes); any other filter on the score (`score() < x`,
`score() = x`, lossy casts, ORs, a second bound); `score()` in
aggregates, GROUP BY, HAVING or QUALIFY; MATCH or SEARCH in HAVING or
QUALIFY of a scored SELECT, also through an alias; `score()` in a
correlated subquery; a SELECT without its own MATCH or SEARCH; a nested
scored SELECT without the TopN.
**How.**
- BE: the scan reads the score in its own expressions. `SegmentIterator`
prepares the score of every row of its row bitmap before the first
batch. It marked only stored columns of a pushed-down expression as
common-expression columns, so an expression on the score alone, e.g.
`score() > 0.5`, was never evaluated (and the scanner had already
removed it from its conjuncts), and an expression that read the score
next to other columns, e.g. a TopN filter on `CAST(score() AS INT)`,
evaluated `Score()` itself, which returns 0. Now the score column is
read with the other common-expression columns, before the expressions
run.
- FE, binding: `BindScoreToOlapScan` replaces `CheckScoreUsage`. It runs
first in rewrite, while subqueries, views and CTEs still have their own
plan nodes, so the analysis classes are as on master. For each SELECT
that calls `score()`, it checks the rules above, adds a score column to
the scan (score limit 0: the scan scores every row it returns) and
replaces the `score()` calls of the SELECT with that column. A table is
a relation, also under the filters analysis puts on it (the delete sign
filter of a UNIQUE table, row policies). Binding after analysis also
covers `* REPLACE (score() AS c)`, alias functions over `score()` and
`ORDER BY` a position, and a UDF named `score` is never mistaken for it.
- FE, rewrite: the minimum score is an ordinary predicate of the scan.
`PushDownScoreTopNIntoOlapScan` pushes a TopN on the score into the
scan, and with it the minimum score, exactly as before this PR (with a
zero score limit when SEARCH has another predicate), because the scan
keeps the best rows of a segment only when no predicate follows. TopN
filter pushdown and MV rewrite need no `score()` cases: a TopN filter
reads the score like any other column, and a materialized view without
the score cannot answer a predicate on it.
- This PR needs the plan copier fix of #69399, which is merged: copying
a scan with virtual columns gave each one two ids and kept the old slot
in the output.
- The BE keeps the score unchanged by MATCH projections:
`SegmentIterator` evaluates them without the score collector.
- `SearchExpression` can be rendered as SQL, which the shape plan logged
at debug level and `EXPLAIN SHAPE PLAN` need.
### Release note
`score()` works in the select list, window functions and ORDER BY of a
SELECT on one table whose WHERE clause has MATCH or SEARCH, with an
optional minimum score `score() > x` or `score() >= x`, without `ORDER
BY score() LIMIT`. A scored SELECT in a subquery, view, CTE or set
operation still needs `ORDER BY score() LIMIT`. Other uses of `score()`
are rejected instead of evaluating it as 0.
---
be/src/storage/segment/segment_iterator.cpp | 74 ++-
be/src/storage/segment/segment_iterator.h | 1 +
.../segment_iterator_apply_index_expr_test.cpp | 29 ++
.../segment_iterator_score_common_expr_test.cpp | 151 ++++++
.../doris/nereids/jobs/executor/Rewriter.java | 8 +-
.../org/apache/doris/nereids/rules/RuleType.java | 2 +-
.../nereids/rules/rewrite/BindScoreToOlapScan.java | 353 ++++++++++++++
.../nereids/rules/rewrite/CheckScoreUsage.java | 115 -----
.../rewrite/PushDownScoreTopNIntoOlapScan.java | 351 ++++----------
.../rewrite/PushDownVectorTopNIntoOlapScan.java | 3 +-
.../trees/expressions/SearchExpression.java | 23 +-
.../doris/nereids/trees/plans/ScoreRangeInfo.java | 11 +
.../org/apache/doris/planner/OlapScanNode.java | 4 +
.../rules/rewrite/BindScoreToOlapScanTest.java | 445 +++++++++++++++++
.../trees/expressions/SearchExpressionTest.java | 27 ++
.../data/ann_index_p0/ann_with_fulltext.out | 8 +-
.../data/inverted_index_p0/test_bm25_score.out | 16 +-
.../inverted_index_p0/test_score_filter_matrix.out | 537 +++++++++++++++++++++
.../inverted_index_p0/test_score_filter_usage.out | 106 ++++
.../suites/ann_index_p0/ann_with_fulltext.groovy | 10 +-
.../inverted_index_p0/test_bm25_score.groovy | 49 +-
.../test_score_filter_matrix.groovy | 224 +++++++++
.../test_score_filter_usage.groovy | 379 +++++++++++++++
23 files changed, 2478 insertions(+), 448 deletions(-)
diff --git a/be/src/storage/segment/segment_iterator.cpp b/be/src/storage/segment/segment_iterator.cpp
index 3b19fb44fde..58a1980c228 100644
--- a/be/src/storage/segment/segment_iterator.cpp
+++ b/be/src/storage/segment/segment_iterator.cpp
@@ -515,17 +515,22 @@ void SegmentIterator::_rebuild_scan_predicate_states() {
void SegmentIterator::_mark_common_expr_states(const VExprSPtr& expr, bool runtime_generated) {
if (expr->is_slot_ref()) {
- const auto ordinal =
- cast_set<ColumnId>(assert_cast<const VSlotRef*>(expr.get())->column_id());
- DORIS_CHECK_LT(ordinal, _schema->num_block_columns());
- _column_states[ordinal].has_common_expr = true;
- _column_states[ordinal].has_runtime_common_expr |= runtime_generated;
- _is_need_expr_eval = true;
+ _mark_common_expr_column(
+ cast_set<ColumnId>(assert_cast<const VSlotRef*>(expr.get())->column_id()),
+ runtime_generated);
return;
}
if (expr->is_virtual_slot_ref()) {
- const auto& virtual_expr =
- assert_cast<const VirtualSlotRef*>(expr.get())->get_virtual_column_expr();
+ const auto* virtual_slot = assert_cast<const VirtualSlotRef*>(expr.get());
+ // The score of every row is prepared before the first batch is read, and Score() itself has
+ // no value, so an expression on the score reads the score column like a stored column.
+ if (_score_runtime != nullptr &&
+ cast_set<size_t>(virtual_slot->column_id()) == _score_runtime->get_dest_column_idx()) {
+ _mark_common_expr_column(cast_set<ColumnId>(virtual_slot->column_id()),
+ runtime_generated);
+ return;
+ }
+ const auto& virtual_expr = virtual_slot->get_virtual_column_expr();
DORIS_CHECK(virtual_expr != nullptr);
_mark_common_expr_states(virtual_expr, runtime_generated);
return;
@@ -535,6 +540,13 @@ void SegmentIterator::_mark_common_expr_states(const VExprSPtr& expr, bool runti
}
}
+void SegmentIterator::_mark_common_expr_column(ColumnId ordinal, bool runtime_generated) {
+ DORIS_CHECK_LT(ordinal, _schema->num_block_columns());
+ _column_states[ordinal].has_common_expr = true;
+ _column_states[ordinal].has_runtime_common_expr |= runtime_generated;
+ _is_need_expr_eval = true;
+}
+
void SegmentIterator::_initialize_predicate_results() {
// Initialize from _col_predicates
for (auto pred : _col_predicates) {
@@ -1429,24 +1441,36 @@ Status SegmentIterator::_apply_index_expr() {
// Evaluate inverted index for virtual column MATCH expressions (projections).
// Unlike common exprs which filter rows, these only compute index result bitmaps
- // for later materialization via fast_execute().
- for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
- if (_row_bitmap.isEmpty()) {
- // Zero surviving rows: the projection column is never materialized,
- // so its whole-segment index evaluation would be pure waste.
- break;
- }
- if (expr_ctx->get_index_context() == nullptr) {
- continue;
- }
- if (Status st = evaluate_with_candidate_policy(expr_ctx); !st.ok()) {
- if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
+ // for later materialization via fast_execute(). They must not add BM25 scores
+ // either: score() and its range filter only reflect the filtering conjuncts.
+ {
+ CollectionSimilarityPtr filter_similarity =
+ _index_query_context != nullptr
+ ? std::exchange(_index_query_context->collection_similarity, nullptr)
+ : nullptr;
+ DEFER({
+ if (_index_query_context != nullptr) {
+ _index_query_context->collection_similarity = filter_similarity;
+ }
+ });
+ for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
+ if (_row_bitmap.isEmpty()) {
+ // Zero surviving rows: the projection column is never materialized,
+ // so its whole-segment index evaluation would be pure waste.
+ break;
+ }
+ if (expr_ctx->get_index_context() == nullptr) {
continue;
- } else {
- LOG(WARNING) << "failed to evaluate inverted index for virtual column expr: "
- << expr_ctx->root()->debug_string()
- << ", error msg: " << st.to_string();
- return st;
+ }
+ if (Status st = evaluate_with_candidate_policy(expr_ctx); !st.ok()) {
+ if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
+ continue;
+ } else {
+ LOG(WARNING) << "failed to evaluate inverted index for virtual column expr: "
+ << expr_ctx->root()->debug_string()
+ << ", error msg: " << st.to_string();
+ return st;
+ }
}
}
}
diff --git a/be/src/storage/segment/segment_iterator.h b/be/src/storage/segment/segment_iterator.h
index 1366dbd07a8..fb1caf9d157 100644
--- a/be/src/storage/segment/segment_iterator.h
+++ b/be/src/storage/segment/segment_iterator.h
@@ -191,6 +191,7 @@ private:
void _init_column_states();
void _rebuild_scan_predicate_states();
void _mark_common_expr_states(const VExprSPtr& expr, bool runtime_generated);
+ void _mark_common_expr_column(ColumnId ordinal, bool runtime_generated);
Status _vec_init_lazy_materialization();
uint32_t segment_id() const { return _segment->id(); }
diff --git a/be/test/storage/segment/segment_iterator_apply_index_expr_test.cpp b/be/test/storage/segment/segment_iterator_apply_index_expr_test.cpp
index d4965950586..86626a49a03 100644
--- a/be/test/storage/segment/segment_iterator_apply_index_expr_test.cpp
+++ b/be/test/storage/segment/segment_iterator_apply_index_expr_test.cpp
@@ -17,6 +17,7 @@
#include <gtest/gtest.h>
+#include <functional>
#include <memory>
#include "common/status.h"
@@ -24,6 +25,8 @@
#include "exprs/vexpr.h"
#include "exprs/vexpr_context.h"
#include "runtime/runtime_state.h"
+#include "storage/index/index_query_context.h"
+#include "storage/index/inverted/query/scoring/collection_similarity.h"
#include "storage/olap_common.h"
#include "storage/schema.h"
#include "storage/segment/column_reader.h"
@@ -52,6 +55,9 @@ public:
}
void set_evaluate_status(Status st) { _eval_status = std::move(st); }
+ void set_on_evaluate(std::function<void()> on_evaluate) {
+ _on_evaluate = std::move(on_evaluate);
+ }
int evaluate_count() const { return _evaluate_count; }
const std::string& expr_name() const override {
@@ -68,11 +74,15 @@ public:
Status evaluate_inverted_index(VExprContext* context, uint32_t segment_num_rows) override {
++_evaluate_count;
+ if (_on_evaluate) {
+ _on_evaluate();
+ }
return _eval_status;
}
private:
Status _eval_status = Status::OK();
+ std::function<void()> _on_evaluate;
int _evaluate_count = 0;
};
@@ -146,6 +156,25 @@ protected:
OlapReaderStatistics _stats;
};
+// A projected MATCH must not add BM25 scores to the ones the filtering conjuncts collect,
+// otherwise a score() range would compare against an inflated score.
+TEST_F(SegmentIteratorApplyIndexExprTest, virtual_column_does_not_collect_scores) {
+ auto similarity = std::make_shared<CollectionSimilarity>();
+ _iter->_index_query_context = std::make_shared<IndexQueryContext>();
+ _iter->_index_query_context->collection_similarity = similarity;
+ auto ctx = make_mock_ctx(Status::OK());
+ bool scoring_visible = true;
+ static_cast<MockEvalExpr*>(ctx->root().get())->set_on_evaluate([&]() {
+ scoring_visible = _iter->_index_query_context->collection_similarity != nullptr;
+ });
+ _iter->_virtual_column_exprs[0] = ctx;
+
+ EXPECT_TRUE(_iter->_apply_index_expr().ok());
+ EXPECT_EQ(1, static_cast<MockEvalExpr*>(ctx->root().get())->evaluate_count());
+ EXPECT_FALSE(scoring_visible);
+ EXPECT_EQ(similarity, _iter->_index_query_context->collection_similarity);
+}
+
// When evaluate_inverted_index returns OK, _apply_index_expr should succeed.
TEST_F(SegmentIteratorApplyIndexExprTest, virtual_column_evaluate_ok) {
_iter->_virtual_column_exprs[0] = make_mock_ctx(Status::OK());
diff --git a/be/test/storage/segment/segment_iterator_score_common_expr_test.cpp b/be/test/storage/segment/segment_iterator_score_common_expr_test.cpp
new file mode 100644
index 00000000000..8f2efb447e1
--- /dev/null
+++ b/be/test/storage/segment/segment_iterator_score_common_expr_test.cpp
@@ -0,0 +1,151 @@
+// 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.
+
+#include <gtest/gtest.h>
+
+#include <memory>
+
+#include "common/status.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/primitive_type.h"
+#include "exprs/score_runtime.h"
+#include "exprs/vexpr.h"
+#include "exprs/vexpr_context.h"
+#include "exprs/virtual_slot_ref.h"
+#include "storage/olap_common.h"
+#include "storage/schema.h"
+#include "storage/tablet/tablet_schema.h"
+
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wkeyword-macro"
+#endif
+#include "storage/segment/segment.h"
+#include "storage/segment/segment_iterator.h"
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+namespace doris::segment_v2 {
+
+namespace {
+
+constexpr ColumnId kScoreColumn = 1;
+
+// Like Score(), an expression that reads no column.
+class NoColumnExpr : public VExpr {
+public:
+ NoColumnExpr() { _data_type = std::make_shared<DataTypeFloat32>(); }
+
+ const std::string& expr_name() const override {
+ static const std::string kName = "NoColumnExpr";
+ return kName;
+ }
+
+ Status execute(VExprContext*, Block*, int*) const override { return Status::OK(); }
+
+ Status execute_column_impl(VExprContext*, const Block*, const Selector*, size_t,
+ ColumnPtr&) const override {
+ return Status::OK();
+ }
+};
+
+TabletSchemaSPtr make_tablet_schema() {
+ TabletSchemaPB schema_pb;
+ schema_pb.set_keys_type(KeysType::DUP_KEYS);
+ auto* key = schema_pb.add_column();
+ key->set_unique_id(0);
+ key->set_name("k0");
+ key->set_type("INT");
+ key->set_is_key(true);
+ key->set_is_nullable(false);
+ auto* score = schema_pb.add_column();
+ score->set_unique_id(1);
+ score->set_name("__score");
+ score->set_type("FLOAT");
+ score->set_is_key(false);
+ score->set_is_nullable(true);
+ auto tablet_schema = std::make_shared<TabletSchema>();
+ tablet_schema->init_from_pb(schema_pb);
+ return tablet_schema;
+}
+
+VExprSPtr make_score_slot() {
+ TExprNode node;
+ node.__set_type(create_type_desc(PrimitiveType::TYPE_FLOAT));
+ node.__set_node_type(TExprNodeType::VIRTUAL_SLOT_REF);
+ node.__set_num_children(0);
+ node.__set_is_nullable(true);
+ TSlotRef slot_ref;
+ slot_ref.__set_slot_id(-1);
+ slot_ref.__set_tuple_id(-1);
+ node.__set_slot_ref(slot_ref);
+
+ auto slot = VirtualSlotRef::create_shared(node);
+ slot->set_virtual_column_expr(std::make_shared<NoColumnExpr>());
+ slot->set_column_id(kScoreColumn);
+ return slot;
+}
+
+} // namespace
+
+class SegmentIteratorScoreCommonExprTest : public testing::Test {
+protected:
+ void SetUp() override {
+ _tablet_schema = make_tablet_schema();
+ _segment =
+ std::make_shared<Segment>(0, RowsetId(), _tablet_schema, InvertedIndexFileInfo());
+ _segment->_num_rows = 100;
+ _read_schema = std::make_shared<ReadSchema>(_tablet_schema->columns());
+ StorageReadOptions opts(_stats);
+ _iter = std::make_unique<SegmentIterator>(_segment, _read_schema, opts);
+ _iter->_column_states.resize(_read_schema->num_read_columns());
+ _score_slot = make_score_slot();
+ }
+
+ OlapReaderStatistics _stats;
+ TabletSchemaSPtr _tablet_schema;
+ std::shared_ptr<Segment> _segment;
+ std::shared_ptr<ReadSchema> _read_schema;
+ std::unique_ptr<SegmentIterator> _iter;
+ VExprSPtr _score_slot;
+};
+
+// The scan prepares the score of every row before the first batch, so an expression on the score,
+// e.g. a TopN filter, reads the score column instead of evaluating Score().
+TEST_F(SegmentIteratorScoreCommonExprTest, expression_on_score_reads_score_column) {
+ _iter->_score_runtime =
+ ScoreRuntime::create_shared(std::make_shared<VExprContext>(_score_slot), false, 0);
+ _iter->_score_runtime->_dest_column_idx = kScoreColumn;
+
+ _iter->_mark_common_expr_states(_score_slot, true);
+
+ EXPECT_TRUE(_iter->_is_need_expr_eval);
+ EXPECT_TRUE(_iter->_column_states[kScoreColumn].has_common_expr);
+ EXPECT_TRUE(_iter->_column_states[kScoreColumn].has_runtime_common_expr);
+ EXPECT_FALSE(_iter->_column_states[0].has_common_expr);
+}
+
+// Any other virtual column is computed from its expression, which reads no column here.
+TEST_F(SegmentIteratorScoreCommonExprTest, other_virtual_column_is_computed) {
+ _iter->_mark_common_expr_states(_score_slot, true);
+
+ EXPECT_FALSE(_iter->_is_need_expr_eval);
+ EXPECT_FALSE(_iter->_column_states[kScoreColumn].has_common_expr);
+}
+
+} // namespace doris::segment_v2
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/executor/Rewriter.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/executor/Rewriter.java
index 6cf3e3e7f82..ef3d22892a8 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/executor/Rewriter.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/executor/Rewriter.java
@@ -38,6 +38,7 @@ import org.apache.doris.nereids.rules.rewrite.AddProjectForVolatileExpression;
import org.apache.doris.nereids.rules.rewrite.AdjustConjunctsReturnType;
import org.apache.doris.nereids.rules.rewrite.AdjustNullable;
import org.apache.doris.nereids.rules.rewrite.AggScalarSubQueryToWindowFunction;
+import org.apache.doris.nereids.rules.rewrite.BindScoreToOlapScan;
import org.apache.doris.nereids.rules.rewrite.BuildAggForUnion;
import org.apache.doris.nereids.rules.rewrite.CTEInline;
import org.apache.doris.nereids.rules.rewrite.CheckAndStandardizeWindowFunctionAndFrame;
@@ -46,7 +47,6 @@ import org.apache.doris.nereids.rules.rewrite.CheckMatchExpression;
import org.apache.doris.nereids.rules.rewrite.CheckMultiDistinct;
import org.apache.doris.nereids.rules.rewrite.CheckPrivileges;
import org.apache.doris.nereids.rules.rewrite.CheckRestorePartition;
-import org.apache.doris.nereids.rules.rewrite.CheckScoreUsage;
import org.apache.doris.nereids.rules.rewrite.ClearContextStatus;
import org.apache.doris.nereids.rules.rewrite.CollectCteConsumerOutput;
import org.apache.doris.nereids.rules.rewrite.CollectFilterAboveConsumer;
@@ -426,6 +426,9 @@ public class Rewriter extends AbstractBatchJobExecutor {
private static final List<RewriteJob> NORMALIZE_PLAN_JOBS = jobs(
topic("Plan Normalization",
+ // Bind score() to its scan while subqueries, views and CTEs still have their own
+ // plan nodes.
+ custom(RuleType.BIND_SCORE_TO_OLAP_SCAN, BindScoreToOlapScan::new),
custom(RuleType.FOLD_CONSTANT_FOR_SQL_CACHE, FoldConstantForSqlCache::new),
// move MergeProjects rule from analyze phase
// because SubqueryToApply and BindSink rule may create extra project node
@@ -804,8 +807,7 @@ public class Rewriter extends AbstractBatchJobExecutor {
topDown(new PushDownVirtualColumnsIntoOlapScan()),
topDown(new PushDownMatchProjectionAsVirtualColumn()),
topic("score optimize",
- topDown(new PushDownScoreTopNIntoOlapScan(),
- new CheckScoreUsage())
+ topDown(new PushDownScoreTopNIntoOlapScan())
),
topic("add projection for join",
custom(RuleType.ADD_PROJECT_FOR_JOIN, AddProjectForJoin::new),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/RuleType.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/RuleType.java
index 05282821d96..e06d4e10cd1 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/RuleType.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/RuleType.java
@@ -344,7 +344,7 @@ public enum RuleType {
PUSH_DOWN_MATCH_PROJECTION_AS_VIRTUAL_COLUMN(RuleTypeClass.REWRITE),
PUSH_DOWN_SCORE_TOPN_INTO_OLAP_SCAN(RuleTypeClass.REWRITE),
PUSH_DOWN_VECTOR_TOPN_INTO_OLAP_SCAN(RuleTypeClass.REWRITE),
- CHECK_SCORE_USAGE(RuleTypeClass.REWRITE),
+ BIND_SCORE_TO_OLAP_SCAN(RuleTypeClass.REWRITE),
OLAP_SCAN_TABLET_PRUNE(RuleTypeClass.REWRITE),
PUSH_AGGREGATE_TO_OLAP_SCAN(RuleTypeClass.REWRITE),
PUSH_COUNT_INTO_UNION_ALL(RuleTypeClass.REWRITE),
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/BindScoreToOlapScan.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/BindScoreToOlapScan.java
new file mode 100644
index 00000000000..b7735089a14
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/BindScoreToOlapScan.java
@@ -0,0 +1,353 @@
+// 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.doris.nereids.rules.rewrite;
+
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.properties.OrderKey;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Match;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Score;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Search;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalApply;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCTEAnchor;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCTEProducer;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalLimit;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalRecursiveUnionAnchor;
+import org.apache.doris.nereids.trees.plans.logical.LogicalRecursiveUnionProducer;
+import org.apache.doris.nereids.trees.plans.logical.LogicalRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalRepeat;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSetOperation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSink;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSort;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+import org.apache.doris.nereids.trees.plans.logical.LogicalView;
+import org.apache.doris.nereids.trees.plans.visitor.CustomRewriter;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * Bind score() to the olap scan that computes it.
+ *
+ * <p>score() is the relevance of a row for the MATCH and SEARCH predicates in the WHERE clause of
+ * its SELECT, and only the olap scan that evaluates those predicates computes it. So score() is
+ * supported in a SELECT that reads one olap table and has a MATCH or SEARCH predicate in its WHERE
+ * clause:
+ * <ul>
+ * <li>in the WHERE clause, as one minimum score: score() > x or score() >= x;</li>
+ * <li>in the select list, window functions and ORDER BY of a SELECT that does not aggregate.</li>
+ * </ul>
+ * A SELECT in a subquery, view, CTE or set operation has to ORDER BY score() with a LIMIT, which keeps
+ * the predicates of the outer query away from its scan. A correlated subquery cannot call score(), because
+ * decorrelation can remove that LIMIT. Any other use of score() is rejected.
+ *
+ * <p>This rule runs before subquery aliases are removed. It adds a score column to the scan, which
+ * scores every row the scan returns, and replaces the score() calls of the SELECT with it, so the
+ * minimum score is a filter on that column. PushDownScoreTopNIntoOlapScan pushes a TopN on the score
+ * into the scan.
+ */
+public class BindScoreToOlapScan implements CustomRewriter {
+ public static final String UNSUPPORTED_SELECT_ERROR = "score() can only be used in a SELECT that reads one "
+ + "table and has a MATCH or SEARCH predicate in its WHERE clause";
+ public static final String NESTED_SELECT_ERROR = "score() in a subquery, view, CTE or set operation "
+ + "requires ORDER BY score() with LIMIT";
+ public static final String CORRELATED_SUBQUERY_ERROR = "score() cannot be used in a correlated subquery";
+ public static final String AGGREGATE_ERROR = "score() can only be used in the WHERE clause of a SELECT "
+ + "with GROUP BY, aggregate functions or DISTINCT";
+ public static final String HAVING_OR_QUALIFY_ERROR = "score(), MATCH and SEARCH cannot be used in HAVING "
+ + "or QUALIFY of a SELECT that calls score()";
+ public static final String ONE_RANGE_ERROR = "Only one score() range predicate is supported in WHERE clause";
+ public static final String RANGE_FORM_ERROR = "score() predicate in WHERE clause must be in the form of "
+ + "'score() > literal' or 'score() >= literal'";
+ public static final String TOP_LEVEL_RANGE_ERROR = "score() predicate must be a top-level AND condition "
+ + "in WHERE clause";
+
+ @Override
+ public Plan rewriteRoot(Plan plan, JobContext jobContext) {
+ if (!plan.anyMatch(node -> callsScore((Plan) node))) {
+ return plan;
+ }
+ return bindSelect(plan, true);
+ }
+
+ /** The score column that this rule added to the scan. */
+ public static Optional<Slot> findScoreSlot(LogicalOlapScan scan) {
+ return scan.getVirtualColumns().stream()
+ .filter(column -> column instanceof Alias && ((Alias) column).child() instanceof Score)
+ .map(NamedExpression::toSlot)
+ .findFirst();
+ }
+
+ private Plan bindSelect(Plan root, boolean outermost) {
+ Plan plan = bindNestedSelects(root);
+ if (!selectCallsScore(plan)) {
+ return plan;
+ }
+ List<Plan> path = pathToScan(plan);
+ if (path.isEmpty()) {
+ throw new AnalysisException(UNSUPPORTED_SELECT_ERROR);
+ }
+ check(path, outermost);
+ return bind(path);
+ }
+
+ private Plan bindNestedSelects(Plan plan) {
+ ImmutableList.Builder<Plan> newChildren = ImmutableList.builderWithExpectedSize(plan.arity());
+ boolean changed = false;
+ for (int i = 0; i < plan.arity(); i++) {
+ Plan child = plan.child(i);
+ // Decorrelation can remove the LIMIT and ORDER BY of a SELECT in a correlated subquery.
+ if (plan instanceof LogicalApply && i == 1 && ((LogicalApply<?, ?>) plan).isCorrelated()
+ && child.anyMatch(node -> callsScore((Plan) node))) {
+ throw new AnalysisException(CORRELATED_SUBQUERY_ERROR);
+ }
+ Plan newChild = startsSelect(plan, i) ? bindSelect(child, false) : bindNestedSelects(child);
+ changed |= newChild != child;
+ newChildren.add(newChild);
+ }
+ return changed ? plan.withChildren(newChildren.build()) : plan;
+ }
+
+ // Subqueries, views, CTEs and the inputs of set operations are SELECTs of their own, a table
+ // alias is not.
+ private static boolean startsSelect(Plan parent, int childIndex) {
+ if (parent instanceof LogicalSubQueryAlias) {
+ return !isTable(parent.child(0));
+ }
+ return parent instanceof LogicalView || parent instanceof LogicalCTEProducer
+ || parent instanceof LogicalSetOperation || parent instanceof LogicalRecursiveUnionAnchor
+ || parent instanceof LogicalRecursiveUnionProducer
+ || parent instanceof LogicalCTEAnchor && childIndex == 0
+ || parent instanceof LogicalApply && childIndex == 1;
+ }
+
+ // A relation, also under the filters that analysis adds to it, e.g. for row policies. A SELECT has
+ // its select list on top.
+ private static boolean isTable(Plan plan) {
+ return plan instanceof LogicalRelation || plan instanceof LogicalFilter && isTable(plan.child(0));
+ }
+
+ private static boolean selectCallsScore(Plan plan) {
+ if (callsScore(plan)) {
+ return true;
+ }
+ for (int i = 0; i < plan.arity(); i++) {
+ if (!startsSelect(plan, i) && selectCallsScore(plan.child(i))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean callsScore(Plan plan) {
+ return plan.getExpressions().stream().anyMatch(expression -> expression.containsType(Score.class));
+ }
+
+ // The plan nodes from the root of the SELECT down to its olap scan; empty when the SELECT reads
+ // anything else than one olap table, e.g. a join, a subquery or a lateral view.
+ private static List<Plan> pathToScan(Plan root) {
+ List<Plan> path = new ArrayList<>();
+ Plan node = root;
+ while (!(node instanceof LogicalOlapScan)) {
+ path.add(node);
+ if (node instanceof LogicalCTEAnchor) {
+ node = node.child(1);
+ } else if (node instanceof LogicalSink || node instanceof LogicalLimit || node instanceof LogicalSort
+ || node instanceof LogicalProject || node instanceof LogicalFilter
+ || node instanceof LogicalAggregate || node instanceof LogicalRepeat
+ || node instanceof LogicalSubQueryAlias && !startsSelect(node, 0)) {
+ node = node.child(0);
+ } else {
+ return ImmutableList.of();
+ }
+ }
+ path.add(node);
+ return path;
+ }
+
+ private static void check(List<Plan> path, boolean outermost) {
+ // The WHERE clause is the filters right above the scan, around its table alias.
+ int clause = path.size() - 2;
+ List<Expression> where = new ArrayList<>();
+ for (; clause >= 0 && (path.get(clause) instanceof LogicalFilter
+ || path.get(clause) instanceof LogicalSubQueryAlias); clause--) {
+ if (path.get(clause) instanceof LogicalFilter) {
+ where.addAll(((LogicalFilter<?>) path.get(clause)).getConjuncts());
+ }
+ }
+ if (where.stream().noneMatch(conjunct -> conjunct.containsType(Match.class, Search.class))) {
+ throw new AnalysisException(UNSUPPORTED_SELECT_ERROR);
+ }
+ List<Expression> ranges = where.stream()
+ .filter(conjunct -> conjunct.containsType(Score.class))
+ .collect(Collectors.toList());
+ if (ranges.size() > 1) {
+ throw new AnalysisException(ONE_RANGE_ERROR);
+ }
+ ranges.forEach(BindScoreToOlapScan::checkRange);
+
+ List<Plan> aboveWhere = path.subList(0, clause + 1);
+ boolean aggregates = aboveWhere.stream().anyMatch(LogicalAggregate.class::isInstance);
+ // HAVING and QUALIFY can also read score(), MATCH and SEARCH through aliases of the SELECT.
+ Set<Slot> scoringAliases = new HashSet<>();
+ for (int i = aboveWhere.size() - 1; i >= 0; i--) {
+ for (Expression expression : aboveWhere.get(i).getExpressions()) {
+ if (expression instanceof NamedExpression
+ && (expression.containsType(Score.class, Match.class, Search.class)
+ || expression.getInputSlots().stream().anyMatch(scoringAliases::contains))) {
+ scoringAliases.add(((NamedExpression) expression).toSlot());
+ }
+ }
+ }
+ for (Plan node : aboveWhere) {
+ if (node instanceof LogicalFilter && ((LogicalFilter<?>) node).getConjuncts().stream().anyMatch(
+ conjunct -> conjunct.containsType(Score.class, Match.class, Search.class)
+ || conjunct.getInputSlots().stream().anyMatch(scoringAliases::contains))) {
+ throw new AnalysisException(HAVING_OR_QUALIFY_ERROR);
+ }
+ if (aggregates && callsScore(node)) {
+ throw new AnalysisException(AGGREGATE_ERROR);
+ }
+ }
+ if (!outermost && !ordersByScoreWithLimit(aboveWhere)) {
+ throw new AnalysisException(NESTED_SELECT_ERROR);
+ }
+ }
+
+ // score() > x or score() >= x, also written x < score() or x <= score(). A cast of score() to
+ // FLOAT or DOUBLE keeps its value.
+ private static void checkRange(Expression conjunct) {
+ if (!(conjunct instanceof ComparisonPredicate)) {
+ throw new AnalysisException(TOP_LEVEL_RANGE_ERROR);
+ }
+ ComparisonPredicate comparison = (ComparisonPredicate) conjunct;
+ boolean scoreAbove = (comparison instanceof GreaterThan || comparison instanceof GreaterThanEqual)
+ && isScore(comparison.left()) && isConstant(comparison.right());
+ boolean scoreBelow = (comparison instanceof LessThan || comparison instanceof LessThanEqual)
+ && isScore(comparison.right()) && isConstant(comparison.left());
+ if (!scoreAbove && !scoreBelow) {
+ throw new AnalysisException(RANGE_FORM_ERROR);
+ }
+ }
+
+ private static boolean isScore(Expression expression) {
+ if (expression instanceof Cast) {
+ return expression.getDataType().isFloatLikeType() && isScore(((Cast) expression).child());
+ }
+ return expression instanceof Score;
+ }
+
+ private static boolean isConstant(Expression expression) {
+ return expression.getInputSlots().isEmpty() && !expression.containsType(Score.class);
+ }
+
+ // A TopN on the score above the SELECT, so that no outer predicate is pushed into the scan. Analysis
+ // restores the select list between LIMIT and ORDER BY when HAVING or ORDER BY reads another column.
+ private static boolean ordersByScoreWithLimit(List<Plan> aboveWhere) {
+ for (int i = 0; i < aboveWhere.size(); i++) {
+ if (!(aboveWhere.get(i) instanceof LogicalLimit)) {
+ continue;
+ }
+ int sort = i + 1;
+ while (sort < aboveWhere.size() && aboveWhere.get(sort) instanceof LogicalProject
+ && ((LogicalProject<?>) aboveWhere.get(sort)).isAllSlots()) {
+ sort++;
+ }
+ if (sort < aboveWhere.size() && aboveWhere.get(sort) instanceof LogicalSort) {
+ List<OrderKey> orderKeys = ((LogicalSort<?>) aboveWhere.get(sort)).getOrderKeys();
+ return orderKeys.size() == 1 && isScoreOrAlias(orderKeys.get(0).getExpr(), aboveWhere);
+ }
+ }
+ return false;
+ }
+
+ private static boolean isScoreOrAlias(Expression expression, List<Plan> aboveWhere) {
+ if (expression instanceof Score) {
+ return true;
+ }
+ return aboveWhere.stream()
+ .filter(LogicalProject.class::isInstance)
+ .flatMap(project -> ((LogicalProject<?>) project).getProjects().stream())
+ .anyMatch(project -> project instanceof Alias && project.toSlot().equals(expression)
+ && ((Alias) project).child() instanceof Score);
+ }
+
+ // Adds the score column to the scan and replaces the score() calls above it with that column.
+ private static Plan bind(List<Plan> path) {
+ LogicalOlapScan scan = (LogicalOlapScan) path.get(path.size() - 1);
+ Alias scoreColumn = new Alias(new Score(), "__score");
+ Slot scoreSlot = scoreColumn.toSlot();
+ // A zero score limit scores every row the scan returns.
+ Plan newPlan = scan.appendVirtualColumnsAndTopN(ImmutableList.of(scoreColumn),
+ scan.getAnnOrderKeys(), scan.getAnnLimit(),
+ ImmutableList.of(new OrderKey(scoreSlot, false, false)), Optional.of(0L), Optional.empty());
+ Function<Expression, Expression> replace = expression -> expression.rewriteDownShortCircuit(
+ node -> node instanceof Score ? scoreSlot : node);
+ for (int i = path.size() - 2; i >= 0; i--) {
+ Plan node = path.get(i);
+ List<Plan> children = new ArrayList<>(node.children());
+ children.set(node instanceof LogicalCTEAnchor ? 1 : 0, newPlan);
+ newPlan = node.withChildren(children);
+ if (newPlan instanceof LogicalFilter) {
+ LogicalFilter<?> filter = (LogicalFilter<?>) newPlan;
+ newPlan = filter.withConjuncts(filter.getConjuncts().stream().map(replace)
+ .collect(ImmutableSet.toImmutableSet()));
+ } else if (newPlan instanceof LogicalSort) {
+ LogicalSort<?> sort = (LogicalSort<?>) newPlan;
+ newPlan = sort.withOrderKeys(sort.getOrderKeys().stream()
+ .map(orderKey -> orderKey.withExpression(replace.apply(orderKey.getExpr())))
+ .collect(ImmutableList.toImmutableList()));
+ } else if (newPlan instanceof LogicalProject) {
+ LogicalProject<?> project = (LogicalProject<?>) newPlan;
+ List<NamedExpression> projects = project.getProjects().stream()
+ .map(expression -> (NamedExpression) replace.apply(expression))
+ .collect(Collectors.toCollection(ArrayList::new));
+ // A node above the projection reads the score, e.g. ORDER BY score().
+ if (path.subList(0, i).stream().anyMatch(BindScoreToOlapScan::callsScore)
+ && !projects.contains(scoreSlot)) {
+ projects.add(scoreSlot);
+ }
+ newPlan = project.withProjects(projects);
+ }
+ }
+ return newPlan;
+ }
+}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckScoreUsage.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckScoreUsage.java
deleted file mode 100644
index e70a3917669..00000000000
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckScoreUsage.java
+++ /dev/null
@@ -1,115 +0,0 @@
-// 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.doris.nereids.rules.rewrite;
-
-import org.apache.doris.nereids.exceptions.AnalysisException;
-import org.apache.doris.nereids.rules.Rule;
-import org.apache.doris.nereids.rules.RuleType;
-import org.apache.doris.nereids.trees.expressions.Alias;
-import org.apache.doris.nereids.trees.expressions.Expression;
-import org.apache.doris.nereids.trees.expressions.functions.scalar.Score;
-import org.apache.doris.nereids.trees.plans.Plan;
-import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
-import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
-import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
-
-import com.google.common.collect.ImmutableList;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-
-import java.util.List;
-
-/**
- * Check score function usage in project and aggregate without proper optimization context.
- *
- * This rule ensures that score() function is used only in contexts where it can be optimized,
- * requiring WHERE clause with MATCH function, ORDER BY and LIMIT.
- */
-public class CheckScoreUsage implements RewriteRuleFactory {
- private static final Logger LOG = LogManager.getLogger(CheckScoreUsage.class);
-
- @Override
- public List<Rule> buildRules() {
- return ImmutableList.of(
- logicalProject(any())
- .when(project -> {
- boolean hasScore = hasScoreFunction(project);
- boolean isOptimized = isScoreAlreadyOptimized(project);
- LOG.debug("Project check - hasScore: " + hasScore + ", isOptimized: " + isOptimized);
- return hasScore && !isOptimized;
- })
- .then(project -> {
- throw new AnalysisException(
- "score() function requires WHERE clause with MATCH function, "
- + "ORDER BY and LIMIT for optimization");
- }).toRule(RuleType.CHECK_SCORE_USAGE),
-
- logicalAggregate(any())
- .when(this::hasScoreInAggregate)
- .then(agg -> {
- throw new AnalysisException(
- "score() function cannot be used in aggregate functions. "
- + "score() requires WHERE clause with MATCH function, "
- + "ORDER BY and LIMIT for optimization");
- }).toRule(RuleType.CHECK_SCORE_USAGE)
- );
- }
-
- private boolean hasScoreFunction(LogicalProject<?> project) {
- return project.getProjects().stream()
- .anyMatch(projection -> {
- if (projection instanceof Alias) {
- return containsScoreFunction(((Alias) projection).child());
- }
- return false;
- });
- }
-
- private boolean hasScoreInAggregate(LogicalAggregate<?> agg) {
- boolean hasScoreInOutput = agg.getOutputExpressions().stream()
- .anyMatch(this::containsScoreFunction);
-
- boolean hasScoreInGroupBy = agg.getGroupByExpressions().stream()
- .anyMatch(this::containsScoreFunction);
-
- return hasScoreInOutput || hasScoreInGroupBy;
- }
-
- private boolean containsScoreFunction(Expression expr) {
- if (expr instanceof Score) {
- return true;
- }
- return expr.children().stream().anyMatch(this::containsScoreFunction);
- }
-
- private boolean isScoreAlreadyOptimized(LogicalProject<?> project) {
- Plan child = project.child();
- if (child instanceof LogicalOlapScan) {
- LogicalOlapScan scan = (LogicalOlapScan) child;
- return scan.getVirtualColumns().stream()
- .anyMatch(virtualCol -> {
- if (virtualCol instanceof Alias) {
- Expression childExpr = ((Alias) virtualCol).child();
- return containsScoreFunction(childExpr);
- }
- return false;
- });
- }
- return false;
- }
-}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownScoreTopNIntoOlapScan.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownScoreTopNIntoOlapScan.java
index c02b9a1591c..ae2a41d5131 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownScoreTopNIntoOlapScan.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownScoreTopNIntoOlapScan.java
@@ -18,6 +18,7 @@
package org.apache.doris.nereids.rules.rewrite;
import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.properties.OrderKey;
import org.apache.doris.nereids.rules.Rule;
import org.apache.doris.nereids.rules.RuleType;
import org.apache.doris.nereids.trees.expressions.Alias;
@@ -28,11 +29,9 @@ import org.apache.doris.nereids.trees.expressions.GreaterThan;
import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
import org.apache.doris.nereids.trees.expressions.LessThan;
import org.apache.doris.nereids.trees.expressions.LessThanEqual;
-import org.apache.doris.nereids.trees.expressions.Match;
import org.apache.doris.nereids.trees.expressions.NamedExpression;
import org.apache.doris.nereids.trees.expressions.SearchExpression;
-import org.apache.doris.nereids.trees.expressions.SlotReference;
-import org.apache.doris.nereids.trees.expressions.functions.scalar.Score;
+import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.expressions.literal.DecimalV3Literal;
import org.apache.doris.nereids.trees.expressions.literal.DoubleLiteral;
import org.apache.doris.nereids.trees.expressions.literal.FloatLiteral;
@@ -43,51 +42,26 @@ import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
import org.apache.doris.nereids.trees.plans.logical.LogicalTopN;
-import org.apache.doris.nereids.util.ExpressionUtils;
import org.apache.doris.nereids.util.Utils;
import org.apache.doris.thrift.TExprOpcode;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Maps;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
import java.util.List;
-import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
- * Push down score function into olap scan node.
- * It will push down score function as a virtual column, and also push down the
- * topN info.
+ * Limit the scoring of a scan to the rows that a TopN on its score keeps.
*
- * Pattern:
- * logicalTopN(logicalProject(logicalFilter(logicalOlapScan)))
- *
- * Requirements:
- * 1. The TopN node has exactly one ordering expression.
- * 2. The ordering expression in TopN must be a slot reference that refers to a
- * Score function.
- * 3. The Filter node must contain at least one Match function.
- *
- * Additionally, this rule now supports score range predicates in WHERE clause:
- * - score() > X, score() >= X, score() < X, score() <= X
- * These predicates are extracted and pushed down to the scan node.
- *
- * Example:
- * Before:
- * SELECT score() as score FROM table WHERE text_col MATCH 'query' AND score() > 0.5
- * ORDER BY score DESC LIMIT 10
- *
- * After:
- * The Score function is pushed down into the OlapScan node as a virtual column,
- * and the TopN information (order by, limit) is also pushed down to be used by
- * the storage engine. The score range predicate is also extracted.
+ * <p>BindScoreToOlapScan makes the scan score every row it returns. When a TopN orders the rows of
+ * the scan by the score alone, the scan can keep the best rows of each segment instead, and SEARCH
+ * can skip documents that cannot reach them. The scan keeps the best rows only when no filter
+ * follows it, so it also takes over a minimum score of the filter, as before score() could be used
+ * without a TopN.
*/
public class PushDownScoreTopNIntoOlapScan implements RewriteRuleFactory {
- private static final Logger LOG = LogManager.getLogger(PushDownScoreTopNIntoOlapScan.class);
@Override
public List<Rule> buildRules() {
@@ -96,266 +70,117 @@ public class PushDownScoreTopNIntoOlapScan implements RewriteRuleFactory {
.then(topN -> {
LogicalProject<LogicalFilter<LogicalOlapScan>> project = topN.child();
LogicalFilter<LogicalOlapScan> filter = project.child();
- LogicalOlapScan scan = filter.child();
- return pushDown(topN, project, filter, scan);
- }).toRule(RuleType.PUSH_DOWN_SCORE_TOPN_INTO_OLAP_SCAN));
+ return pushDown(topN, Optional.of(project), filter).map(newFilter ->
+ topN.withChildren(project.withChildren(newFilter))).orElse(null);
+ }).toRule(RuleType.PUSH_DOWN_SCORE_TOPN_INTO_OLAP_SCAN),
+ logicalTopN(logicalFilter(logicalOlapScan()))
+ .then(topN -> pushDown(topN, Optional.empty(), topN.child())
+ .map(topN::withChildren).orElse(null))
+ .toRule(RuleType.PUSH_DOWN_SCORE_TOPN_INTO_OLAP_SCAN));
}
- private Plan pushDown(
- LogicalTopN<LogicalProject<LogicalFilter<LogicalOlapScan>>> topN,
- LogicalProject<LogicalFilter<LogicalOlapScan>> project,
- LogicalFilter<LogicalOlapScan> filter,
- LogicalOlapScan scan) {
- // 1. Requirement: Project must contain a score() function.
- boolean hasScoreFunction = project.getProjects().stream()
- .anyMatch(projection -> {
- if (projection instanceof Alias) {
- return ((Alias) projection).child() instanceof Score;
- }
- return false;
- });
- if (!hasScoreFunction) {
- return null;
- }
-
- // 2. Requirement: WHERE clause must contain a MATCH or SEARCH function.
- boolean hasMatchOrSearchPredicate = filter.getConjuncts().stream()
- .anyMatch(conjunct -> !conjunct.collect(
- e -> e instanceof Match || e instanceof SearchExpression).isEmpty());
- if (!hasMatchOrSearchPredicate) {
- throw new AnalysisException(
- "WHERE clause must contain at least one MATCH or SEARCH function"
- + " for score() push down optimization");
- }
-
- // 3. Check for score() predicates in WHERE clause and extract score range info
- List<Expression> scorePredicates = filter.getConjuncts().stream()
- .filter(conjunct -> !conjunct.collect(e -> e instanceof Score).isEmpty())
- .collect(ImmutableList.toImmutableList());
-
- Optional<ScoreRangeInfo> scoreRangeInfo = Optional.empty();
- Expression extractedScorePredicate = null;
- if (!scorePredicates.isEmpty()) {
- if (scorePredicates.size() > 1) {
- throw new AnalysisException(
- "Only one score() range predicate is supported in WHERE clause. "
- + "Found " + scorePredicates.size() + " predicates: " + scorePredicates);
- }
- Expression predicate = scorePredicates.get(0);
- scoreRangeInfo = extractScoreRangeInfo(predicate);
- if (!scoreRangeInfo.isPresent()) {
- throw new AnalysisException(
- "score() predicate in WHERE clause must be in the form of 'score() > literal' "
- + "or 'score() >= literal' (min_score semantics). "
- + "Operators <, <=, and = are not supported.");
- }
- extractedScorePredicate = predicate;
- }
-
- // 4. Requirement: TopN must have exactly one ordering expression.
- if (topN.getOrderKeys().size() != 1) {
- throw new AnalysisException(
- "TopN must have exactly one ordering expression for score() push down optimization");
- }
-
- // 5. Requirement: ORDER BY expression must refer to a SELECT score() alias.
- Expression orderKey = topN.getOrderKeys().get(0).getExpr();
- if (!(orderKey instanceof SlotReference)) {
- throw new AnalysisException(
- "ORDER BY expression must be a slot reference (not a function call or complex expression)"
- + " for score() push down optimization");
- }
-
- SlotReference orderSlot = (SlotReference) orderKey;
- Expression scoreExpr = null;
- Alias scoreAlias = null;
-
- // Find the 'score()' expression in the project list that matches the order by
- // slot.
- for (NamedExpression projection : project.getProjects()) {
- if (projection.toSlot().equals(orderSlot) && projection instanceof Alias) {
- Expression childExpr = ((Alias) projection).child();
- if (childExpr instanceof Score) {
- scoreExpr = childExpr;
- scoreAlias = (Alias) projection;
- break;
- }
- }
+ private Optional<Plan> pushDown(LogicalTopN<?> topN, Optional<LogicalProject<?>> project,
+ LogicalFilter<LogicalOlapScan> filter) {
+ LogicalOlapScan scan = filter.child();
+ Optional<Slot> scoreSlot = BindScoreToOlapScan.findScoreSlot(scan);
+ if (!scoreSlot.isPresent() || !scan.getScoreLimit().equals(Optional.of(0L))
+ || scan.getScoreRangeInfo().isPresent() || topN.getOrderKeys().size() != 1) {
+ return Optional.empty();
}
-
- if (scoreAlias == null) {
- throw new AnalysisException(
- "ORDER BY expression must reference a score() function from SELECT clause"
- + " for push down optimization");
+ OrderKey orderKey = topN.getOrderKeys().get(0);
+ if (!ordersByScore(orderKey.getExpr(), project, scoreSlot.get())) {
+ return Optional.empty();
}
-
// When limit + offset overflows the long range, the pushed scan limit would wrap to a
- // negative value. Fail with the same error as ordinary TopN instead of leaving score()
- // unmaterialized and reporting an unrelated score() usage error.
+ // negative value. Fail with the same error as ordinary TopN.
if (Utils.addOverflows(topN.getLimit(), topN.getOffset())) {
throw new AnalysisException("limit + offset overflows the long range");
}
-
- long scoreLimit = topN.getLimit() + topN.getOffset();
- long pushedScoreLimit = shouldDisableSearchTopN(filter.getConjuncts(), extractedScorePredicate)
- ? 0L : scoreLimit;
-
- // All conditions met, perform the push down.
- // This is the core action: push score() as a virtual column and also push the
- // topN info.
- Plan newScan = scan.appendVirtualColumnsAndTopN(ImmutableList.of(scoreAlias),
- ImmutableList.of(), Optional.empty(),
- topN.getOrderKeys(), Optional.of(pushedScoreLimit),
- scoreRangeInfo);
-
- // Rebuild the plan tree above the new scan.
- // We need to replace the original score() function with a reference to the new
- // virtual column slot.
- Map<Expression, Expression> replaceMap = Maps.newHashMap();
- replaceMap.put(scoreExpr, scoreAlias.toSlot());
- replaceMap.put(scoreAlias, scoreAlias.toSlot());
-
- // If we extracted a score predicate, remove it from the filter
- // as it will be pushed down to the scan node
- Set<Expression> newConjuncts;
- if (extractedScorePredicate != null) {
- final Expression predicateToRemove = extractedScorePredicate;
- newConjuncts = filter.getConjuncts().stream()
- .filter(c -> !c.equals(predicateToRemove))
- .collect(ImmutableSet.toImmutableSet());
- } else {
- newConjuncts = filter.getConjuncts();
+ Optional<Expression> minimum = filter.getConjuncts().stream()
+ .filter(conjunct -> extractScoreRange(conjunct, scoreSlot.get()).isPresent())
+ .findFirst();
+ Set<Expression> conjuncts = filter.getConjuncts().stream()
+ .filter(conjunct -> !minimum.equals(Optional.of(conjunct)))
+ .collect(ImmutableSet.toImmutableSet());
+ // A zero limit keeps scoring every row, and the scan applies the minimum score.
+ long limit = searchNeedsAllScores(conjuncts) ? 0 : topN.getLimit() + topN.getOffset();
+ if (limit == 0 && !minimum.isPresent()) {
+ return Optional.empty();
}
+ LogicalOlapScan newScan = scan.appendVirtualColumnsAndTopN(ImmutableList.of(),
+ scan.getAnnOrderKeys(), scan.getAnnLimit(),
+ ImmutableList.of(new OrderKey(scoreSlot.get(), orderKey.isAsc(), orderKey.isNullFirst())),
+ Optional.of(limit), minimum.flatMap(conjunct -> extractScoreRange(conjunct, scoreSlot.get())));
+ return Optional.of(conjuncts.isEmpty() ? newScan : filter.withConjunctsAndChild(conjuncts, newScan));
+ }
- // The filter node remains, as the MATCH predicate is still needed.
- Plan newFilter;
- if (newConjuncts.isEmpty()) {
- newFilter = newScan;
- } else {
- newFilter = filter.withConjunctsAndChild(newConjuncts, newScan);
+ private static boolean ordersByScore(Expression orderExpr, Optional<LogicalProject<?>> project, Slot scoreSlot) {
+ if (orderExpr.equals(scoreSlot)) {
+ return true;
}
-
- // Rebuild project list with the replaced expressions.
- List<NamedExpression> newProjections = ExpressionUtils
- .replaceNamedExpressions(project.getProjects(), replaceMap);
- Plan newProject = project.withProjectsAndChild(newProjections, newFilter);
-
- // Rebuild the TopN node on top of the new project.
- return topN.withChildren(newProject);
+ if (!project.isPresent() || !(orderExpr instanceof Slot)) {
+ return false;
+ }
+ for (NamedExpression projection : project.get().getProjects()) {
+ if (projection.toSlot().equals(orderExpr)) {
+ return projection instanceof Alias && ((Alias) projection).child().equals(scoreSlot);
+ }
+ }
+ return false;
}
- private boolean shouldDisableSearchTopN(Set<Expression> conjuncts, Expression extractedScorePredicate) {
- List<Expression> nonScoreConjuncts = conjuncts.stream()
- .filter(conjunct -> extractedScorePredicate == null || !conjunct.equals(extractedScorePredicate))
- .collect(ImmutableList.toImmutableList());
-
- boolean hasSearchPredicate = nonScoreConjuncts.stream()
- .anyMatch(conjunct -> !conjunct.collect(e -> e instanceof SearchExpression).isEmpty());
- if (!hasSearchPredicate) {
+ // SEARCH skips documents that cannot reach the top only when it is the only predicate of the
+ // scan: another predicate could drop the documents it keeps.
+ private static boolean searchNeedsAllScores(Set<Expression> conjuncts) {
+ if (conjuncts.stream().noneMatch(conjunct -> conjunct.containsType(SearchExpression.class))) {
return false;
}
- return nonScoreConjuncts.size() > 1 || !(nonScoreConjuncts.get(0) instanceof SearchExpression);
+ return conjuncts.size() > 1 || !(conjuncts.iterator().next() instanceof SearchExpression);
}
- /**
- * Extract score range info from a single score predicate.
- * Only supports min_score semantics (similar to Elasticsearch):
- * - score() > X or score() >= X
- * - Reversed patterns: X < score() or X <= score()
- *
- * Note: < and <= are NOT supported because max_score filtering is rarely needed.
- * Note: EqualTo (=) is NOT supported.
- */
- private Optional<ScoreRangeInfo> extractScoreRangeInfo(Expression predicate) {
+ // A minimum score: score > x or score >= x, also written x < score or x <= score.
+ private static Optional<ScoreRangeInfo> extractScoreRange(Expression predicate, Slot scoreSlot) {
if (!(predicate instanceof ComparisonPredicate)) {
- if (!predicate.collect(e -> e instanceof Score).isEmpty()) {
- throw new AnalysisException(
- "score() predicate must be a top-level AND condition in WHERE clause. "
- + "Nesting score() inside OR or other compound expressions is not supported. "
- + "Invalid expression: " + predicate.toSql());
- }
return Optional.empty();
}
-
- ComparisonPredicate comp = (ComparisonPredicate) predicate;
- Expression left = comp.left();
- Expression right = comp.right();
-
- if (isScoreExpression(left) && isNumericLiteral(right)) {
- TExprOpcode op = getMinScoreOpcode(comp);
- if (op != null) {
- return Optional.of(new ScoreRangeInfo(op, extractNumericValue(right)));
+ ComparisonPredicate comparison = (ComparisonPredicate) predicate;
+ if (isScore(comparison.left(), scoreSlot) && isNumericLiteral(comparison.right())) {
+ if (comparison instanceof GreaterThan) {
+ return Optional.of(new ScoreRangeInfo(TExprOpcode.GT, numericValue(comparison.right())));
+ } else if (comparison instanceof GreaterThanEqual) {
+ return Optional.of(new ScoreRangeInfo(TExprOpcode.GE, numericValue(comparison.right())));
}
- }
-
- if (isScoreExpression(right) && isNumericLiteral(left)) {
- TExprOpcode op = getReversedMinScoreOpcode(comp);
- if (op != null) {
- return Optional.of(new ScoreRangeInfo(op, extractNumericValue(left)));
+ } else if (isScore(comparison.right(), scoreSlot) && isNumericLiteral(comparison.left())) {
+ if (comparison instanceof LessThan) {
+ return Optional.of(new ScoreRangeInfo(TExprOpcode.GT, numericValue(comparison.left())));
+ } else if (comparison instanceof LessThanEqual) {
+ return Optional.of(new ScoreRangeInfo(TExprOpcode.GE, numericValue(comparison.left())));
}
}
-
return Optional.empty();
}
- /**
- * Check if the expression is a Score function, possibly wrapped in Cast expressions.
- * The optimizer may wrap score() in Cast for type coercion (e.g., score() >= 4.0 may become
- * CAST(score() AS DECIMAL) >= 4.0).
- */
- private boolean isScoreExpression(Expression expr) {
- if (expr instanceof Score) {
- return true;
- }
- if (expr instanceof Cast) {
- return isScoreExpression(((Cast) expr).child());
+ // The score column, or a FLOAT or DOUBLE cast of it, which keeps its value.
+ private static boolean isScore(Expression expression, Slot scoreSlot) {
+ if (expression instanceof Cast) {
+ return expression.getDataType().isFloatLikeType() && isScore(((Cast) expression).child(), scoreSlot);
}
- return false;
+ return expression.equals(scoreSlot);
}
- private boolean isNumericLiteral(Expression expr) {
- return expr instanceof DoubleLiteral
- || expr instanceof FloatLiteral
- || expr instanceof IntegerLikeLiteral
- || expr instanceof DecimalV3Literal;
- }
-
- private double extractNumericValue(Expression expr) {
- if (expr instanceof DoubleLiteral) {
- return ((DoubleLiteral) expr).getValue();
- } else if (expr instanceof FloatLiteral) {
- return ((FloatLiteral) expr).getValue();
- } else if (expr instanceof IntegerLikeLiteral) {
- return ((IntegerLikeLiteral) expr).getLongValue();
- } else if (expr instanceof DecimalV3Literal) {
- return ((DecimalV3Literal) expr).getDouble();
- }
- throw new IllegalArgumentException("Not a numeric literal: " + expr);
- }
-
- /**
- * Get opcode for min_score patterns: score() > X or score() >= X
- * Returns null for unsupported operators (< and <=)
- */
- private TExprOpcode getMinScoreOpcode(ComparisonPredicate comp) {
- if (comp instanceof GreaterThan) {
- return TExprOpcode.GT;
- } else if (comp instanceof GreaterThanEqual) {
- return TExprOpcode.GE;
- }
- return null;
+ private static boolean isNumericLiteral(Expression expression) {
+ return expression instanceof DoubleLiteral || expression instanceof FloatLiteral
+ || expression instanceof IntegerLikeLiteral || expression instanceof DecimalV3Literal;
}
- /**
- * Get the reversed opcode for min_score patterns like "0.5 < score()" (equivalent to "score() > 0.5")
- * Returns null for unsupported operators
- */
- private TExprOpcode getReversedMinScoreOpcode(ComparisonPredicate comp) {
- if (comp instanceof LessThan) {
- return TExprOpcode.GT;
- } else if (comp instanceof LessThanEqual) {
- return TExprOpcode.GE;
+ private static double numericValue(Expression literal) {
+ if (literal instanceof DoubleLiteral) {
+ return ((DoubleLiteral) literal).getValue();
+ } else if (literal instanceof FloatLiteral) {
+ return ((FloatLiteral) literal).getValue();
+ } else if (literal instanceof IntegerLikeLiteral) {
+ return ((IntegerLikeLiteral) literal).getLongValue();
}
- return null;
+ return ((DecimalV3Literal) literal).getDouble();
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownVectorTopNIntoOlapScan.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownVectorTopNIntoOlapScan.java
index 597f331e28d..68b3075d49d 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownVectorTopNIntoOlapScan.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownVectorTopNIntoOlapScan.java
@@ -153,10 +153,11 @@ public class PushDownVectorTopNIntoOlapScan implements RewriteRuleFactory {
return null;
}
+ // Keep the score that BindScoreToOlapScan bound to the scan.
Plan plan = scan.appendVirtualColumnsAndTopN(
ImmutableList.of(orderKeyAlias),
topN.getOrderKeys(), Optional.of(topN.getLimit() + topN.getOffset()),
- ImmutableList.of(), Optional.empty(), Optional.empty());
+ scan.getScoreOrderKeys(), scan.getScoreLimit(), scan.getScoreRangeInfo());
Map<Expression, Expression> replaceMap = Maps.newHashMap();
replaceMap.put(orderKeyAlias, orderKeyAlias.toSlot());
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/SearchExpression.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/SearchExpression.java
index 5767d72bedd..32b9e3d5092 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/SearchExpression.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/SearchExpression.java
@@ -23,9 +23,11 @@ import org.apache.doris.nereids.trees.expressions.functions.scalar.ElementAt;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.BooleanType;
import org.apache.doris.nereids.types.DataType;
+import org.apache.doris.nereids.util.SqlLiteralUtils;
import java.util.List;
import java.util.Objects;
+import java.util.Optional;
/**
* SearchExpression represents a search query with bound slot references.
@@ -33,11 +35,20 @@ import java.util.Objects;
*/
public class SearchExpression extends Expression {
private final String dslString;
+ // The second argument of search(dsl, options), kept so that toSql() reproduces the call.
+ private final Optional<String> optionsJson;
private final SearchDslParser.QsPlan qsPlan;
public SearchExpression(String dslString, SearchDslParser.QsPlan qsPlan, List<Expression> slotChildren) {
+ this(dslString, Optional.empty(), qsPlan, slotChildren);
+ }
+
+ /** Create a bound search expression that keeps the options argument of search(dsl, options). */
+ public SearchExpression(String dslString, Optional<String> optionsJson, SearchDslParser.QsPlan qsPlan,
+ List<Expression> slotChildren) {
super(slotChildren);
this.dslString = Objects.requireNonNull(dslString, "dslString cannot be null");
+ this.optionsJson = Objects.requireNonNull(optionsJson, "optionsJson cannot be null");
this.qsPlan = Objects.requireNonNull(qsPlan, "qsPlan cannot be null");
}
@@ -79,7 +90,7 @@ public class SearchExpression extends Expression {
"SearchExpression children must be SlotReference or ElementAt instances");
}
}
- return new SearchExpression(dslString, qsPlan, children);
+ return new SearchExpression(dslString, optionsJson, qsPlan, children);
}
@Override
@@ -92,6 +103,13 @@ public class SearchExpression extends Expression {
return "search('" + dslString + "')";
}
+ @Override
+ protected String computeToSql() {
+ StringBuilder sql = new StringBuilder("search(").append(SqlLiteralUtils.quoteStringLiteral(dslString));
+ optionsJson.ifPresent(options -> sql.append(", ").append(SqlLiteralUtils.quoteStringLiteral(options)));
+ return sql.append(")").toString();
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
@@ -105,11 +123,12 @@ public class SearchExpression extends Expression {
}
SearchExpression that = (SearchExpression) o;
return Objects.equals(dslString, that.dslString)
+ && Objects.equals(optionsJson, that.optionsJson)
&& Objects.equals(qsPlan, that.qsPlan);
}
@Override
public int hashCode() {
- return Objects.hash(super.hashCode(), dslString, qsPlan);
+ return Objects.hash(super.hashCode(), dslString, optionsJson, qsPlan);
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/ScoreRangeInfo.java b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/ScoreRangeInfo.java
index 097eb6911eb..354d2585844 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/ScoreRangeInfo.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/ScoreRangeInfo.java
@@ -20,6 +20,8 @@ package org.apache.doris.nereids.trees.plans;
import org.apache.doris.thrift.TExprOpcode;
import org.apache.doris.thrift.TScoreRangeInfo;
+import com.google.common.base.Preconditions;
+
import java.util.Objects;
/**
@@ -44,6 +46,15 @@ public class ScoreRangeInfo {
return threshold;
}
+ /**
+ * Render the pushed predicate for EXPLAIN, e.g. "score() > 0.5".
+ */
+ public String toSql() {
+ Preconditions.checkState(op == TExprOpcode.GT || op == TExprOpcode.GE,
+ "score range only supports > and >=, but got %s", op);
+ return "score() " + (op == TExprOpcode.GT ? ">" : ">=") + " " + threshold;
+ }
+
/**
* Convert to Thrift representation for sending to BE.
*/
diff --git a/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java b/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java
index 76a715a339f..a975f8f2bf3 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java
@@ -1286,6 +1286,10 @@ public class OlapScanNode extends ScanNode {
if (scoreSortLimit != -1) {
output.append(prefix).append("SCORE SORT LIMIT: ").append(scoreSortLimit).append("\n");
}
+ if (scoreRangeInfo != null) {
+ // The pushed score predicate is no longer among the scan conjuncts.
+ output.append(prefix).append("SCORE RANGE: ").append(scoreRangeInfo.toSql()).append("\n");
+ }
if (annSortInfo != null) {
output.append(prefix).append("ANN SORT INFO:\n");
diff --git a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/BindScoreToOlapScanTest.java b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/BindScoreToOlapScanTest.java
new file mode 100644
index 00000000000..734e9188a96
--- /dev/null
+++ b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/BindScoreToOlapScanTest.java
@@ -0,0 +1,445 @@
+// 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.doris.nereids.rules.rewrite;
+
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Score;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.PlanChecker;
+import org.apache.doris.planner.OlapScanNode;
+import org.apache.doris.thrift.TPlanNode;
+import org.apache.doris.utframe.TestWithFeService;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+class BindScoreToOlapScanTest extends TestWithFeService {
+ @Override
+ protected void runBeforeAll() throws Exception {
+ createDatabase("score_usage");
+ connectContext.setDatabase("score_usage");
+ connectContext.getSessionVariable().setDisableNereidsRules("PRUNE_EMPTY_PARTITION");
+ for (String format : new String[] {"V2", "V3", "SNII"}) {
+ createTable("CREATE TABLE score_usage_" + format + " ("
+ + "id INT, c1 TEXT, c2 TEXT, "
+ + "INDEX idx_c1 (c1) USING INVERTED PROPERTIES "
+ + "('parser' = 'english', 'lower_case' = 'true', 'support_phrase' = 'true')) "
+ + "DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1 "
+ + "PROPERTIES ('replication_num' = '1', "
+ + "'inverted_index_storage_format' = '" + format + "')");
+ }
+ createTable("CREATE TABLE score_usage_ann ("
+ + "id INT NOT NULL, c1 TEXT, embedding ARRAY<FLOAT> NOT NULL, "
+ + "INDEX idx_c1 (c1) USING INVERTED PROPERTIES ('parser' = 'english'), "
+ + "INDEX idx_ann (embedding) USING ANN PROPERTIES "
+ + "('index_type' = 'hnsw', 'metric_type' = 'l2_distance', 'dim' = '2')) "
+ + "DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1 "
+ + "PROPERTIES ('replication_num' = '1', 'inverted_index_storage_format' = 'V3')");
+ createView("CREATE VIEW score_usage_top AS SELECT id, score() AS s FROM score_usage_V2"
+ + " WHERE c1 MATCH 'apple' ORDER BY s DESC LIMIT 2");
+ createTable("CREATE TABLE score_usage_mow (id INT, c1 TEXT, "
+ + "INDEX idx_c1 (c1) USING INVERTED PROPERTIES ('parser' = 'english')) "
+ + "UNIQUE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1 "
+ + "PROPERTIES ('replication_num' = '1', 'enable_unique_key_merge_on_write' = 'true')");
+ }
+
+ static Stream<Arguments> scoringPredicates() {
+ return Stream.of("V2", "V3", "SNII").flatMap(format -> Stream.of(
+ Arguments.of(format, "c1 MATCH 'apple'"),
+ Arguments.of(format, "search('c1:apple')")));
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testMinimumScoreIsAFilterOfTheScan(String format, String predicate) {
+ for (String range : new String[] {"score() > 0.00001", "0.00001 < score()",
+ "CAST(score() AS DOUBLE) > 0.00001", "CAST(score() AS FLOAT) > 0.00001",
+ "score() >= 0.00001", "0.00001 <= score()"}) {
+ assertMinimumScore("SELECT id FROM score_usage_" + format + " WHERE " + predicate + " AND " + range, 1);
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testScoreInSelectListAndOrderBy(String format, String predicate) {
+ String from = " FROM score_usage_" + format + " WHERE " + predicate + " AND score() > 0.00001";
+ assertMinimumScore("SELECT id, score() AS s" + from, 2);
+ assertMinimumScore("SELECT id, score() AS first_score, score() AS second_score" + from, 3);
+ for (String suffix : new String[] {" LIMIT 10", " ORDER BY id LIMIT 1 OFFSET 1",
+ " ORDER BY s DESC, id LIMIT 1 OFFSET 1", " ORDER BY s DESC"}) {
+ assertMinimumScore("SELECT id, c2, score() AS s" + from + suffix, 3);
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testScoreWithoutMinimumScoresEveryRow(String format, String predicate) {
+ for (String suffix : new String[] {"", " ORDER BY id LIMIT 10", " ORDER BY s, id LIMIT 10"}) {
+ assertFullScoring("SELECT id, score() AS s FROM score_usage_" + format + " WHERE " + predicate + suffix,
+ 2);
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testScoreTopNIsPushedIntoTheScan(String format, String predicate) {
+ for (String projection : new String[] {"id", "id, score() AS s"}) {
+ for (String range : new String[] {"", " AND score() > 0.00001"}) {
+ LogicalOlapScan scan = rewrittenScan("SELECT " + projection + " FROM score_usage_" + format
+ + " WHERE " + predicate + range + " ORDER BY score() DESC LIMIT 10");
+ Assertions.assertEquals(10L, scan.getScoreLimit().get().longValue());
+ Assertions.assertEquals(!range.isEmpty(), scan.getScoreRangeInfo().isPresent());
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testMinimumScoreOfAggregation(String format, String predicate) {
+ String from = " FROM score_usage_" + format + " WHERE " + predicate + " AND score() > 0.00001";
+ assertMinimumScore("SELECT count(*)" + from, 1);
+ assertMinimumScore("SELECT c2, count(*)" + from + " GROUP BY c2 HAVING count(*) > 0", 2);
+ assertMinimumScore("SELECT DISTINCT c2" + from, 1);
+ for (String groupBy : new String[] {"GROUPING SETS ((c2), ())", "ROLLUP(c2)", "CUBE(c2)"}) {
+ assertMinimumScore("SELECT c2, count(*)" + from + " GROUP BY " + groupBy, 2);
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testOtherScoreFiltersAreRejected(String format, String predicate) {
+ String from = "SELECT id FROM score_usage_" + format + " WHERE " + predicate + " AND ";
+ for (String filter : new String[] {"CAST(score() AS INT) > 0", "CAST(score() AS DECIMAL(10, 6)) > 0",
+ "score() < 1", "score() <= 1", "score() = 1", "score() * score() > 0", "score() > id",
+ "score() + 1 > 1"}) {
+ assertScoreUsageError(from + filter, BindScoreToOlapScan.RANGE_FORM_ERROR);
+ }
+ assertScoreUsageError(from + "score() > 0.1 AND score() < 0.9", BindScoreToOlapScan.ONE_RANGE_ERROR);
+ assertScoreUsageError(from + "(score() > 0 OR id = 1)", BindScoreToOlapScan.TOP_LEVEL_RANGE_ERROR);
+ assertScoreUsageError(from + "score() > 'abc'", "score() function can only be compared with numeric types");
+ assertScoreUsageError("SELECT id, 'abc' < score() FROM score_usage_" + format + " WHERE " + predicate,
+ "score() function can only be compared with numeric types");
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testScoreOfAggregationIsRejected(String format, String predicate) {
+ String from = " FROM score_usage_" + format + " WHERE " + predicate;
+ for (String query : new String[] {"SELECT sum(score())" + from, "SELECT count(distinct score())" + from,
+ "SELECT score()" + from + " GROUP BY score()", "SELECT DISTINCT score()" + from,
+ "SELECT c2, max(score())" + from + " GROUP BY c2",
+ "SELECT c2, max(score())" + from + " GROUP BY ROLLUP(c2)"}) {
+ assertScoreUsageError(query, BindScoreToOlapScan.AGGREGATE_ERROR);
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("scoringPredicates")
+ void testOverflowingTopNIsRejected(String format, String predicate) {
+ RuntimeException exception = Assertions.assertThrows(RuntimeException.class,
+ () -> PlanChecker.from(connectContext).checkPlannerResult(
+ "SELECT id, score() AS s FROM score_usage_" + format
+ + " WHERE " + predicate + " AND score() > 0.00001 ORDER BY s DESC"
+ + " LIMIT 9223372036854775807 OFFSET 9223372036854775807"));
+ Assertions.assertTrue(exception.getMessage().contains("limit + offset overflows"), exception.getMessage());
+ }
+
+ @Test
+ void testScoreNextToWindowFunctions() {
+ assertMinimumScore("SELECT id, score() AS s, row_number() OVER (ORDER BY id) AS rn"
+ + " FROM score_usage_V2 WHERE c1 MATCH 'apple' AND score() > 0.00001", 3);
+ assertMinimumScore("SELECT id, row_number() OVER (ORDER BY score() DESC, id) AS rn"
+ + " FROM score_usage_V2 WHERE c1 MATCH 'apple' AND score() > 0.00001", 2);
+ }
+
+ // The score column passes the delete sign filter that analysis puts on a UNIQUE table.
+ @ParameterizedTest
+ @ValueSource(strings = {"score_usage_V2", "score_usage_mow"})
+ void testTableAlias(String table) {
+ assertMinimumScore("SELECT a.id, score() AS s FROM " + table + " a"
+ + " WHERE a.c1 MATCH 'apple' AND score() > 0.00001", 2);
+ // ORDER BY score() reads the score although the select list does not.
+ LogicalOlapScan scan = rewrittenScan("SELECT a.id FROM " + table + " a WHERE a.c1 MATCH 'apple'"
+ + " ORDER BY score() DESC LIMIT 10");
+ Assertions.assertEquals(10L, scan.getScoreLimit().get().longValue());
+ }
+
+ // The score column is not a column of the table.
+ @Test
+ void testStarLeavesOutTheScoreColumn() {
+ String where = " WHERE c1 MATCH 'apple' AND score() > 0.00001";
+ assertMinimumScore("SELECT * FROM score_usage_V2" + where, 3);
+ assertMinimumScore("SELECT a.* FROM score_usage_V2 a" + where, 3);
+ assertMinimumScore("SELECT *, score() AS s FROM score_usage_V2" + where, 4);
+ assertMinimumScore("SELECT * EXCEPT (c2) FROM score_usage_V2" + where, 2);
+ // * REPLACE puts score() into the select list like any other item.
+ assertMinimumScore("SELECT * REPLACE (score() AS c2) FROM score_usage_V2" + where, 3);
+ assertFullScoring("SELECT * REPLACE (score() AS c2) FROM score_usage_V2 WHERE c1 MATCH 'apple'", 3);
+ }
+
+ // Analysis expands an alias function, so its score() is bound like one in the select list.
+ @Test
+ void testScoreInAliasFunction() throws Exception {
+ createFunction("CREATE ALIAS FUNCTION score_usage_alias() WITH PARAMETER() AS score()");
+ assertFullScoring("SELECT id, score_usage_alias() FROM score_usage_V2 WHERE c1 MATCH 'apple'", 2);
+ }
+
+ // With prefer_udf_over_builtin, a UDF named score is called instead of the builtin score().
+ @Test
+ void testUdfNamedScore() throws Exception {
+ createFunction("CREATE ALIAS FUNCTION score() WITH PARAMETER() AS abs(1)");
+ boolean preferUdf = connectContext.getSessionVariable().preferUdfOverBuiltin;
+ connectContext.getSessionVariable().preferUdfOverBuiltin = true;
+ try {
+ LogicalOlapScan scan = rewrittenScan("SELECT id, score() FROM score_usage_V2 WHERE c1 MATCH 'apple'");
+ Assertions.assertFalse(BindScoreToOlapScan.findScoreSlot(scan).isPresent());
+ } finally {
+ connectContext.getSessionVariable().preferUdfOverBuiltin = preferUdf;
+ executeSql("DROP FUNCTION score()");
+ }
+ }
+
+ // SEARCH keeps every document when another predicate follows, so the scan only takes over the
+ // minimum score, as before score() could be used without a TopN.
+ @Test
+ void testMinimumScoreOfSearchWithAnotherPredicate() {
+ LogicalOlapScan scan = rewrittenScan("SELECT id, score() AS s FROM score_usage_V2 WHERE search('c1:apple')"
+ + " AND id % 2 = 0 AND score() > 0.00001 ORDER BY s DESC LIMIT 10");
+ Assertions.assertEquals(0L, scan.getScoreLimit().get().longValue());
+ Assertions.assertTrue(scan.getScoreRangeInfo().isPresent());
+ }
+
+ @Test
+ void testEachSelectScoresItsOwnTable() {
+ String scored = "SELECT id, score() AS s FROM %s WHERE c1 MATCH '%s' ORDER BY s DESC LIMIT 2";
+ Plan plan = PlanChecker.from(connectContext)
+ .analyze("SELECT * FROM (" + String.format(scored, "score_usage_V2", "apple") + ") x UNION ALL "
+ + "SELECT * FROM (" + String.format(scored, "score_usage_V3", "pear") + ") y")
+ .rewrite().getCascadesContext().getRewritePlan();
+ Set<Slot> scoreSlots = plan.<LogicalOlapScan>collect(LogicalOlapScan.class::isInstance).stream()
+ .map(scan -> BindScoreToOlapScan.findScoreSlot(scan).get())
+ .collect(Collectors.toSet());
+ Assertions.assertEquals(2, scoreSlots.size());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "SELECT * FROM (%s) x",
+ "WITH c AS (%s) SELECT * FROM c",
+ "SELECT * FROM (%s) x UNION ALL SELECT id, 0 FROM score_usage_V3",
+ "SELECT id FROM score_usage_V3 WHERE id IN (SELECT id FROM (%s) x)",
+ "SELECT id FROM score_usage_V3 WHERE EXISTS (%s)"})
+ void testNestedScoreRequiresTopN(String query) {
+ String scored = "SELECT id, score() AS s FROM score_usage_V2 WHERE c1 MATCH 'apple' AND score() > 0.00001";
+ assertScoreUsageError(String.format(query, scored), BindScoreToOlapScan.NESTED_SELECT_ERROR);
+ assertScoreUsageError(String.format(query, scored + " ORDER BY 1 DESC LIMIT 2"),
+ BindScoreToOlapScan.NESTED_SELECT_ERROR);
+ for (String topN : new String[] {" ORDER BY s DESC LIMIT 2", " ORDER BY 2 DESC LIMIT 2"}) {
+ Assertions.assertDoesNotThrow(() -> PlanChecker.from(connectContext).checkPlannerResult(
+ String.format(query, scored + topN)), topN);
+ }
+ }
+
+ @Test
+ void testNestedScoreTopNAboveHaving() {
+ // HAVING reads c2, which the SELECT does not return, so analysis restores the select list between
+ // LIMIT and ORDER BY.
+ Assertions.assertDoesNotThrow(() -> PlanChecker.from(connectContext).checkPlannerResult(
+ "SELECT * FROM (SELECT id, score() AS s FROM score_usage_V2 WHERE c1 MATCH 'apple'"
+ + " HAVING c2 = 'sweet' ORDER BY s DESC LIMIT 2) x"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "SELECT id FROM score_usage_V3 b WHERE (b.c1 MATCH 'red' OR b.c1 MATCH 'green') AND EXISTS ("
+ + "SELECT 1 FROM score_usage_V2 a WHERE a.c1 = b.c1 AND a.c1 MATCH 'apple'"
+ + " AND score() > 0.6 ORDER BY score() DESC LIMIT 1)",
+ "SELECT id FROM score_usage_V3 b WHERE EXISTS (SELECT 1 FROM (SELECT c1, score() AS s"
+ + " FROM score_usage_V2 WHERE c1 MATCH 'apple' ORDER BY s DESC LIMIT 1) a WHERE a.c1 = b.c1)",
+ "SELECT id, (SELECT max(x.id) FROM (SELECT id, score() AS s FROM score_usage_V2"
+ + " WHERE c1 MATCH 'apple' ORDER BY s DESC LIMIT 2) x WHERE x.id = b.id) FROM score_usage_V3 b"})
+ void testCorrelatedSubqueryIsRejected(String query) {
+ assertScoreUsageError(query, BindScoreToOlapScan.CORRELATED_SUBQUERY_ERROR);
+ }
+
+ // The main query of a WITH clause is the outermost SELECT.
+ @Test
+ void testOutermostSelectUnderWith() {
+ assertFullScoring("WITH c AS (SELECT 1 AS one) SELECT id, score() AS s FROM score_usage_V2"
+ + " WHERE c1 MATCH 'apple'", 2);
+ }
+
+ @Test
+ void testViewWithScoreTopN() {
+ PlanChecker.from(connectContext).checkPlannerResult("SELECT * FROM score_usage_top WHERE id > 0",
+ planner -> Assertions.assertEquals(2, thriftScan(planner).olap_scan_node.score_sort_limit));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "SELECT score() FROM score_usage_V2",
+ "SELECT score() FROM score_usage_V2 WHERE c2 = 'sweet'",
+ // score() belongs to the MATCH of its own SELECT, not to the one of a subquery or CTE.
+ "SELECT score() FROM (SELECT id, c1 FROM score_usage_V2 WHERE c1 MATCH 'apple') x",
+ "WITH c AS (SELECT id, c1 FROM score_usage_V2) SELECT id, score() FROM c WHERE c1 MATCH 'apple'",
+ "SELECT a.id, score() FROM score_usage_V2 a JOIN score_usage_V3 b ON a.id = b.id"
+ + " WHERE a.c1 MATCH 'apple'",
+ "SELECT a.id FROM score_usage_V2 a JOIN score_usage_V3 b ON a.id = b.id AND score() > 0"
+ + " WHERE a.c1 MATCH 'apple'",
+ "SELECT id, score() FROM score_usage_V2 WHERE c1 MATCH 'apple'"
+ + " AND id IN (SELECT id FROM score_usage_V3)",
+ "SELECT id, e, score() FROM score_usage_V2 LATERAL VIEW explode(array(1, 2)) t AS e"
+ + " WHERE c1 MATCH 'apple'"})
+ void testUnsupportedSelectIsRejected(String query) {
+ assertScoreUsageError(query, BindScoreToOlapScan.UNSUPPORTED_SELECT_ERROR);
+ }
+
+ @Test
+ void testHavingAndQualifyAreRejected() {
+ assertScoreUsageError("SELECT c2, count(*) FROM score_usage_V2 WHERE c1 MATCH 'apple'"
+ + " AND score() > 0.00001 GROUP BY c2 HAVING c2 MATCH 'sweet'",
+ BindScoreToOlapScan.HAVING_OR_QUALIFY_ERROR);
+ assertScoreUsageError("SELECT id, score() AS s, row_number() OVER (ORDER BY id) AS rn"
+ + " FROM score_usage_V2 WHERE c1 MATCH 'apple' QUALIFY rn = 1 AND s > 0.5",
+ BindScoreToOlapScan.HAVING_OR_QUALIFY_ERROR);
+ // MATCH through an alias of the select list.
+ assertScoreUsageError("SELECT id, score() AS s, c1 MATCH 'red' AS m,"
+ + " row_number() OVER (PARTITION BY c1 ORDER BY id) AS rn"
+ + " FROM score_usage_V2 WHERE c1 MATCH 'apple' QUALIFY m AND rn = 1",
+ BindScoreToOlapScan.HAVING_OR_QUALIFY_ERROR);
+ assertScoreUsageError("SELECT id, score() AS s, c1 MATCH 'red' AS m"
+ + " FROM score_usage_V2 WHERE c1 MATCH 'apple' HAVING m",
+ BindScoreToOlapScan.HAVING_OR_QUALIFY_ERROR);
+ assertScoreUsageError("SELECT c1 MATCH 'red' AS m, count(*) FROM score_usage_V2"
+ + " WHERE c1 MATCH 'apple' AND score() > 0.00001 GROUP BY m HAVING m",
+ BindScoreToOlapScan.HAVING_OR_QUALIFY_ERROR);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"c1 MATCH 'apple'", "search('c1:apple')"})
+ void testMinimumScoreKeepsAnnTopN(String predicate) {
+ PlanChecker.from(connectContext).checkPlannerResult(
+ "SELECT id, l2_distance_approximate(embedding, [0.0, 0.0]) AS dist FROM score_usage_ann"
+ + " WHERE " + predicate + " AND score() > 0.5 ORDER BY dist LIMIT 1",
+ planner -> {
+ TPlanNode scan = thriftScan(planner);
+ Assertions.assertNotNull(scan.olap_scan_node.ann_sort_info);
+ Assertions.assertEquals(1, scan.olap_scan_node.ann_sort_limit);
+ Assertions.assertEquals(0, scan.olap_scan_node.score_sort_limit);
+ assertFiltersScore(scan);
+ });
+ }
+
+ @Test
+ void testCseVirtualColumnsLeaveScoreToTheBinding() {
+ boolean enableCse = connectContext.getSessionVariable().experimentalEnableVirtualSlotForCse;
+ connectContext.getSessionVariable().experimentalEnableVirtualSlotForCse = true;
+ try {
+ LogicalOlapScan scan = rewrittenScan("SELECT id, sin(abs(score()) + 1) AS a, cos(abs(score()) + 1) AS b"
+ + " FROM score_usage_V2 WHERE c1 MATCH 'apple' AND score() > 0.00001");
+ // Only the score column may contain score(); a CSE column would evaluate it as zero.
+ List<NamedExpression> scoreColumns = scan.getVirtualColumns().stream()
+ .filter(column -> column.containsType(Score.class))
+ .collect(Collectors.toList());
+ Assertions.assertEquals(1, scoreColumns.size(), scan.getVirtualColumns().toString());
+ Assertions.assertTrue(((Alias) scoreColumns.get(0)).child() instanceof Score);
+ } finally {
+ connectContext.getSessionVariable().experimentalEnableVirtualSlotForCse = enableCse;
+ }
+ }
+
+ @Test
+ void testExplainShowsTheMinimumScore() throws Exception {
+ String explain = getSQLPlanOrErrorMsg("EXPLAIN SELECT id FROM score_usage_V2"
+ + " WHERE c1 MATCH 'apple' AND score() >= 0.5");
+ Assertions.assertTrue(explain.contains("SCORE SORT LIMIT: 0"), explain);
+ Assertions.assertFalse(explain.contains("SCORE RANGE"), explain);
+ // The scan keeps the best rows of each segment only when it also applies the minimum score.
+ explain = getSQLPlanOrErrorMsg("EXPLAIN SELECT id FROM score_usage_V2"
+ + " WHERE c1 MATCH 'apple' AND score() >= 0.5 ORDER BY score() DESC LIMIT 10");
+ Assertions.assertTrue(explain.contains("SCORE SORT LIMIT: 10"), explain);
+ Assertions.assertTrue(explain.contains("SCORE RANGE: score() >= 0.5"), explain);
+ }
+
+ private LogicalOlapScan rewrittenScan(String sql) {
+ return (LogicalOlapScan) PlanChecker.from(connectContext).analyze(sql).rewrite()
+ .getCascadesContext().getRewritePlan()
+ .collectFirst(plan -> plan instanceof LogicalOlapScan).get();
+ }
+
+ // The minimum score is a conjunct of the scan, which evaluates it like any other.
+ private void assertMinimumScore(String sql, int outputColumns) {
+ PlanChecker.from(connectContext).checkPlannerResult(sql,
+ planner -> assertFiltersScore(assertScoresEveryRow(planner, outputColumns)));
+ }
+
+ private void assertFiltersScore(TPlanNode scan) {
+ Assertions.assertFalse(scan.olap_scan_node.isSetScoreRangeInfo());
+ int scoreSlotId = scan.olap_scan_node.score_sort_info.ordering_exprs.get(0).nodes.get(0).slot_ref.slot_id;
+ Assertions.assertTrue(scan.conjuncts.stream().anyMatch(conjunct -> conjunct.nodes.stream()
+ .anyMatch(node -> node.isSetSlotRef() && node.slot_ref.slot_id == scoreSlotId)));
+ }
+
+ private void assertFullScoring(String sql, int outputColumns) {
+ PlanChecker.from(connectContext).checkPlannerResult(sql, planner -> {
+ TPlanNode scan = assertScoresEveryRow(planner, outputColumns);
+ Assertions.assertFalse(scan.olap_scan_node.isSetScoreRangeInfo(), sql);
+ });
+ }
+
+ // The scan scores every row it returns, with the score column in its output tuple.
+ private TPlanNode assertScoresEveryRow(NereidsPlanner planner, int outputColumns) {
+ TPlanNode scan = thriftScan(planner);
+ Assertions.assertNotNull(scan.olap_scan_node.score_sort_info);
+ Assertions.assertEquals(0, scan.olap_scan_node.score_sort_limit);
+ Assertions.assertTrue(scan.olap_scan_node.score_sort_info.ordering_exprs.get(0)
+ .nodes.get(0).slot_ref.is_virtual_slot, "Scoring must reference a virtual slot");
+ int scoreSlotId = scan.olap_scan_node.score_sort_info.ordering_exprs.get(0).nodes.get(0).slot_ref.slot_id;
+ OlapScanNode scanNode = (OlapScanNode) planner.getScanNodes().get(0);
+ Assertions.assertTrue(scanNode.getTupleDesc().getSlots().stream()
+ .anyMatch(slot -> slot.getId().asInt() == scoreSlotId),
+ "The score column must be in the scan tuple");
+ Assertions.assertEquals(outputColumns, planner.getFragments().get(0).getOutputExprs().size());
+ return scan;
+ }
+
+ private TPlanNode thriftScan(NereidsPlanner planner) {
+ Assertions.assertEquals(1, planner.getScanNodes().size());
+ return planner.getScanNodes().get(0).treeToThrift().getNodes().get(0);
+ }
+
+ private void assertScoreUsageError(String sql, String error) {
+ AnalysisException exception = Assertions.assertThrows(AnalysisException.class,
+ () -> PlanChecker.from(connectContext).analyze(sql).rewrite(), sql);
+ Assertions.assertTrue(exception.getMessage().contains(error), exception.getMessage());
+ }
+}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/SearchExpressionTest.java b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/SearchExpressionTest.java
index b1397cf8ce6..acff9ebd539 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/SearchExpressionTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/SearchExpressionTest.java
@@ -18,6 +18,8 @@
package org.apache.doris.nereids.trees.expressions;
import org.apache.doris.analysis.SearchDslParser;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.BooleanType;
import org.apache.doris.nereids.types.StringType;
@@ -28,12 +30,37 @@ import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Optional;
/**
* Unit tests for SearchExpression
*/
public class SearchExpressionTest {
+ @Test
+ public void testToSqlPreservesDsl() {
+ for (String dsl : Arrays.asList("title:hello", "title:\"O'Reilly\\manual\"")) {
+ SearchExpression searchExpr = new SearchExpression(dsl, createTestPlan(),
+ Arrays.asList(createTestSlot("title")));
+ Expression parsed = new NereidsParser().parseExpression(searchExpr.toSql());
+ Assertions.assertEquals(dsl, ((StringLikeLiteral) parsed.child(0)).getStringValue());
+ }
+ }
+
+ @Test
+ public void testToSqlKeepsOptions() {
+ String options = "{\"default_field\":\"title\",\"default_operator\":\"or\"}";
+ SearchExpression searchExpr = new SearchExpression("hello world", Optional.of(options), createTestPlan(),
+ Arrays.asList(createTestSlot("title")));
+ Expression parsed = new NereidsParser().parseExpression(searchExpr.toSql());
+ Assertions.assertEquals(2, parsed.children().size());
+ Assertions.assertEquals("hello world", ((StringLikeLiteral) parsed.child(0)).getStringValue());
+ Assertions.assertEquals(options, ((StringLikeLiteral) parsed.child(1)).getStringValue());
+ Assertions.assertEquals(searchExpr, searchExpr.withChildren(searchExpr.children()));
+ Assertions.assertNotEquals(searchExpr, new SearchExpression("hello world", searchExpr.getQsPlan(),
+ searchExpr.children()));
+ }
+
private SearchDslParser.QsPlan createTestPlan() {
SearchDslParser.QsNode root = new SearchDslParser.QsNode(
SearchDslParser.QsClauseType.TERM, "title", "hello");
diff --git a/regression-test/data/ann_index_p0/ann_with_fulltext.out b/regression-test/data/ann_index_p0/ann_with_fulltext.out
index e3dfae627f9..dcc3eada4bf 100644
--- a/regression-test/data/ann_index_p0/ann_with_fulltext.out
+++ b/regression-test/data/ann_index_p0/ann_with_fulltext.out
@@ -15,6 +15,10 @@
0 This example illustrates how subtle differences can influence perception. It's more about interpretation than right or wrong.
-- !q2 --
-0 This example illustrates how subtle differences can influence perception. It's more about interpretation than right or wrong. 81.69190979003906
-9 This task isn’t about right answers, but about consistency in your judgments over time. 122.17068481445312
+0 This example illustrates how subtle differences can influence perception. It's more about interpretation than right or wrong. 81.69191
+9 This task isn’t about right answers, but about consistency in your judgments over time. 122.170685
+
+-- !q3 --
+1.0389736 163.05757
+2.1595716 81.69191
diff --git a/regression-test/data/inverted_index_p0/test_bm25_score.out b/regression-test/data/inverted_index_p0/test_bm25_score.out
index e4e83d30e4f..5b8ede10f56 100644
--- a/regression-test/data/inverted_index_p0/test_bm25_score.out
+++ b/regression-test/data/inverted_index_p0/test_bm25_score.out
@@ -18,7 +18,21 @@
893966443 30.0.0.0 GET /english/playing/mascot/images/button.03.gif HTTP/1.0 200 893 10.160415
-- !sql --
-893966443 30.0.0.0 GET /english/playing/mascot/images/button.03.gif HTTP/1.0 200 893 10.160415
+893966443 30.0.0.0 GET /english/playing/mascot/images/button.03.gif HTTP/1.0 200 893 10.160416
+
+-- !score_order_by_score_and_column --
+200 10.160415
+200 4.585793
+200 4.585793
+
+-- !score_topn_best --
+10.160415
+
+-- !score_range_without_topn --
+14
+
+-- !score_range_topn_control --
+14
-- !sql --
2 2 {"key":"abc hhh"} 0.0
diff --git a/regression-test/data/inverted_index_p0/test_score_filter_matrix.out b/regression-test/data/inverted_index_p0/test_score_filter_matrix.out
new file mode 100644
index 00000000000..5ffe7ab9e17
--- /dev/null
+++ b/regression-test/data/inverted_index_p0/test_score_filter_matrix.out
@@ -0,0 +1,537 @@
+-- This file is automatically generated. You should know what you did if you want to edit this
+-- !V2_match_range --
+1 0.4700036
+2 0.4700036
+
+-- !V2_match_topn_control --
+1 0.4700036
+2 0.4700036
+
+-- !V2_match_strict_boundary --
+
+-- !V2_match_inclusive_boundary --
+1
+2
+
+-- !V2_match_reversed_ge --
+1
+2
+
+-- !V2_match_lossless_cast --
+1
+2
+
+-- !V2_match_high_threshold --
+
+-- !V2_match_null_threshold --
+
+-- !V2_match_no_hits --
+
+-- !V2_search_range --
+1 0.4700036
+2 0.4700036
+
+-- !V2_search_topn_control --
+1 0.4700036
+2 0.4700036
+
+-- !V2_search_strict_boundary --
+
+-- !V2_search_inclusive_boundary --
+1
+2
+
+-- !V2_search_reversed_ge --
+1
+2
+
+-- !V2_search_lossless_cast --
+1
+2
+
+-- !V2_search_high_threshold --
+
+-- !V2_search_null_threshold --
+
+-- !V2_search_no_hits --
+
+-- !V2_match_multirowset --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_match_multirowset_topn_control --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_match_long_norm_threshold --
+
+-- !V2_match_warm_cache --
+1
+2
+5
+6
+
+-- !V2_match_cache_false_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V2_match_cache_false_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V2_match_cache_true_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V2_match_cache_true_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V2_search_multirowset --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_search_multirowset_topn_control --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_search_long_norm_threshold --
+
+-- !V2_search_warm_cache --
+1
+2
+5
+6
+
+-- !V2_search_cache_false_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V2_search_cache_false_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V2_search_cache_true_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V2_search_cache_true_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V2_match_after_delete --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_match_after_delete_topn_control --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_search_after_delete --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_search_after_delete_topn_control --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V2_match_mow --
+2 0.64072424
+3 0.90232176
+
+-- !V2_match_mow_topn_control --
+2 0.64072424
+3 0.90232176
+
+-- !V2_search_mow --
+2 0.64072424
+3 0.90232176
+
+-- !V2_search_mow_topn_control --
+2 0.64072424
+3 0.90232176
+
+-- !V2_match_mow_after_delete --
+3 1.0217376
+
+-- !V2_match_mow_after_delete_topn_control --
+3 1.0217376
+
+-- !V2_search_mow_after_delete --
+3 1.0217376
+
+-- !V2_search_mow_after_delete_topn_control --
+3 1.0217376
+
+-- !V3_match_range --
+1 0.4700036
+2 0.4700036
+
+-- !V3_match_topn_control --
+1 0.4700036
+2 0.4700036
+
+-- !V3_match_strict_boundary --
+
+-- !V3_match_inclusive_boundary --
+1
+2
+
+-- !V3_match_reversed_ge --
+1
+2
+
+-- !V3_match_lossless_cast --
+1
+2
+
+-- !V3_match_high_threshold --
+
+-- !V3_match_null_threshold --
+
+-- !V3_match_no_hits --
+
+-- !V3_search_range --
+1 0.4700036
+2 0.4700036
+
+-- !V3_search_topn_control --
+1 0.4700036
+2 0.4700036
+
+-- !V3_search_strict_boundary --
+
+-- !V3_search_inclusive_boundary --
+1
+2
+
+-- !V3_search_reversed_ge --
+1
+2
+
+-- !V3_search_lossless_cast --
+1
+2
+
+-- !V3_search_high_threshold --
+
+-- !V3_search_null_threshold --
+
+-- !V3_search_no_hits --
+
+-- !V3_match_multirowset --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_match_multirowset_topn_control --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_match_long_norm_threshold --
+
+-- !V3_match_warm_cache --
+1
+2
+5
+6
+
+-- !V3_match_cache_false_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V3_match_cache_false_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V3_match_cache_true_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V3_match_cache_true_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V3_search_multirowset --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_search_multirowset_topn_control --
+1 0.72814035
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_search_long_norm_threshold --
+
+-- !V3_search_warm_cache --
+1
+2
+5
+6
+
+-- !V3_search_cache_false_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V3_search_cache_false_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V3_search_cache_true_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !V3_search_cache_true_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !V3_match_after_delete --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_match_after_delete_topn_control --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_search_after_delete --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_search_after_delete_topn_control --
+2 0.72814035
+5 0.95549184
+6 0.7187315
+
+-- !V3_match_mow --
+2 0.64072424
+3 0.90232176
+
+-- !V3_match_mow_topn_control --
+2 0.64072424
+3 0.90232176
+
+-- !V3_search_mow --
+2 0.64072424
+3 0.90232176
+
+-- !V3_search_mow_topn_control --
+2 0.64072424
+3 0.90232176
+
+-- !V3_match_mow_after_delete --
+3 1.0217376
+
+-- !V3_match_mow_after_delete_topn_control --
+3 1.0217376
+
+-- !V3_search_mow_after_delete --
+3 1.0217376
+
+-- !V3_search_mow_after_delete_topn_control --
+3 1.0217376
+
+-- !SNII_match_range --
+1 0.4700036
+2 0.4700036
+
+-- !SNII_match_topn_control --
+1 0.4700036
+2 0.4700036
+
+-- !SNII_match_strict_boundary --
+
+-- !SNII_match_inclusive_boundary --
+1
+2
+
+-- !SNII_match_reversed_ge --
+1
+2
+
+-- !SNII_match_lossless_cast --
+1
+2
+
+-- !SNII_match_high_threshold --
+
+-- !SNII_match_null_threshold --
+
+-- !SNII_match_no_hits --
+
+-- !SNII_search_range --
+1 0.4700036
+2 0.4700036
+
+-- !SNII_search_topn_control --
+1 0.4700036
+2 0.4700036
+
+-- !SNII_search_strict_boundary --
+
+-- !SNII_search_inclusive_boundary --
+1
+2
+
+-- !SNII_search_reversed_ge --
+1
+2
+
+-- !SNII_search_lossless_cast --
+1
+2
+
+-- !SNII_search_high_threshold --
+
+-- !SNII_search_null_threshold --
+
+-- !SNII_search_no_hits --
+
+-- !SNII_match_multirowset --
+1 0.72814035
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_match_multirowset_topn_control --
+1 0.72814035
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_match_long_norm_threshold --
+5
+
+-- !SNII_match_warm_cache --
+1
+2
+5
+6
+
+-- !SNII_match_cache_false_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_match_cache_false_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_match_cache_true_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_match_cache_true_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_search_multirowset --
+1 0.72814035
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_search_multirowset_topn_control --
+1 0.72814035
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_search_long_norm_threshold --
+5
+
+-- !SNII_search_warm_cache --
+1
+2
+5
+6
+
+-- !SNII_search_cache_false_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_search_cache_false_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_search_cache_true_wand_false --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_search_cache_true_wand_true --
+2 0.72814035
+6 0.7187315
+
+-- !SNII_match_after_delete --
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_match_after_delete_topn_control --
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_search_after_delete --
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_search_after_delete_topn_control --
+2 0.72814035
+5 0.9568616
+6 0.7187315
+
+-- !SNII_match_mow --
+2 0.64072424
+3 0.90232176
+
+-- !SNII_match_mow_topn_control --
+2 0.64072424
+3 0.90232176
+
+-- !SNII_search_mow --
+2 0.64072424
+3 0.90232176
+
+-- !SNII_search_mow_topn_control --
+2 0.64072424
+3 0.90232176
+
+-- !SNII_match_mow_after_delete --
+3 1.0217376
+
+-- !SNII_match_mow_after_delete_topn_control --
+3 1.0217376
+
+-- !SNII_search_mow_after_delete --
+3 1.0217376
+
+-- !SNII_search_mow_after_delete_topn_control --
+3 1.0217376
+
+-- !ann_control --
+1 0.0
+
+-- !ann_after_score_filter --
+2 1.4142135
+
diff --git a/regression-test/data/inverted_index_p0/test_score_filter_usage.out b/regression-test/data/inverted_index_p0/test_score_filter_usage.out
new file mode 100644
index 00000000000..6a089bcde58
--- /dev/null
+++ b/regression-test/data/inverted_index_p0/test_score_filter_usage.out
@@ -0,0 +1,106 @@
+-- This file is automatically generated. You should know what you did if you want to edit this
+-- !where_only_score --
+1
+2
+
+-- !projected_score_range --
+1 0.4700036
+2 0.4700036
+
+-- !repeated_score_aliases --
+1 0.4700036 0.4700036
+2 0.4700036 0.4700036
+
+-- !select_star_score_range --
+1 apple red sweet
+2 apple green sour
+
+-- !select_star_replace_score --
+1 apple red 0.4700036
+2 apple green 0.4700036
+
+-- !table_alias_score_range --
+1 0.4700036
+2 0.4700036
+
+-- !mow_alias_score_range --
+1 0.43445712
+2 0.43445712
+
+-- !mow_alias_score_topn --
+1 0.43445712
+2 0.43445712
+
+-- !mv_minimum_score --
+
+-- !score_without_range --
+1 0.4700036
+2 0.4700036
+
+-- !ordinary_order_with_offset --
+2 sour 0.4700036
+
+-- !multiple_order_keys --
+1 sweet 0.4700036
+
+-- !reverse_key_order --
+2 sour 0.4700036
+
+-- !score_sort_without_limit --
+1 sweet 0.4700036
+2 sour 0.4700036
+
+-- !score_derived_topn --
+15000 14
+
+-- !window_same_select --
+1 0.4700036 1
+2 0.4700036 2
+
+-- !window_order_by_score --
+1 1
+2 2
+
+-- !count_score_range --
+2
+
+-- !count_score_range_without_pushdown --
+2
+
+-- !count_high_score_range --
+0
+
+-- !group_by_score_range --
+sour 1
+sweet 1
+
+-- !grouping_sets_score_range --
+\N 2
+sour 1
+sweet 1
+
+-- !nested_score_topn_having --
+1 0.4700036
+
+-- !nested_score_topn --
+1 0.4700036 sweet
+2 0.4700036 sour
+
+-- !nested_score_topn_by_position --
+1 0.4700036
+2 0.4700036
+
+-- !union_score_topn --
+1 0.9808291
+2 0.9808291
+
+-- !projected_match_above_score --
+
+-- !projected_match_score --
+1 0.4700036 true
+2 0.4700036 true
+
+-- !cse_score_expressions --
+1 0.9949247125157072 0.1006221467945171
+2 0.9949247125157072 0.1006221467945171
+
diff --git a/regression-test/suites/ann_index_p0/ann_with_fulltext.groovy b/regression-test/suites/ann_index_p0/ann_with_fulltext.groovy
index c7d0b11a7de..ead633b513d 100644
--- a/regression-test/suites/ann_index_p0/ann_with_fulltext.groovy
+++ b/regression-test/suites/ann_index_p0/ann_with_fulltext.groovy
@@ -57,9 +57,9 @@ suite("ann_with_fulltext") {
qt_q2 """
select id, comment, l2_distance_approximate(embedding, [26.360261917114258,7.05784273147583,32.361351013183594,86.39714050292969,58.79527282714844,27.189321517944336,99.38946533203125,80.19270324707031]) as dist from ann_with_fulltext where comment match_any "illustrates comments answers" order by dist limit 2
"""
- // This case should error because score() + another ordering expression is not allowed for TopN push down
- test {
- sql "select score() as score, l2_distance_approximate(embedding, [26.360261917114258,7.05784273147583,32.361351013183594,86.39714050292969,58.79527282714844,27.189321517944336,99.38946533203125,80.19270324707031]) as dist from ann_with_fulltext where comment match_any \"illustrates comments answers\" order by score, dist limit 2"
- exception "TopN must have exactly one ordering expression for score() push down optimization"
- }
+ // A TopN on the score and another expression is not pushed into the scan: the scan scores
+ // every row and the TopN sorts them.
+ qt_q3 """
+ select score() as score, l2_distance_approximate(embedding, [26.360261917114258,7.05784273147583,32.361351013183594,86.39714050292969,58.79527282714844,27.189321517944336,99.38946533203125,80.19270324707031]) as dist from ann_with_fulltext where comment match_any "illustrates comments answers" order by score, dist limit 2
+ """
}
\ No newline at end of file
diff --git a/regression-test/suites/inverted_index_p0/test_bm25_score.groovy b/regression-test/suites/inverted_index_p0/test_bm25_score.groovy
index d7a53b4873a..e623b032c6d 100644
--- a/regression-test/suites/inverted_index_p0/test_bm25_score.groovy
+++ b/regression-test/suites/inverted_index_p0/test_bm25_score.groovy
@@ -103,67 +103,56 @@ suite("test_bm25_score", "p0") {
// Test exception cases for score() function usage
log.info("Testing exception cases for score() function...")
+ // score() needs a MATCH or SEARCH predicate in the WHERE clause of its own SELECT on one table.
+ def unsupportedSelect = "score() can only be used in a SELECT that reads one table"
test {
sql """ select score() as score from test_bm25_score limit 10; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
+ exception unsupportedSelect
}
test {
sql """ select score() as score from test_bm25_score where status = 200 limit 10; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
- }
-
- test {
- sql """ select score() as score from test_bm25_score where request match_any 'button.03.gif' limit 10; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
- }
-
- test {
- sql """ select score() as score from test_bm25_score where request match_any 'button.03.gif' order by score; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
- }
-
- test {
- sql """ select score() as score from test_bm25_score where request match_any 'button.03.gif' order by status limit 10; """
- exception "ORDER BY expression must reference a score() function from SELECT clause for push down optimization"
+ exception unsupportedSelect
}
test {
sql """ select score() from test_bm25_score; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
+ exception unsupportedSelect
}
test {
sql """ select * from (select score() as s from test_bm25_score where status = 200) t; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
+ exception unsupportedSelect
}
test {
sql """ select score() as score from test_bm25_score where request = 'button.03.gif' order by score() limit 10; """
- exception "WHERE clause must contain at least one MATCH or SEARCH function for score() push down optimization"
- }
-
- test {
- sql """ select score() as score from test_bm25_score where request match 'button.03.gif'; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
+ exception unsupportedSelect
}
+ // A scored SELECT in a subquery or set operation needs ORDER BY score() with LIMIT.
test {
sql """
(select score() as score from test_bm25_score where request match_any 'button.03.gif')
union all
(select score() as score from test_bm25_score where request match_any 'test');
"""
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
+ exception "score() in a subquery, view, CTE or set operation requires ORDER BY score() with LIMIT"
}
+ // Without a TopN on the score, the scan scores every row it returns; a TopN on the score
+ // finds the same best score.
+ qt_score_order_by_score_and_column """ select status, score() as s from test_bm25_score where request match_any 'button.03.gif' order by s desc, status limit 3; """
+ qt_score_topn_best """ select score() as score from test_bm25_score where request match_any 'button.03.gif' order by score desc limit 1; """
+
// score() > 0.5 with ORDER BY and LIMIT is now supported after score range filter pushdown feature
sql """ select *, score() from test_bm25_score where request match_any 'button.03.gif' and score() > 0.5 order by score() limit 10; """
- test {
- sql """ select *, score() as score from test_bm25_score where request match_any 'button.03.gif' and score() > 0.5; """
- exception "score() function requires WHERE clause with MATCH function, ORDER BY and LIMIT for optimization"
- }
+ // score() > 0.5 without ORDER BY and LIMIT is a supported minimum score filter. Its row count
+ // must match the score TopN path with a limit above the number of matching rows.
+ sql """ select *, score() as score from test_bm25_score where request match_any 'button.03.gif' and score() > 0.5; """
+ qt_score_range_without_topn """ select count() from test_bm25_score where request match_any 'button.03.gif' and score() > 0.5; """
+ qt_score_range_topn_control """ select count() from (select score() as s from test_bm25_score where request match_any 'button.03.gif' and score() > 0.5 order by s desc limit 1000) t; """
log.info("All exception test cases completed successfully")
} finally {
diff --git a/regression-test/suites/inverted_index_p0/test_score_filter_matrix.groovy b/regression-test/suites/inverted_index_p0/test_score_filter_matrix.groovy
new file mode 100644
index 00000000000..b5d38164174
--- /dev/null
+++ b/regression-test/suites/inverted_index_p0/test_score_filter_matrix.groovy
@@ -0,0 +1,224 @@
+// 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.
+
+suite("test_score_filter_matrix", "p0") {
+ def predicates = [match: "c1 MATCH 'apple'", search: "search('c1:apple')"]
+ for (String format : ["V2", "V3", "SNII"]) {
+ sql "DROP TABLE IF EXISTS test_score_filter_matrix"
+ sql """
+ CREATE TABLE test_score_filter_matrix (
+ id INT, c1 TEXT, c2 TEXT,
+ INDEX idx_c1(c1) USING INVERTED PROPERTIES (
+ "parser"="english", "lower_case"="true", "support_phrase"="true")
+ ) DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num"="1", "inverted_index_storage_format"="${format}")
+ """
+ sql """
+ INSERT INTO test_score_filter_matrix VALUES
+ (1, 'apple red', 'sweet'), (2, 'apple green', 'sour'), (3, 'banana yellow', 'sweet')
+ """
+ predicates.each { label, predicate ->
+ def tag = "${format}_${label}"
+ "order_qt_${tag}_range"("""
+ SELECT id, score() AS s FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() > 0.00001
+ """)
+ "order_qt_${tag}_topn_control"("""
+ SELECT id, score() AS s FROM test_score_filter_matrix
+ WHERE ${predicate} ORDER BY s DESC LIMIT 100
+ """)
+ def boundary = sql("""
+ SELECT score() AS s FROM test_score_filter_matrix
+ WHERE ${predicate} ORDER BY s DESC LIMIT 1
+ """)[0][0].toString()
+ "order_qt_${tag}_strict_boundary"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() > CAST(${boundary} AS FLOAT)
+ """)
+ "order_qt_${tag}_inclusive_boundary"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() >= CAST(${boundary} AS FLOAT)
+ """)
+ "order_qt_${tag}_reversed_ge"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate} AND 0.00001 <= score()
+ """)
+ "order_qt_${tag}_lossless_cast"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate} AND CAST(score() AS DOUBLE) > 0.00001
+ """)
+ "order_qt_${tag}_high_threshold"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() > 1000000
+ """)
+ "order_qt_${tag}_null_threshold"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() > CAST(NULL AS DOUBLE)
+ """)
+ "order_qt_${tag}_no_hits"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate.replace('apple', 'unmatchedtoken')} AND score() > 0
+ """)
+ for (String type : ["INT", "DECIMAL(10, 6)"]) {
+ test {
+ sql "SELECT id FROM test_score_filter_matrix WHERE ${predicate} " +
+ "AND CAST(score() AS ${type}) > 0"
+ exception "score() predicate in WHERE clause must be in the form"
+ }
+ }
+ for (String range : ["score() < 1", "score() <= 1", "score() = 1", "score() * score() > 0", "score() > id",
+ "score() + 1 > 1"]) {
+ test {
+ sql "SELECT id FROM test_score_filter_matrix WHERE ${predicate} AND ${range}"
+ exception "score() predicate in WHERE clause must be in the form"
+ }
+ }
+ test {
+ sql "SELECT id FROM test_score_filter_matrix WHERE ${predicate} " +
+ "AND score() > 0.1 AND score() < 0.9"
+ exception "Only one score() range predicate is supported"
+ }
+ test {
+ sql "SELECT id FROM test_score_filter_matrix WHERE ${predicate} AND (score() > 0 OR id = 1)"
+ exception "score() predicate must be a top-level AND condition"
+ }
+ }
+
+ sql """
+ INSERT INTO test_score_filter_matrix VALUES
+ (4, NULL, 'missing'), (5, repeat('apple ', 300), 'repeat'), (6, 'apple blue green', 'fresh')
+ """
+ predicates.each { label, predicate ->
+ def tag = "${format}_${label}"
+ "order_qt_${tag}_multirowset"("""
+ SELECT id, score() AS s FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() > 0
+ """)
+ "order_qt_${tag}_multirowset_topn_control"("""
+ SELECT id, score() AS s FROM test_score_filter_matrix
+ WHERE ${predicate} ORDER BY s DESC LIMIT 100
+ """)
+ "order_qt_${tag}_long_norm_threshold"("""
+ SELECT id FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() > 0.956
+ """)
+ "order_qt_${tag}_warm_cache"("""
+ SELECT /*+ SET_VAR(enable_inverted_index_query_cache=true) */ id
+ FROM test_score_filter_matrix WHERE ${predicate}
+ """)
+ for (boolean cache : [false, true]) {
+ for (boolean wand : [false, true]) {
+ "order_qt_${tag}_cache_${cache}_wand_${wand}"("""
+ SELECT /*+ SET_VAR(enable_inverted_index_query_cache=${cache},
+ enable_inverted_index_wand_query=${wand}) */ id, score() AS s
+ FROM test_score_filter_matrix
+ WHERE ${predicate} AND id % 2 = 0 AND score() > 0
+ """)
+ }
+ }
+ }
+ sql "DELETE FROM test_score_filter_matrix WHERE id = 1"
+ predicates.each { label, predicate ->
+ def tag = "${format}_${label}"
+ "order_qt_${tag}_after_delete"("""
+ SELECT id, score() AS s FROM test_score_filter_matrix
+ WHERE ${predicate} AND score() > 0
+ """)
+ "order_qt_${tag}_after_delete_topn_control"("""
+ SELECT id, score() AS s FROM test_score_filter_matrix
+ WHERE ${predicate} ORDER BY s DESC LIMIT 100
+ """)
+ }
+
+ sql "DROP TABLE IF EXISTS test_score_filter_mow"
+ sql """
+ CREATE TABLE test_score_filter_mow (
+ id INT NOT NULL, c1 TEXT,
+ INDEX idx_c1(c1) USING INVERTED PROPERTIES (
+ "parser"="english", "lower_case"="true", "support_phrase"="true")
+ ) UNIQUE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num"="1", "enable_unique_key_merge_on_write"="true",
+ "inverted_index_storage_format"="${format}")
+ """
+ sql "INSERT INTO test_score_filter_mow VALUES (1, 'apple red'), (2, 'apple green'), (3, 'banana yellow')"
+ sql "INSERT INTO test_score_filter_mow VALUES (1, 'banana yellow'), (3, 'apple apple'), (4, NULL)"
+ predicates.each { label, predicate ->
+ def tag = "${format}_${label}"
+ "order_qt_${tag}_mow"("""
+ SELECT id, score() AS s FROM test_score_filter_mow
+ WHERE ${predicate} AND score() > 0
+ """)
+ "order_qt_${tag}_mow_topn_control"("""
+ SELECT id, score() AS s FROM test_score_filter_mow
+ WHERE ${predicate} ORDER BY s DESC LIMIT 100
+ """)
+ }
+ sql "DELETE FROM test_score_filter_mow WHERE id = 2"
+ predicates.each { label, predicate ->
+ def tag = "${format}_${label}"
+ "order_qt_${tag}_mow_after_delete"("""
+ SELECT id, score() AS s FROM test_score_filter_mow
+ WHERE ${predicate} AND score() > 0
+ """)
+ "order_qt_${tag}_mow_after_delete_topn_control"("""
+ SELECT id, score() AS s FROM test_score_filter_mow
+ WHERE ${predicate} ORDER BY s DESC LIMIT 100
+ """)
+ }
+ }
+ sql "DROP TABLE IF EXISTS test_score_filter_ann"
+ sql """
+ CREATE TABLE test_score_filter_ann (
+ id INT NOT NULL, c1 TEXT, embedding ARRAY<FLOAT> NOT NULL,
+ INDEX idx_c1(c1) USING INVERTED PROPERTIES("parser"="english"),
+ INDEX idx_ann(embedding) USING ANN
+ PROPERTIES("index_type"="hnsw", "metric_type"="l2_distance", "dim"="2")
+ ) DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES("replication_num"="1", "inverted_index_storage_format"="V3")
+ """
+ sql """
+ INSERT INTO test_score_filter_ann VALUES
+ (1, 'apple red green blue yellow orange pear peach grape lemon', [0.0, 0.0]),
+ (2, 'apple apple apple', [1.0, 1.0]), (3, 'banana yellow', [2.0, 2.0])
+ """
+ qt_ann_control """
+ SELECT id, l2_distance_approximate(embedding, [0.0, 0.0]) AS dist
+ FROM test_score_filter_ann WHERE c1 MATCH 'apple' ORDER BY dist LIMIT 1
+ """
+ qt_ann_after_score_filter """
+ SELECT id, l2_distance_approximate(embedding, [0.0, 0.0]) AS dist
+ FROM test_score_filter_ann WHERE c1 MATCH 'apple' AND score() > 0.5
+ ORDER BY dist LIMIT 1
+ """
+ // The minimum score is a filter of the scan, so the nearest row (id 1) is never chosen by the
+ // ANN TopN just to be discarded by the score filter afterwards.
+ explain {
+ sql """
+ SELECT id, l2_distance_approximate(embedding, [0.0, 0.0]) AS dist
+ FROM test_score_filter_ann WHERE c1 MATCH 'apple' AND score() > 0.5
+ ORDER BY dist LIMIT 1
+ """
+ contains "ANN SORT LIMIT: 1"
+ contains "SCORE SORT LIMIT: 0"
+ notContains "SCORE RANGE"
+ }
+
+ test {
+ sql "SELECT id FROM test_score_filter_matrix WHERE score() > 0"
+ exception "score() can only be used in a SELECT that reads one table"
+ }
+}
diff --git a/regression-test/suites/inverted_index_p0/test_score_filter_usage.groovy b/regression-test/suites/inverted_index_p0/test_score_filter_usage.groovy
new file mode 100644
index 00000000000..71533cbfa5b
--- /dev/null
+++ b/regression-test/suites/inverted_index_p0/test_score_filter_usage.groovy
@@ -0,0 +1,379 @@
+// 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.
+
+// score() is supported in a SELECT that reads one table and has a MATCH or SEARCH predicate in
+// its WHERE clause: as one minimum score in WHERE, and in the select list, window functions and
+// ORDER BY of a SELECT that does not aggregate. A scored SELECT in a subquery, view, CTE or set
+// operation needs ORDER BY score() with LIMIT.
+suite("test_score_filter_usage", "p0") {
+ def unsupportedSelect = "score() can only be used in a SELECT that reads one table"
+ def nestedSelect = "score() in a subquery, view, CTE or set operation requires ORDER BY score() with LIMIT"
+
+ sql "DROP TABLE IF EXISTS test_score_filter_usage"
+ sql """
+ CREATE TABLE test_score_filter_usage (
+ id INT,
+ c1 TEXT,
+ c2 TEXT,
+ INDEX idx_c1 (c1) USING INVERTED PROPERTIES (
+ "lower_case" = "true", "parser" = "english", "support_phrase" = "true")
+ ) DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num" = "1", "inverted_index_storage_format" = "V2")
+ """
+ sql """
+ INSERT INTO test_score_filter_usage VALUES
+ (1, 'apple red', 'sweet'),
+ (2, 'apple green', 'sour'),
+ (3, 'banana yellow', 'sweet')
+ """
+
+ // A minimum score without ORDER BY score() LIMIT.
+ order_qt_where_only_score """
+ SELECT id FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ order_qt_projected_score_range """
+ SELECT id, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ order_qt_repeated_score_aliases """
+ SELECT id, score() AS first_score, score() AS second_score
+ FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ order_qt_select_star_score_range """
+ SELECT * FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ // * REPLACE puts score() into the select list like any other item.
+ order_qt_select_star_replace_score """
+ SELECT * REPLACE (score() AS c2) FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ order_qt_table_alias_score_range """
+ SELECT t.id, score() AS s FROM test_score_filter_usage t
+ WHERE t.c1 MATCH 'apple' AND score() > 0.00001
+ """
+ // A table alias of a UNIQUE table sits above the delete sign filter that analysis adds.
+ sql "DROP TABLE IF EXISTS test_score_filter_usage_mow"
+ sql """
+ CREATE TABLE test_score_filter_usage_mow (
+ id INT,
+ c1 TEXT,
+ INDEX idx_c1 (c1) USING INVERTED PROPERTIES ("parser" = "english")
+ ) UNIQUE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num" = "1", "enable_unique_key_merge_on_write" = "true")
+ """
+ sql "INSERT INTO test_score_filter_usage_mow VALUES (1, 'apple red'), (2, 'apple green'), (3, 'banana')"
+ order_qt_mow_alias_score_range """
+ SELECT a.id, score() AS s FROM test_score_filter_usage_mow a
+ WHERE a.c1 MATCH 'apple' AND score() > 0.00001
+ """
+ order_qt_mow_alias_score_topn """
+ SELECT a.id, score() AS s FROM test_score_filter_usage_mow a
+ WHERE a.c1 MATCH 'apple' ORDER BY s DESC LIMIT 10
+ """
+ // A materialized view of the same MATCH has no score, so it cannot answer a minimum score.
+ async_mv_rewrite_fail(context.dbName, "SELECT id, c1 FROM test_score_filter_usage WHERE c1 MATCH 'apple'",
+ "SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() > 0.6",
+ "test_score_filter_usage_mv")
+ order_qt_mv_minimum_score """
+ SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() > 0.6
+ """
+ // The minimum score is a filter of the scan, which reads the score like any other column.
+ explain {
+ sql "SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() >= 0.5"
+ contains "SCORE SORT LIMIT: 0"
+ notContains "SCORE RANGE"
+ }
+ // A scan that keeps the best rows of each segment applies the minimum score before.
+ explain {
+ sql """
+ SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() >= 0.5
+ ORDER BY score() DESC LIMIT 2
+ """
+ contains "SCORE SORT LIMIT: 2"
+ contains "SCORE RANGE: score() >= 0.5"
+ }
+
+ // Without a minimum score, the scan scores every row it returns.
+ order_qt_score_without_range """
+ SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'apple'
+ """
+
+ // Ordinary sorts of the scored rows.
+ qt_ordinary_order_with_offset """
+ SELECT id, c2, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ ORDER BY id LIMIT 1 OFFSET 1
+ """
+ qt_multiple_order_keys """
+ SELECT id, c2, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ ORDER BY s DESC, id DESC LIMIT 1 OFFSET 1
+ """
+ qt_reverse_key_order """
+ SELECT id, c2, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ ORDER BY id DESC LIMIT 1
+ """
+ order_qt_score_sort_without_limit """
+ SELECT id, c2, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ ORDER BY s DESC
+ """
+ test {
+ sql """
+ SELECT id, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ ORDER BY s DESC LIMIT 9223372036854775807 OFFSET 9223372036854775807
+ """
+ exception "limit + offset overflows the long range"
+ }
+
+ // An ordinary TopN on a key computed from score() pushes its TopN filter into the scan, which
+ // reads the score like any other column. One tablet is read in many batches.
+ sql "DROP TABLE IF EXISTS test_score_filter_usage_topn"
+ sql """
+ CREATE TABLE test_score_filter_usage_topn (
+ id INT,
+ grp INT,
+ c1 TEXT,
+ INDEX idx_c1 (c1) USING INVERTED PROPERTIES ("parser" = "english")
+ ) DUPLICATE KEY(id) DISTRIBUTED BY HASH(grp) BUCKETS 4
+ PROPERTIES ("replication_num" = "1")
+ """
+ sql """
+ INSERT INTO test_score_filter_usage_topn
+ SELECT number, 1, CASE WHEN number = 100 THEN 'rare' WHEN number = 15000 THEN 'rare rare rare rare rare'
+ ELSE 'common filler words' END
+ FROM numbers("number" = "20000")
+ """
+ order_qt_score_derived_topn """
+ SELECT /*+ SET_VAR(topn_filter_ratio=1000000, batch_size=32) */ id, CAST(score() AS INT) AS k
+ FROM test_score_filter_usage_topn WHERE c1 MATCH 'rare' AND id % 2 = 0 ORDER BY k DESC LIMIT 1
+ """
+
+ // Window functions of the same SELECT see the score of each row.
+ order_qt_window_same_select """
+ SELECT id, score() AS s, row_number() OVER (ORDER BY id) AS rn
+ FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ order_qt_window_order_by_score """
+ SELECT id, row_number() OVER (ORDER BY score() DESC, id) AS rn
+ FROM test_score_filter_usage WHERE c1 MATCH 'apple'
+ """
+
+ // An aggregating SELECT can only use the minimum score, which the scan evaluates before
+ // COUNT_ON_INDEX counts the remaining rows.
+ qt_count_score_range """
+ SELECT /*+ SET_VAR(enable_count_on_index_pushdown=true) */ count(*) FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ qt_count_score_range_without_pushdown """
+ SELECT /*+ SET_VAR(enable_count_on_index_pushdown=false) */ count(*) FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+ qt_count_high_score_range """
+ SELECT /*+ SET_VAR(enable_count_on_index_pushdown=true) */ count(*) FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 1000000
+ """
+ order_qt_group_by_score_range """
+ SELECT c2, count(*) FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001 GROUP BY c2
+ """
+ order_qt_grouping_sets_score_range """
+ SELECT c2, count(*) FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001 GROUP BY GROUPING SETS ((c2), ())
+ """
+ test {
+ sql "SELECT c2, max(score()) FROM test_score_filter_usage WHERE c1 MATCH 'apple' GROUP BY c2"
+ exception "score() can only be used in the WHERE clause of a SELECT with GROUP BY"
+ }
+
+ // The minimum score must be one score() > literal or score() >= literal.
+ test {
+ sql "SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND CAST(score() AS INT) > 0"
+ exception "score() predicate in WHERE clause must be in the form"
+ }
+ test {
+ sql "SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() < 0.9"
+ exception "score() predicate in WHERE clause must be in the form"
+ }
+ test {
+ sql "SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() > 0.1 AND score() < 0.9"
+ exception "Only one score() range predicate is supported"
+ }
+ test {
+ sql "SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND (score() > 0 OR id = 1)"
+ exception "score() predicate must be a top-level AND condition"
+ }
+
+ // HAVING and QUALIFY run above the scan, where the score is no longer computed.
+ test {
+ sql """
+ SELECT c2, count(*) FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() > 0.00001
+ GROUP BY c2 HAVING c2 MATCH 'sweet'
+ """
+ exception "score(), MATCH and SEARCH cannot be used in HAVING or QUALIFY"
+ }
+ test {
+ sql """
+ SELECT id, score() AS s, row_number() OVER (ORDER BY id) AS rn FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' QUALIFY rn = 1 AND s > 0.00001
+ """
+ exception "score(), MATCH and SEARCH cannot be used in HAVING or QUALIFY"
+ }
+ test {
+ sql """
+ SELECT id, score() AS s, c1 MATCH 'red' AS m, row_number() OVER (PARTITION BY c1 ORDER BY id) AS rn
+ FROM test_score_filter_usage WHERE c1 MATCH 'apple' QUALIFY m AND rn = 1
+ """
+ exception "score(), MATCH and SEARCH cannot be used in HAVING or QUALIFY"
+ }
+
+ // score() is the relevance for the MATCH and SEARCH predicates of its own SELECT on one table.
+ test {
+ sql "SELECT id, score() FROM test_score_filter_usage WHERE c2 = 'sweet'"
+ exception unsupportedSelect
+ }
+ test {
+ sql """
+ SELECT a.id, score() AS s FROM test_score_filter_usage a
+ JOIN test_score_filter_usage b ON a.id = b.id WHERE a.c1 MATCH 'apple'
+ """
+ exception unsupportedSelect
+ }
+ test {
+ sql """
+ SELECT a.id FROM test_score_filter_usage a JOIN test_score_filter_usage b
+ ON a.id = b.id AND score() > 0.00001 WHERE a.c1 MATCH 'apple'
+ """
+ exception unsupportedSelect
+ }
+ test {
+ sql """
+ SELECT id FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() > 0.00001
+ AND id IN (SELECT id FROM test_score_filter_usage WHERE c2 = 'sweet')
+ """
+ exception unsupportedSelect
+ }
+ test {
+ sql """
+ SELECT * FROM (
+ SELECT id, row_number() OVER (ORDER BY id) AS rn FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple'
+ ) w WHERE score() > 0.00001
+ """
+ exception unsupportedSelect
+ }
+ test {
+ sql """
+ WITH c AS (SELECT id, c1 FROM test_score_filter_usage WHERE c1 MATCH 'apple')
+ SELECT id FROM c WHERE score() > 0.00001
+ """
+ exception unsupportedSelect
+ }
+
+ // Without ORDER BY score() LIMIT, a nested scored SELECT would let the predicates of the outer
+ // query into its scan, e.g. an outer MATCH would add to the score.
+ test {
+ sql """
+ SELECT id, s FROM (
+ SELECT id, c1, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ ) x WHERE x.c1 MATCH 'red'
+ """
+ exception nestedSelect
+ }
+ test {
+ sql """
+ SELECT id, s FROM (SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'apple') x
+ WHERE s > 0.00001
+ """
+ exception nestedSelect
+ }
+ test {
+ sql """
+ WITH c AS (SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'apple')
+ SELECT * FROM c
+ """
+ exception nestedSelect
+ }
+ test {
+ sql """
+ SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'apple'
+ UNION ALL
+ SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'red'
+ """
+ exception nestedSelect
+ }
+ // Decorrelation removes ORDER BY score() LIMIT from a correlated subquery.
+ test {
+ sql """
+ SELECT id FROM test_score_filter_usage b
+ WHERE (b.c1 MATCH 'red' OR b.c1 MATCH 'green') AND EXISTS (
+ SELECT 1 FROM test_score_filter_usage a
+ WHERE a.c1 = b.c1 AND a.c1 MATCH 'apple' AND score() > 0.6
+ ORDER BY score() DESC LIMIT 1)
+ """
+ exception "score() cannot be used in a correlated subquery"
+ }
+ order_qt_nested_score_topn_having """
+ SELECT * FROM (
+ SELECT id, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' HAVING c2 = 'sweet' ORDER BY s DESC LIMIT 2
+ ) x
+ """
+ order_qt_nested_score_topn """
+ SELECT x.id, x.s, b.c2 FROM (
+ SELECT id, score() AS s FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001 ORDER BY s DESC LIMIT 2
+ ) x JOIN test_score_filter_usage b ON x.id = b.id
+ WHERE x.s > 0.00001
+ """
+ // ORDER BY the position of score() in the select list.
+ order_qt_nested_score_topn_by_position """
+ SELECT * FROM (
+ SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'apple' ORDER BY 2 DESC LIMIT 2
+ ) x
+ """
+ order_qt_union_score_topn """
+ (SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'green' ORDER BY s DESC LIMIT 1)
+ UNION ALL
+ (SELECT id, score() AS s FROM test_score_filter_usage WHERE c1 MATCH 'red' ORDER BY s DESC LIMIT 1)
+ """
+
+ // A projected MATCH must not add its BM25 score to the one the filter compares (0.4700036).
+ order_qt_projected_match_above_score """
+ SELECT id, c1 MATCH_PHRASE 'apple' AS flag FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.6
+ """
+ order_qt_projected_match_score """
+ SELECT id, score() AS s, c1 MATCH_PHRASE 'apple' AS flag FROM test_score_filter_usage
+ WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+
+ // A common sub-expression virtual column must not keep score() away from its binding.
+ order_qt_cse_score_expressions """
+ SELECT /*+ SET_VAR(experimental_enable_virtual_slot_for_cse=true) */ id,
+ sin(abs(score()) + 1) AS a, cos(abs(score()) + 1) AS b
+ FROM test_score_filter_usage WHERE c1 MATCH 'apple' AND score() > 0.00001
+ """
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org