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 2b5f0599026 [fix](inverted index) Fix score() with MATCH on VARIANT
paths missing from a segment (#71022)
2b5f0599026 is described below
commit 2b5f05990261dfcd873276b033a860c003ffd0af
Author: Jack <[email protected]>
AuthorDate: Wed Dec 2 17:26:46 2026 +0800
[fix](inverted index) Fix score() with MATCH on VARIANT paths missing from
a segment (#71022)
### Background
`score()` ranks rows by BM25 and needs every scored predicate answered
by the inverted index. Since #69053, an AND/OR/NOT whose branches
produced scores fails when any branch has no index result, so scores
cannot leak from a branch evaluated row by row. A VARIANT column stores
a path only in segments whose rows contain it, so `v.content` can be
missing from a whole segment. SEARCH (#69347) proves such absence from
the segment's VARIANT metadata and treats the path as matching nothing;
MATCH did not.
### What problem does this PR solve?
Issue Number: None
Related PR: #69053 (added the incomplete-evaluation error), #69347
(SEARCH's absent-path proof, reused here), #38908 (added the AND early
exit fixed here)
PR Type: Bugfix
Problem Summary:
`score()` over MATCH predicates combined with AND/OR/NOT on VARIANT
paths fails when some segment does not store one of the paths, although
`search()` over the same paths works. This PR moves #69347's absence
proof into one shared check and lets MATCH use it: on a path the segment
provably does not store, MATCH is NULL on every row, which the index now
answers exactly. Paths that are stored without an index keep row
evaluation. Two edge cases had to be handled with it: the proof now
finds legacy dotted keys (`v['a.b']` over a stored `a.b.c`), and an
index-evaluated AND no longer stops while NULL rows can still turn
FALSE, which also fixes `NOT (... AND ...)` on ordinary nullable
columns. Most of the diff is tests.
```sql
-- v is a VARIANT with an english inverted index; each INSERT writes one
segment
INSERT INTO t VALUES (1, '{"title":"apple search guide","content":"search
database engine"}'), ...;
INSERT INTO t VALUES (3, '{"title":"apple archive"}'), (4,
'{"title":"database manual"}');
INSERT INTO t VALUES (5, '{"content":"apple search"}'), (6,
'{"content":"database analytics"}');
SELECT id, score() FROM t WHERE v['title'] MATCH_ANY 'apple' OR
v['content'] MATCH_ANY 'search'
ORDER BY score() DESC LIMIT 100;
```
| | Result |
| --- | --- |
| Before | `[E-6001]Cannot score a compound predicate with incomplete
index evaluation` |
| After | ids 9, 1, 3, 5 with 1.6659, 1.3164, 0.833, 0.833: the same as
`search('v.title:apple OR v.content:search')` |
### Details
- **Change map:** about 550 changed lines: 125 added and 45 removed in
production code, of which 51 are #69347's proof moved from `vsearch.cpp`
to `vexpr_context.cpp` and 7 its legacy dotted-key check; the MATCH
change is 48 lines in `vmatch_predicate.{h,cpp}`, and the AND early exit
7 lines in `vcompound_pred.h`; 378 lines are tests (BE UT 227,
regression suite 120 and its .out 31).
- **Frequency:** Always, when `score()` ranks a scored AND/OR/NOT of
MATCH predicates on VARIANT paths and at least one segment does not
store one of the paths, as in the example above.
- **Root cause:** in a segment without the path there is no index
iterator for it, so `VExpr::_evaluate_inverted_index` returns OK without
a result and the MATCH falls back to row evaluation.
`VCompoundPred::evaluate_inverted_index` then sees an incomplete branch
next to a scored one and returns the error added by #69053. SEARCH does
not fail because `verify_missing_variant_path` (#69347) proves the path
absent and answers it as matching nothing.
- **Why existing tests missed it:** BE: `vcompound_pred_score_test.cpp`
(#69053) checks the error with mocked incomplete branches, and
`test_search_distinguishes_unindexed_historical_variant_path` (#69347)
covers SEARCH only; no unit test evaluated MATCH on a VARIANT path
missing from a segment. Regression:
`search/test_search_score_boolean_branches` (#69053) scores MATCH OR on
ordinary columns written in one segment, and
`inverted_index_p0/test_bm25_score_variant` scores a single MATCH on
one-insert VARIANT tables; none had segments that miss one branch's
path.
- **Fix:** `IndexExecContext::is_variant_path_absent` now holds #69347's
proof, and SEARCH keeps its contract and messages on top of it.
`VMatchPredicate` calls it when its own index evaluation left no result
for an extracted VARIANT path without an index iterator, and stores an
exact result: no matching rows, every row NULL. That is what MATCH on
NULL gives, so NOT and AND/OR keep their three-valued results. The fix
sits in the MATCH predicate because only the predicate knows its NULL
result; the compound scoring check stays as it is. For segments without
escaped keys, the proof also looks for a prefix under the split path, as
`get_subcolumn_meta_by_path` and the read plan do, so FE's single
component `a.b` finds a stored `a.b.c` in inline-metadata (V2) segments;
`VariantColumnReader::has_prefix_path`, which the read plan shares, is
unchanged. `VCompoundPred` AND used to stop at the first branch with no
TRUE row and keep its NULL rows, so `NOT (title MATCH_ANY 'x' AND
content MATCH_ANY 'hit')` dropped a row with a NULL title and a
non-matching content; it now stops only when no row is TRUE or NULL.
That case needs `disable_nereids_expression_rules='SIMPLIFY_NOT_EXPR'`,
since the default rewrite turns NOT over AND into OR.
- **Other paths and branches:** The AND early exit dates from #38908 and
is on branch-4.1 and branch-4.2. SEARCH: not affected, it already had
the proof and now shares it. Comparison, IN, and IS NULL predicates on
an absent VARIANT path keep their row-level fallback (their results on
NULL differ per function), so combined with a scored MATCH under
`score()` they still fail with the same error; not fixed here. MATCH on
the VARIANT root (values index): not affected, the root is never absent.
branch-4.1 and branch-4.2 have the bug: both carry #69053 (#69160,
#69265) and #69347 (#69603, #69361); a backport needs to adapt the moved
proof to their root-reader lookup by column uid.
- **Behavior change:** without `score()`, a MATCH on a VARIANT path that
a segment does not store is now answered by the inverted index instead
of row evaluation. The rows are the same (checked against row evaluation
with `enable_inverted_index_query=false`), but such segments now count
in the profile's inverted-index counters, and the scan may skip reading
the all-NULL path.
### Testing
All local, ASAN, single BE.
- BE UT `test_match_returns_null_rows_for_absent_variant_path` (new):
MATCH on an absent path of a real unindexed segment gets {no hits, 2
NULL rows}, also under NOT. Fails on the base c7747fa64cb (no index
result) and with only the MATCH hook disabled; passes with the fix.
- BE UT `test_match_reads_rows_for_unindexed_variant_path` (new): a
stored but unindexed path keeps row evaluation.
`test_search_distinguishes_unindexed_historical_variant_path` (#69347)
passes before and after.
- BE UT `test_match_reads_rows_for_legacy_dotted_variant_path` (new): on
an inline-metadata (V2) segment storing `a.b.c`, MATCH on the component
`a.b` keeps row evaluation; it fails (MATCH answered as absent) without
the split-path check.
- BE UT
`VCompoundPredScoreTest.AndWithOnlyNullRowsLeftEvaluatesLaterBranches`
(new): NOT(AND({NULL on both rows}, {FALSE})) is TRUE on both rows; it
failed before the AND change.
- BE UT suites around the change (VARIANT reader, SEARCH, MATCH,
compound score): 353 passed, 2 skipped (NestedGroup not built). A wider
earlier run had 3 failures in code this PR does not touch:
`ValuesIndexExistsOnlyInSniiSegments/{0,2}` (#69761's test vs #70788's
status code) and `AsyncCacheWriteManagerTest`.
- Regression `search/test_search_score_boolean_branches` (new VARIANT
and nullable cases): `variant_match_or` fails on the base with E-6001;
`nullable_not_and`, `variant_not_and_absent`, and `variant_dotted_path`
give 3 / 2,6 / no rows on the first PR head, and 2,3 / 2,4,6 / 1 with
the fixes, the same as row evaluation with the index disabled and as the
hand-derived three-valued results.
- Regression: all 46 `search/` suites, 12 null-semantics and compound
suites under `inverted_index_p0/` (`test_match_or_null_semantics`,
`test_cross_field_or_with_null`, `test_is_null_expr`, ...), and 6
VARIANT/MATCH score suites pass.
- clang-format, `check-format.sh`, `check-build-hygiene.sh`, clang-tidy
on changed lines: clean.
---
be/src/exprs/vcompound_pred.h | 7 +-
be/src/exprs/vexpr_context.cpp | 58 ++++++++
be/src/exprs/vexpr_context.h | 8 ++
be/src/exprs/vmatch_predicate.cpp | 44 ++++++
be/src/exprs/vmatch_predicate.h | 4 +
be/src/exprs/vsearch.cpp | 49 +------
be/test/exprs/vcompound_pred_score_test.cpp | 67 +++++++++
.../variant/variant_column_writer_reader_test.cpp | 160 +++++++++++++++++++++
.../search/test_search_score_boolean_branches.out | 31 ++++
.../test_search_score_boolean_branches.groovy | 120 ++++++++++++++++
10 files changed, 503 insertions(+), 45 deletions(-)
diff --git a/be/src/exprs/vcompound_pred.h b/be/src/exprs/vcompound_pred.h
index 263f46d79fb..1e092427c2a 100644
--- a/be/src/exprs/vcompound_pred.h
+++ b/be/src/exprs/vcompound_pred.h
@@ -346,8 +346,11 @@ public:
res &= *index_result;
}
- if (res.get_data_bitmap()->isEmpty()) {
- break; // Early exit if result is empty
+ // Stop only once every row is FALSE. A NULL row can still
become FALSE in a
+ // later branch: NULL AND FALSE is FALSE, so NOT (NULL AND
FALSE) keeps it.
+ if (res.get_data_bitmap()->isEmpty() &&
+ (res.get_null_bitmap() == nullptr ||
res.get_null_bitmap()->isEmpty())) {
+ break;
}
} else {
all_pass = false;
diff --git a/be/src/exprs/vexpr_context.cpp b/be/src/exprs/vexpr_context.cpp
index 32b15201e15..cd915b96548 100644
--- a/be/src/exprs/vexpr_context.cpp
+++ b/be/src/exprs/vexpr_context.cpp
@@ -38,8 +38,13 @@
#include "exprs/vexpr.h"
#include "runtime/runtime_state.h"
#include "runtime/thread_context.h"
+#include "storage/iterators.h"
#include "storage/olap_common.h"
+#include "storage/schema.h"
#include "storage/segment/column_reader.h"
+#include "storage/segment/segment.h"
+#include "storage/segment/variant/variant_column_reader.h"
+#include "util/json/path_in_data.h"
#include "util/simd/bits.h"
namespace doris {
@@ -48,6 +53,59 @@ class RowDescriptor;
namespace doris {
+Status IndexExecContext::is_variant_path_absent(int32_t read_ordinal,
+ const PathInData&
relative_path,
+ bool* absent) const {
+ DORIS_CHECK(_segment != nullptr);
+ DORIS_CHECK_GE(read_ordinal, 0);
+ DORIS_CHECK_LT(static_cast<size_t>(read_ordinal),
_read_schema->num_read_columns());
+ DORIS_CHECK(_column_iter_opts.stats != nullptr);
+ const auto& column = *_read_schema->column(read_ordinal);
+ StorageReadOptions read_options(*_column_iter_opts.stats);
+ read_options.io_ctx = _column_iter_opts.io_ctx;
+ std::shared_ptr<segment_v2::VariantColumnReader> reader;
+ Status st = _segment->get_variant_root_reader(column, read_options,
&reader);
+ if (st.is<ErrorCode::NOT_FOUND>()) {
+ // After DROP v(uid=1), ADD v(uid=2), an old segment cannot contain
this scan's root.
+ // Resolve by the current uid so historical values of the same name
cannot match.
+ *absent = true;
+ return Status::OK();
+ }
+ RETURN_IF_ERROR(st);
+ DORIS_CHECK(reader != nullptr);
+ RETURN_IF_ERROR(
+ reader->load_external_meta_once(_column_iter_opts.stats,
&_column_iter_opts.io_ctx));
+ const auto* stats = reader->get_stats();
+ // Doc statistics enumerate stored paths without the sparse statistics
limit. For example,
+ // a segment containing only `string4` can prove `string5` absent even in
doc mode.
+ // An opaque root/ancestor value may contain the requested path, so it
remains unavailable.
+ bool in_doc = stats->existed_in_doc_value_column("") ||
+
stats->has_prefix_path_in_doc_value_column(relative_path.get_path() + ".");
+ std::string ancestor = relative_path.get_path();
+ while (!in_doc) {
+ in_doc = stats->existed_in_doc_value_column(ancestor);
+ const auto dot = ancestor.rfind('.');
+ if (dot == std::string::npos) {
+ break;
+ }
+ ancestor.resize(dot);
+ }
+ // Without escaped keys the key `a.b` and the path a -> b are stored
alike, and the read plan
+ // reads FE's component ['a.b'] through the split path. For example, a
stored `a.b.c` gives
+ // `v['a.b']` the value {"c":...}, so the split path must count as a
prefix too.
+ const bool has_prefix =
+ reader->has_prefix_path(relative_path, _column_iter_opts.stats,
+ &_column_iter_opts.io_ctx) ||
+ (reader->path_encoding() == 0 &&
+ reader->has_prefix_path(PathInData(relative_path.get_path()),
_column_iter_opts.stats,
+ &_column_iter_opts.io_ctx));
+ // Truncated sparse statistics cannot prove absence, nor can an existing
unindexed path.
+ *absent = reader->get_subcolumn_meta_by_path(relative_path) == nullptr &&
!has_prefix &&
+ !reader->exist_in_sparse_column(relative_path) &&
+ !reader->is_exceeded_sparse_column_limit() && !in_doc &&
!stats->has_nested_group;
+ return Status::OK();
+}
+
VExprContext::VExprContext(VExprSPtr expr) : _root(std::move(expr)) {}
VExprContext::~VExprContext() {
diff --git a/be/src/exprs/vexpr_context.h b/be/src/exprs/vexpr_context.h
index 367aeef515d..b699340e641 100644
--- a/be/src/exprs/vexpr_context.h
+++ b/be/src/exprs/vexpr_context.h
@@ -45,6 +45,7 @@
#include "storage/segment/column_iterator_options.h"
namespace doris {
+class PathInData;
class RowDescriptor;
class ReadSchema;
using ReadSchemaSPtr = std::shared_ptr<ReadSchema>;
@@ -107,6 +108,13 @@ public:
const segment_v2::ColumnIteratorOptions& column_iter_opts() const { return
_column_iter_opts; }
+ // Sets *absent to whether this segment proves that the VARIANT root read
at `read_ordinal`
+ // stores nothing at `relative_path`, so every row of the segment reads
NULL there. A missing
+ // index iterator proves nothing: `v.a` may live in the sparse or
doc-value column, or in a
+ // segment written before its index existed. Requires a segment.
+ Status is_variant_path_absent(int32_t read_ordinal, const PathInData&
relative_path,
+ bool* absent) const;
+
bool has_index_result_for_expr(const VExpr* expr) const {
return _index_result_bitmap.contains(expr);
}
diff --git a/be/src/exprs/vmatch_predicate.cpp
b/be/src/exprs/vmatch_predicate.cpp
index 30bfbaa7ef4..45df6f96030 100644
--- a/be/src/exprs/vmatch_predicate.cpp
+++ b/be/src/exprs/vmatch_predicate.cpp
@@ -48,7 +48,9 @@
#include "storage/index/index_query_context.h"
#include "storage/index/inverted/analysis/analyzer/analyzer.h"
#include "storage/index/inverted/inverted_index_reader.h"
+#include "storage/schema.h"
#include "storage/segment/segment.h"
+#include "util/json/path_in_data.h"
namespace doris {
class RowDescriptor;
@@ -179,6 +181,10 @@ Status
VMatchPredicate::evaluate_inverted_index(VExprContext* context, uint32_t
index_context->set_analyzer_ctx_for_expr(this, _analyzer_ctx);
}
auto status = _evaluate_inverted_index(context, _function,
segment_num_rows);
+ if (status.ok() && index_context != nullptr &&
+ !index_context->has_index_result_for_expr(this)) {
+ RETURN_IF_ERROR(_evaluate_absent_variant_path(*index_context,
segment_num_rows));
+ }
const auto& input = get_child(0);
if (index_context != nullptr && input->is_slot_ref() &&
input->result_type() == TYPE_VARIANT) {
@@ -204,6 +210,44 @@ Status
VMatchPredicate::evaluate_inverted_index(VExprContext* context, uint32_t
return status;
}
+// A MATCH on a VARIANT path that this segment does not store is NULL on every
row, which the
+// index can answer exactly. Without that answer the MATCH falls back to row
evaluation, and
+// score() then rejects an AND/OR whose other branches were scored. For
example, in a segment
+// written from {"title":"apple archive"}, `v['content'] MATCH 'search'` is
answered here, so
+// `v['title'] MATCH 'apple' OR v['content'] MATCH 'search'` can still score
the title branch.
+Status VMatchPredicate::_evaluate_absent_variant_path(IndexExecContext&
index_context,
+ uint32_t
segment_num_rows) {
+ // The planner reads `v['content']` as a path slot, usually under a cast
to the MATCH type.
+ // Without a segment there is no VARIANT metadata to prove the path absent
from.
+ const auto input = expr_without_cast(get_child(0));
+ if (!input->is_slot_ref() || index_context.segment() == nullptr) {
+ return Status::OK();
+ }
+ // A path with an index iterator has already been answered or declined by
its index, and
+ // only an extracted VARIANT path can be absent from a segment.
+ const int column_id = assert_cast<const
VSlotRef*>(input.get())->column_id();
+ const auto& column = *index_context.read_schema()->column(column_id);
+ if (index_context.get_inverted_index_iterator(column_id) != nullptr ||
+ !column.is_extracted_column()) {
+ return Status::OK();
+ }
+ bool absent = false;
+ RETURN_IF_ERROR(index_context.is_variant_path_absent(
+ column_id, column.path_info_ptr()->copy_pop_front(), &absent));
+ // A path that is stored but has no index, such as one in the sparse
column, still needs
+ // row evaluation.
+ if (!absent) {
+ return Status::OK();
+ }
+ auto null_rows = std::make_shared<roaring::Roaring>();
+ null_rows->addRange(0, segment_num_rows);
+ index_context.set_index_result_for_expr(
+ this,
+ InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(),
std::move(null_rows)));
+ index_context.set_true_for_index_status(this, column_id);
+ return Status::OK();
+}
+
const std::string& VMatchPredicate::get_analyzer_key() const {
return _analyzer_ctx->analyzer_key;
}
diff --git a/be/src/exprs/vmatch_predicate.h b/be/src/exprs/vmatch_predicate.h
index d158ce7d951..7e5292f783d 100644
--- a/be/src/exprs/vmatch_predicate.h
+++ b/be/src/exprs/vmatch_predicate.h
@@ -27,6 +27,7 @@
#include "storage/index/inverted/analysis/inverted_index_parser.h"
namespace doris {
+class IndexExecContext;
class RowDescriptor;
class RuntimeState;
class TExprNode;
@@ -61,6 +62,9 @@ public:
FunctionBasePtr function() { return _function; }
private:
+ Status _evaluate_absent_variant_path(IndexExecContext& index_context,
+ uint32_t segment_num_rows);
+
FunctionBasePtr _function;
std::string _expr_name;
std::string _function_name;
diff --git a/be/src/exprs/vsearch.cpp b/be/src/exprs/vsearch.cpp
index 03972533984..226f1a20b2e 100644
--- a/be/src/exprs/vsearch.cpp
+++ b/be/src/exprs/vsearch.cpp
@@ -33,9 +33,8 @@
#include "runtime/runtime_state.h"
#include "storage/index/inverted/inverted_index_reader.h"
#include "storage/schema.h"
-#include "storage/segment/segment.h"
-#include "storage/segment/variant/variant_column_reader.h"
#include "util/hash_util.hpp"
+#include "util/json/path_in_data.h"
#include "util/thrift_util.h"
namespace doris {
@@ -67,51 +66,15 @@ void add_search_binding_diagnostic(const IndexExecContext*
index_context,
// old rowsets may contain values without an executable SEARCH index.
Status verify_missing_variant_path(const TSearchFieldBinding& binding, int
column_index,
IndexExecContext* index_context) {
- auto* segment = index_context->segment();
- if (segment == nullptr || !binding.__isset.parent_field_name ||
+ if (index_context->segment() == nullptr ||
!binding.__isset.parent_field_name ||
!binding.__isset.subcolumn_path) {
return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
"SEARCH cannot establish missing path '{}'",
binding.field_name);
}
- const auto& read_schema = index_context->read_schema();
- DORIS_CHECK_GE(column_index, 0);
- DORIS_CHECK_LT(static_cast<size_t>(column_index),
read_schema->num_read_columns());
- const auto& column = *read_schema->column(column_index);
- const auto& opts = index_context->column_iter_opts();
- DORIS_CHECK(opts.stats != nullptr);
- StorageReadOptions read_options(*opts.stats);
- read_options.io_ctx = opts.io_ctx;
- std::shared_ptr<VariantColumnReader> reader;
- Status st = segment->get_variant_root_reader(column, read_options,
&reader);
- if (st.is<ErrorCode::NOT_FOUND>()) {
- // After DROP v(uid=1), ADD v(uid=2), an old segment cannot contain
this scan's root.
- // Resolve by the current uid so historical values of the same name
cannot match.
- return Status::OK();
- }
- RETURN_IF_ERROR(st);
- DORIS_CHECK(reader != nullptr);
- RETURN_IF_ERROR(reader->load_external_meta_once(opts.stats, &opts.io_ctx));
- const PathInData path(binding.subcolumn_path);
- const auto* stats = reader->get_stats();
- // Doc statistics enumerate stored paths without the sparse statistics
limit. For example,
- // a segment containing only `string4` can prove `string5` absent even in
doc mode.
- // An opaque root/ancestor value may contain the requested path, so it
remains unavailable.
- bool in_doc = stats->existed_in_doc_value_column("") ||
- stats->has_prefix_path_in_doc_value_column(path.get_path() +
".");
- std::string ancestor = path.get_path();
- while (!in_doc) {
- in_doc = stats->existed_in_doc_value_column(ancestor);
- const auto dot = ancestor.rfind('.');
- if (dot == std::string::npos) {
- break;
- }
- ancestor.resize(dot);
- }
- // Truncated sparse statistics cannot prove absence, nor can an existing
unindexed path.
- if (reader->get_subcolumn_meta_by_path(path) != nullptr ||
- reader->has_prefix_path(path, opts.stats, &opts.io_ctx) ||
- reader->exist_in_sparse_column(path) ||
reader->is_exceeded_sparse_column_limit() ||
- in_doc || stats->has_nested_group) {
+ bool absent = false;
+ RETURN_IF_ERROR(index_context->is_variant_path_absent(
+ column_index, PathInData(binding.subcolumn_path), &absent));
+ if (!absent) {
return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
"SEARCH index unavailable for Variant field '{}'",
binding.field_name);
}
diff --git a/be/test/exprs/vcompound_pred_score_test.cpp
b/be/test/exprs/vcompound_pred_score_test.cpp
index 87f3b0bac54..33f9f7ef1d6 100644
--- a/be/test/exprs/vcompound_pred_score_test.cpp
+++ b/be/test/exprs/vcompound_pred_score_test.cpp
@@ -75,6 +75,45 @@ private:
float _score;
};
+// Publishes a fixed exact three-valued index result without scores.
+class ThreeValuedBitmapExpr final : public VExpr {
+public:
+ ThreeValuedBitmapExpr(std::initializer_list<uint32_t> true_rows,
+ std::initializer_list<uint32_t> null_rows) {
+ set_node_type(TExprNodeType::MATCH_PRED);
+ for (uint32_t row : true_rows) {
+ _true_rows.add(row);
+ }
+ for (uint32_t row : null_rows) {
+ _null_rows.add(row);
+ }
+ }
+
+ const std::string& expr_name() const override {
+ static const std::string name = "ThreeValuedBitmapExpr";
+ return name;
+ }
+
+ 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();
+ }
+
+ Status evaluate_inverted_index(VExprContext* context, uint32_t) override {
+ context->get_index_context()->set_index_result_for_expr(
+ this, segment_v2::InvertedIndexResultBitmap(
+ std::make_shared<roaring::Roaring>(_true_rows),
+ std::make_shared<roaring::Roaring>(_null_rows)));
+ return Status::OK();
+ }
+
+private:
+ roaring::Roaring _true_rows;
+ roaring::Roaring _null_rows;
+};
+
class UnindexedExpr final : public VExpr {
public:
const std::string& expr_name() const override {
@@ -222,5 +261,33 @@ TEST(VCompoundPredScoreTest,
IncompleteScoredBranchReturnsErrorWithoutPublishing
EXPECT_TRUE(parent_similarity->release_scores().empty());
}
+TEST(VCompoundPredScoreTest, AndWithOnlyNullRowsLeftEvaluatesLaterBranches) {
+ // NOT (NULL AND FALSE) is TRUE on both rows. An AND that stopped after
its first branch
+ // would keep both rows NULL, and NOT would then reject them.
+ auto conjunction = make_compound(
+ TExprOpcode::COMPOUND_AND,
+
std::make_shared<ThreeValuedBitmapExpr>(std::initializer_list<uint32_t> {},
+
std::initializer_list<uint32_t> {0, 1}),
+
std::make_shared<ThreeValuedBitmapExpr>(std::initializer_list<uint32_t> {},
+
std::initializer_list<uint32_t> {}));
+ auto root = make_not(conjunction);
+
+ std::vector<std::unique_ptr<segment_v2::IndexIterator>> iterators;
+ std::vector<IndexFieldNameAndTypePair> storage_types;
+ std::unordered_map<ColumnId, std::unordered_map<const VExpr*, bool>>
status_map;
+ segment_v2::ColumnIteratorOptions iterator_options;
+ auto index_context = std::make_shared<IndexExecContext>(
+ iterators, storage_types, status_map, nullptr, nullptr,
iterator_options,
+ std::make_shared<ReadSchema>(std::vector<TabletColumnPtr> {}));
+ auto expr_context = VExprContext::create_shared(root);
+ expr_context->set_index_context(index_context);
+
+ ASSERT_TRUE(root->evaluate_inverted_index(expr_context.get(), 2).ok());
+ const auto* result = index_context->get_index_result_for_expr(root.get());
+ ASSERT_NE(result, nullptr);
+ EXPECT_EQ(result->get_data_bitmap()->cardinality(), 2);
+ EXPECT_TRUE(result->get_null_bitmap()->isEmpty());
+}
+
} // namespace
} // namespace doris
diff --git a/be/test/storage/variant/variant_column_writer_reader_test.cpp
b/be/test/storage/variant/variant_column_writer_reader_test.cpp
index ecf1da7d9de..f90f3927e1b 100644
--- a/be/test/storage/variant/variant_column_writer_reader_test.cpp
+++ b/be/test/storage/variant/variant_column_writer_reader_test.cpp
@@ -54,8 +54,13 @@
#include "exec/rowid_fetcher.h"
#include "exprs/function/search/function_search.h"
#include "exprs/function/search/variant_inverted_index_search.h"
+#include "exprs/function/simple_function_factory.h"
+#include "exprs/vcast_expr.h"
+#include "exprs/vcompound_pred.h"
#include "exprs/vectorized_fn_call.h"
#include "exprs/vexpr_context.h"
+#include "exprs/vliteral.h"
+#include "exprs/vmatch_predicate.h"
#include "exprs/vsearch.h"
#include "exprs/vslot_ref.h"
#include "gtest/gtest.h"
@@ -8763,6 +8768,161 @@ TEST_F(VariantColumnWriterReaderTest,
test_search_distinguishes_unindexed_histor
}
}
+// Index evaluation of NOT(MATCH_ANY(CAST(v.<path> AS STRING), 'hit')), the
form the planner sends
+// for `NOT v['<path>'] MATCH_ANY 'hit'`. It owns everything the index context
refers to.
+struct NegatedMatchOnPath {
+ TabletColumnPtr leaf;
+ std::shared_ptr<VMatchPredicate> match;
+ VExprSPtr negation;
+ std::vector<std::unique_ptr<segment_v2::IndexIterator>> no_indexes;
+ std::vector<IndexFieldNameAndTypePair> types;
+ std::unordered_map<ColumnId, std::unordered_map<const VExpr*, bool>>
status_map;
+ OlapReaderStatistics stats;
+ std::shared_ptr<IndexExecContext> scan;
+ Status status;
+};
+
+static std::shared_ptr<VMatchPredicate> make_match_any_hit(const TabletColumn&
leaf) {
+ const auto text_type = make_nullable(std::make_shared<DataTypeString>());
+ TMatchPredicate match;
+ match.__set_parser_type("english");
+ match.__set_parser_lowercase(true);
+ TFunctionName name;
+ name.__set_function_name("match_any");
+ TFunction fn;
+ fn.__set_name(name);
+ fn.__set_binary_type(TFunctionBinaryType::BUILTIN);
+ fn.__set_arg_types({create_type_desc(TYPE_STRING),
create_type_desc(TYPE_STRING)});
+ fn.__set_ret_type(create_type_desc(TYPE_BOOLEAN));
+ TExprNode node;
+ node.__set_node_type(TExprNodeType::MATCH_PRED);
+ node.__set_type(create_type_desc(TYPE_BOOLEAN));
+ node.__set_is_nullable(true);
+ node.__set_num_children(2);
+ node.__set_fn(fn);
+ node.__set_match_predicate(match);
+ auto predicate = VMatchPredicate::create_shared(node);
+ TExprNode cast_node;
+ cast_node.__set_node_type(TExprNodeType::CAST_EXPR);
+ cast_node.__set_type(create_type_desc(TYPE_STRING));
+ cast_node.__set_is_nullable(true);
+ cast_node.__set_num_children(1);
+ auto cast = VCastExpr::create_shared(cast_node);
+ cast->_target_data_type = text_type;
+ auto slot = std::make_shared<VSlotRef>();
+ slot->set_node_type(TExprNodeType::SLOT_REF);
+ slot->set_column_id(0);
+ slot->_column_name = &leaf.name();
+ cast->add_child(slot);
+ predicate->add_child(cast);
+ TStringLiteral text;
+ text.__set_value("hit");
+ TExprNode literal;
+ literal.__set_node_type(TExprNodeType::STRING_LITERAL);
+ literal.__set_type(create_type_desc(TYPE_STRING));
+ literal.__set_string_literal(text);
+ predicate->add_child(VLiteral::create_shared(literal));
+ predicate->_function = SimpleFunctionFactory::instance().get_function(
+ "match_any",
+ {{nullptr, text_type, "v"}, {nullptr,
std::make_shared<DataTypeString>(), "q"}},
+ make_nullable(std::make_shared<DataTypeUInt8>()));
+ DORIS_CHECK(predicate->_function != nullptr);
+ return predicate;
+}
+
+static std::unique_ptr<NegatedMatchOnPath> evaluate_negated_match_on_path(
+ segment_v2::Segment* segment, const std::string& path) {
+ auto run = std::make_unique<NegatedMatchOnPath>();
+ const auto& parent = segment->tablet_schema()->column(0);
+ auto leaf = std::make_shared<TabletColumn>();
+ leaf->set_name(parent.name() + "." + path);
+ leaf->set_type(FieldType::OLAP_FIELD_TYPE_STRING);
+ leaf->set_unique_id(-1);
+ leaf->set_parent_unique_id(parent.unique_id());
+ leaf->set_is_nullable(true);
+ // FE sends `v['a.b']` as the single path component `a.b`.
+ leaf->set_path_info(PathInData(parent.name(), std::vector<std::string>
{path}));
+ run->leaf = leaf;
+ run->match = make_match_any_hit(*leaf);
+ TExprNode not_node;
+ not_node.__set_node_type(TExprNodeType::COMPOUND_PRED);
+ not_node.__set_opcode(TExprOpcode::COMPOUND_NOT);
+ not_node.__set_type(create_type_desc(TYPE_BOOLEAN));
+ not_node.__set_is_nullable(true);
+ not_node.__set_num_children(1);
+ run->negation = VCompoundPred::create_shared(not_node);
+ run->negation->add_child(run->match);
+
+ run->no_indexes.resize(1);
+ run->types = {{leaf->name(), std::make_shared<DataTypeString>()}};
+ run->status_map[0][run->match.get()] = false;
+ segment_v2::ColumnIteratorOptions opts;
+ opts.stats = &run->stats;
+ run->scan = std::make_shared<IndexExecContext>(
+ run->no_indexes, run->types, run->status_map, nullptr, segment,
opts,
+ std::make_shared<ReadSchema>(std::vector<TabletColumnPtr> {leaf}));
+ VExprContext context(run->negation);
+ context.set_index_context(run->scan);
+ run->status = run->negation->evaluate_inverted_index(&context, 2);
+ return run;
+}
+
+TEST_F(VariantColumnWriterReaderTest,
test_match_returns_null_rows_for_absent_variant_path) {
+ init_variant_tablet(41006);
+ auto rowset = create_variant_rowset({{R"({"missing":"hit"})", R"({})"}},
1);
+ std::vector<segment_v2::SegmentSharedPtr> segments;
+
ASSERT_TRUE(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments).ok());
+ ASSERT_EQ(1, segments.size());
+
+ // No row stores `absent`, so the MATCH is NULL on both rows, and so is
its negation.
+ const auto run = evaluate_negated_match_on_path(segments.front().get(),
"absent");
+ ASSERT_TRUE(run->status.ok()) << run->status;
+ for (const VExpr* expr :
+ std::initializer_list<const VExpr*> {run->match.get(),
run->negation.get()}) {
+ const auto* result = run->scan->get_index_result_for_expr(expr);
+ ASSERT_NE(nullptr, result);
+ EXPECT_TRUE(result->get_data_bitmap()->isEmpty());
+ EXPECT_EQ(2, result->get_null_bitmap()->cardinality());
+ }
+ EXPECT_TRUE(run->status_map[0][run->match.get()]);
+}
+
+TEST_F(VariantColumnWriterReaderTest,
test_match_reads_rows_for_unindexed_variant_path) {
+ init_variant_tablet(41007);
+ auto rowset = create_variant_rowset({{R"({"missing":"hit"})", R"({})"}},
1);
+ std::vector<segment_v2::SegmentSharedPtr> segments;
+
ASSERT_TRUE(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments).ok());
+ ASSERT_EQ(1, segments.size());
+ const auto& parent = segments.front()->tablet_schema()->column(0);
+
ASSERT_TRUE(segments.front()->tablet_schema()->inverted_indexs(parent.unique_id()).empty());
+
+ // Row 0 stores "hit" at `missing` without an index, so only row
evaluation can answer it.
+ const auto run = evaluate_negated_match_on_path(segments.front().get(),
"missing");
+ ASSERT_TRUE(run->status.ok()) << run->status;
+ EXPECT_FALSE(run->scan->has_index_result_for_expr(run->match.get()));
+ EXPECT_FALSE(run->scan->has_index_result_for_expr(run->negation.get()));
+ EXPECT_FALSE(run->status_map[0][run->match.get()]);
+}
+
+TEST_F(VariantColumnWriterReaderTest,
test_match_reads_rows_for_legacy_dotted_variant_path) {
+ init_variant_tablet(41008);
+ // V2 keeps the path metadata inline, so no external meta store can answer
the prefix `a.b.`.
+ init_tablet_from_current_schema(41008,
TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V2);
+ auto rowset = create_variant_rowset({{R"({"a":{"b":{"c":"hit"}}})",
R"({})"}}, 1);
+ std::vector<segment_v2::SegmentSharedPtr> segments;
+
ASSERT_TRUE(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments).ok());
+ ASSERT_EQ(1, segments.size());
+
+ // Without escaped keys, the segment stores row 0 under a -> b -> c, and
the read plan reads
+ // `v['a.b']` from there as {"c":"hit"}. The path is stored, so only row
evaluation can
+ // answer the MATCH.
+ const auto run = evaluate_negated_match_on_path(segments.front().get(),
"a.b");
+ ASSERT_TRUE(run->status.ok()) << run->status;
+ EXPECT_FALSE(run->scan->has_index_result_for_expr(run->match.get()));
+ EXPECT_FALSE(run->scan->has_index_result_for_expr(run->negation.get()));
+ EXPECT_FALSE(run->status_map[0][run->match.get()]);
+}
+
TEST_F(VariantColumnWriterReaderTest,
test_nested_search_uses_current_parent_uid) {
init_variant_tablet(41003);
auto rowset = create_variant_rowset({{R"({"items":[{"msg":"old"}]})"}}, 1);
diff --git a/regression-test/data/search/test_search_score_boolean_branches.out
b/regression-test/data/search/test_search_score_boolean_branches.out
index ba8d7a888cb..6c5a3a4c797 100644
--- a/regression-test/data/search/test_search_score_boolean_branches.out
+++ b/regression-test/data/search/test_search_score_boolean_branches.out
@@ -58,3 +58,34 @@
8 0
9 0.4932
+-- !variant_search --
+1 1.3164
+3 0.833
+5 0.833
+9 1.6659
+
+-- !variant_match_or --
+1 1.3164
+3 0.833
+5 0.833
+9 1.6659
+
+-- !variant_not_absent --
+1 0.6582
+2 0
+3 0.833
+6 0
+9 0.833
+
+-- !nullable_not_and --
+2
+3
+
+-- !variant_not_and_absent --
+2
+4
+6
+
+-- !variant_dotted_path --
+1
+
diff --git
a/regression-test/suites/search/test_search_score_boolean_branches.groovy
b/regression-test/suites/search/test_search_score_boolean_branches.groovy
index 87bfb8f4e2c..c2545b8f81a 100644
--- a/regression-test/suites/search/test_search_score_boolean_branches.groovy
+++ b/regression-test/suites/search/test_search_score_boolean_branches.groovy
@@ -102,4 +102,124 @@ suite("test_search_score_boolean_branches", "p0") {
"""
exception "Cannot score a compound predicate with incomplete index
evaluation"
}
+
+ // Each INSERT writes its own segment, so some segments store only v.title
or only v.content.
+ // Keep every path materialized and indexed; the fuzzy defaults may store
paths in the sparse
+ // or doc-value column, where a segment cannot prove a path absent.
+ sql """ set debug_variant_enable_doc_mode = false """
+ sql """ set debug_variant_max_subcolumns_count = 0 """
+ sql "DROP TABLE IF EXISTS test_search_score_variant_absent_path"
+ sql """
+ CREATE TABLE test_search_score_variant_absent_path (
+ id INT NOT NULL,
+ v VARIANT NULL,
+ INDEX idx_v(v) USING INVERTED PROPERTIES("parser" = "english")
+ ) ENGINE=OLAP
+ DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default:1",
+ "disable_auto_compaction" = "true"
+ )
+ """
+ sql """
+ INSERT INTO test_search_score_variant_absent_path VALUES
+ (1, parse_to_variant('{"title":"apple search
guide","content":"search database engine"}')),
+ (2, parse_to_variant('{"title":"banana guide","content":"analytics
engine"}'))
+ """
+ sql """
+ INSERT INTO test_search_score_variant_absent_path VALUES
+ (3, parse_to_variant('{"title":"apple archive"}')),
+ (4, parse_to_variant('{"title":"database manual"}'))
+ """
+ sql """
+ INSERT INTO test_search_score_variant_absent_path VALUES
+ (5, parse_to_variant('{"content":"apple search"}')),
+ (6, parse_to_variant('{"content":"database analytics"}'))
+ """
+ sql """
+ INSERT INTO test_search_score_variant_absent_path VALUES
+ (7, parse_to_variant('{"category":"apple search metadata"}')),
+ (8, parse_to_variant('{}')),
+ (9, parse_to_variant('{"title":"apple database","content":"search
analytics"}'))
+ """
+
+ order_qt_variant_search """
+ SELECT id, ROUND(score(), 4) AS bm25_score
+ FROM test_search_score_variant_absent_path
+ WHERE search('v.title:apple OR v.content:search')
+ ORDER BY score() DESC LIMIT 100
+ """
+
+ order_qt_variant_match_or """
+ SELECT id, ROUND(score(), 4) AS bm25_score
+ FROM test_search_score_variant_absent_path
+ WHERE v['title'] MATCH_ANY 'apple' OR v['content'] MATCH_ANY 'search'
+ ORDER BY score() DESC LIMIT 100
+ """
+
+ // An absent v.content is NULL, so NOT keeps a row only when v.title
matches.
+ order_qt_variant_not_absent """
+ SELECT id, ROUND(score(), 4) AS bm25_score
+ FROM test_search_score_variant_absent_path
+ WHERE NOT (v['content'] MATCH_ANY 'search') OR v['title'] MATCH_ANY
'apple'
+ ORDER BY score() DESC LIMIT 100
+ """
+
+ sql "DROP TABLE IF EXISTS test_search_score_nullable_not_and"
+ sql """
+ CREATE TABLE test_search_score_nullable_not_and (
+ id INT NOT NULL,
+ title STRING NULL,
+ content STRING NULL,
+ INDEX idx_title(title) USING INVERTED PROPERTIES("parser" =
"english"),
+ INDEX idx_content(content) USING INVERTED PROPERTIES("parser" =
"english")
+ ) ENGINE=OLAP
+ DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_allocation" = "tag.location.default:1")
+ """
+ sql """
+ INSERT INTO test_search_score_nullable_not_and VALUES
+ (1, NULL, 'hit'), (2, NULL, 'miss'), (3, 'apple', 'miss')
+ """
+
+ // Keep NOT over AND. NULL AND FALSE is FALSE, so NOT keeps row 2 of the
nullable table and
+ // row 4 of the VARIANT table, which has no v.content and a v.title
without 'apple'.
+ sql """ set disable_nereids_expression_rules = 'SIMPLIFY_NOT_EXPR' """
+ order_qt_nullable_not_and """
+ SELECT id FROM test_search_score_nullable_not_and
+ WHERE NOT (title MATCH_ANY 'x' AND content MATCH_ANY 'hit')
+ """
+ order_qt_variant_not_and_absent """
+ SELECT id FROM test_search_score_variant_absent_path
+ WHERE NOT (v['content'] MATCH_ANY 'search' AND v['title'] MATCH_ANY
'apple')
+ """
+ sql """ set disable_nereids_expression_rules = '' """
+
+ // Without escaped keys, the segment stores row 1 under a.b.c, and
v['a.b'] reads
+ // {"c":"hit"} from there.
+ sql "DROP TABLE IF EXISTS test_search_score_variant_dotted_path"
+ sql """
+ CREATE TABLE test_search_score_variant_dotted_path (
+ id INT NOT NULL,
+ v VARIANT NULL,
+ INDEX idx_v(v) USING INVERTED PROPERTIES("parser" = "english")
+ ) ENGINE=OLAP
+ DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default:1",
+ "disable_auto_compaction" = "true",
+ "variant_escape_dots_in_keys" = "false"
+ )
+ """
+ sql """
+ INSERT INTO test_search_score_variant_dotted_path VALUES
+ (1, parse_to_variant('{"a":{"b":{"c":"hit"}}}')),
+ (2, parse_to_variant('{"a":{"x":"hit"}}'))
+ """
+ order_qt_variant_dotted_path """
+ SELECT id FROM test_search_score_variant_dotted_path WHERE v['a.b']
MATCH_ANY 'hit'
+ """
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]