This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new 1363ffa3b3e branch-4.2: [fix](inverted index) Fix score() with MATCH
on VARIANT paths missing from a segment #71022 (#71060)
1363ffa3b3e is described below
commit 1363ffa3b3e9c181613582b8d9f5f4e155d8c3d7
Author: Jack <[email protected]>
AuthorDate: Fri Nov 27 13:56:27 2026 +0800
branch-4.2: [fix](inverted index) Fix score() with MATCH on VARIANT paths
missing from a segment #71022 (#71060)
### Background
Pick of apache/doris#71022 to branch-4.2. `score()` needs every scored
predicate answered by the inverted index, and an AND/OR/NOT with a
scored branch fails when another branch has no index result (#69053, on
this branch via #69265). A VARIANT column stores a path only in segments
whose rows contain it, and SEARCH (#69347, on this branch via #69361)
already proves such absence from segment metadata; MATCH did not.
### What problem does this PR solve?
Issue Number: None
Related PR: #71022 (source, not merged yet when picked), #71063 (same
pick for branch-4.1), #69265 (#69053 on branch-4.2), #69361 (#69347 on
branch-4.2), #38908 (added the AND early exit fixed here)
PR Type: Bugfix
Problem Summary:
On branch-4.2, `score()` over MATCH predicates combined with AND/OR/NOT
on VARIANT paths fails with "Cannot score a compound predicate with
incomplete index evaluation" when some segment does not store one of the
paths, while `search()` works. Same fix as #71022: SEARCH's absence
proof becomes one shared `IndexExecContext::is_variant_path_absent`,
MATCH uses it to answer a provably absent path as no hits with every row
NULL, the proof also finds legacy dotted keys under the split path, and
an index-evaluated AND no longer stops while NULL rows can still turn
FALSE (which also fixes `NOT (a AND b)` on nullable indexed columns with
`SIMPLIFY_NOT_EXPR` disabled).
### Details
- **Source:** apache/doris#71022 head bd12065805b, commits 262a92cce17,
ec87bb18603, bd12065805b, squashed here. The source PR was still under
review; recheck this pick against its merged commit.
- **Adaptations for branch-4.2** (behavior unchanged):
- `IndexExecContext::is_variant_path_absent` uses branch-4.2's own proof
body moved from `vsearch.cpp`: the read schema maps a slot ordinal
through `column_id()`, and the VARIANT root is resolved by unique ID
with `has_column_unique_id` and `get_column_reader`; a root missing from
the segment counts as absent, as SEARCH did here.
- `VMatchPredicate` uses `get_inverted_index_iterator_by_column_id` and
`read_schema->column(read_schema->column_id(id))`.
- The BE tests build the branch's `Schema` and pass `column_ids` to
`IndexExecContext`.
- **Frequency, root cause, other paths:** as in #71022.
Hunk audit against #71022 (all `@@` hunks of the source; source line
numbers):
| File | Hunks | Status |
| --- | --- | --- |
| be/src/exprs/vcompound_pred.h | AND early exit | Ported (verbatim) |
| be/src/exprs/vexpr_context.h | forward decl; `is_variant_path_absent`
declaration | Ported (verbatim) |
| be/src/exprs/vexpr_context.cpp | includes; `is_variant_path_absent` |
Adapted: branch-4.2 root lookup and column-ID mapping; no
`storage/iterators.h` |
| be/src/exprs/vmatch_predicate.h | forward decl; helper declaration |
Ported (verbatim) |
| be/src/exprs/vmatch_predicate.cpp | includes; hook;
`_evaluate_absent_variant_path` | Adapted:
`get_inverted_index_iterator_by_column_id`, column-ID mapping |
| be/src/exprs/vsearch.cpp | includes; `verify_missing_variant_path` |
Adapted: removes branch-4.2's own proof body |
| be/src/storage/segment/variant/variant_column_reader.cpp | prefix
lookup changed in ec87bb18603, restored in bd12065805b | Net zero, as in
the source |
| be/test/exprs/vcompound_pred_score_test.cpp | mock;
`AndWithOnlyNullRowsLeftEvaluatesLaterBranches` | Adapted: branch
`IndexExecContext` constructor |
| be/test/storage/variant/variant_column_writer_reader_test.cpp |
includes; helper; three tests | Adapted: `Schema` and `column_ids` in
the helper; inserted after the SEARCH test |
|
regression-test/suites/search/test_search_score_boolean_branches.groovy
| new VARIANT and nullable cases | Ported (verbatim) |
| regression-test/data/search/test_search_score_boolean_branches.out |
new tags | Ported (verbatim); regenerated on branch-4.2 with
`-forceGenOut`, byte-identical |
### Testing
Local, ASAN, single BE, on this commit:
- BE UT `VariantColumnWriterReaderTest.*`, `VCompoundPredScoreTest.*`,
`VSearch*`, `*VMatchPredicate*`, `*FunctionSearch*`,
`*VariantColumnReader*`, `*HierarchicalData*`: 362 tests, 360 passed, 2
skipped (NestedGroup not built); the four new tests and #69347's SEARCH
test pass.
- Regression `search/test_search_score_boolean_branches`: passes;
`-forceGenOut` reproduces the picked .out byte for byte. The new queries
return the same rows with `enable_inverted_index_query=false` (2,3 /
2,4,6 / 1 / 1,3,5,9); `test_search_score_variant_dotted_path` was
created with storage format V2.
- `build-support/check-format.sh`: pass. This branch has no
`check-build-hygiene.sh`.
### Release note
Fixed the error "Cannot score a compound predicate with incomplete index
evaluation" when `score()` ranks rows filtered by MATCH predicates on
VARIANT paths combined with AND, OR, or NOT, and some data does not
contain one of the paths. Also fixed missing rows for `NOT (a AND b)` on
inverted-indexed columns when `a` is NULL and `b` is FALSE, with
`SIMPLIFY_NOT_EXPR` disabled.
### Check List (For Author)
- Behavior changed: Yes (see #71022: MATCH on a VARIANT path absent from
a segment is answered by the index; same rows)
- Does this need documentation: No
- Pre-submission status: Partially verified: not run in cloud mode; the
source PR is not merged yet
### AI Disclosure
- Tool: Claude Code (Claude Opus 5.5)
- Generated: the pick, its adaptations, and this description
- Human review: not stated
(cherry picked from commit 262a92cce174c0ecc2929298034ba0598c5cf205)
(cherry picked from commit ec87bb18603f866401dd2858829af87178471216)
(cherry picked from commit bd12065805b77bed93f0b6d3158f0d201e48a65d)
---
be/src/exprs/vcompound_pred.h | 7 +-
be/src/exprs/vexpr_context.cpp | 65 +++++++++
be/src/exprs/vexpr_context.h | 8 +
be/src/exprs/vmatch_predicate.cpp | 45 ++++++
be/src/exprs/vmatch_predicate.h | 4 +
be/src/exprs/vsearch.cpp | 55 +------
be/test/exprs/vcompound_pred_score_test.cpp | 68 +++++++++
.../variant/variant_column_writer_reader_test.cpp | 162 +++++++++++++++++++++
.../search/test_search_score_boolean_branches.out | 31 ++++
.../test_search_score_boolean_branches.groovy | 120 +++++++++++++++
10 files changed, 514 insertions(+), 51 deletions(-)
diff --git a/be/src/exprs/vcompound_pred.h b/be/src/exprs/vcompound_pred.h
index 6d783a2e468..fdcd881e78e 100644
--- a/be/src/exprs/vcompound_pred.h
+++ b/be/src/exprs/vcompound_pred.h
@@ -347,8 +347,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 b25d2daa112..a412d362542 100644
--- a/be/src/exprs/vexpr_context.cpp
+++ b/be/src/exprs/vexpr_context.cpp
@@ -40,7 +40,11 @@
#include "runtime/runtime_state.h"
#include "runtime/thread_context.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 {
@@ -50,6 +54,67 @@ class RowDescriptor;
namespace doris {
#include "common/compile_check_begin.h"
+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_column_ids());
+ DORIS_CHECK(_column_iter_opts.stats != nullptr);
+ const auto& column =
*_read_schema->column(_read_schema->column_id(read_ordinal));
+ const int32_t root_uid =
+ column.parent_unique_id() >= 0 ? column.parent_unique_id() :
column.unique_id();
+ // DROP/ADD can leave an old segment without the current root UID. Do not
open its
+ // historical same-named column or initialize readers for a root that is
absent.
+ if (!_segment->tablet_schema()->has_column_unique_id(root_uid)) {
+ *absent = true;
+ return Status::OK();
+ }
+ std::shared_ptr<segment_v2::ColumnReader> column_reader;
+ Status st = _segment->get_column_reader(root_uid, &column_reader,
_column_iter_opts.stats,
+ &_column_iter_opts.io_ctx);
+ 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);
+ auto* reader =
dynamic_cast<segment_v2::VariantColumnReader*>(column_reader.get());
+ 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 26db991a6aa..56c8be1658f 100644
--- a/be/src/exprs/vexpr_context.h
+++ b/be/src/exprs/vexpr_context.h
@@ -44,6 +44,7 @@
#include "storage/segment/column_reader.h"
namespace doris {
+class PathInData;
class RowDescriptor;
class RuntimeState;
class Schema;
@@ -125,6 +126,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 3bb2bffb475..027369ac7b1 100644
--- a/be/src/exprs/vmatch_predicate.cpp
+++ b/be/src/exprs/vmatch_predicate.cpp
@@ -47,7 +47,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;
@@ -178,6 +180,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) {
@@ -203,6 +209,45 @@ 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& read_schema = index_context.read_schema();
+ const auto& column =
*read_schema->column(read_schema->column_id(column_id));
+ if (index_context.get_inverted_index_iterator_by_column_id(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 4c513733105..b41c64d16cb 100644
--- a/be/src/exprs/vmatch_predicate.h
+++ b/be/src/exprs/vmatch_predicate.h
@@ -32,6 +32,7 @@ class Analyzer;
}
} // namespace lucene
namespace doris {
+class IndexExecContext;
class RowDescriptor;
class RuntimeState;
class TExprNode;
@@ -66,6 +67,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 901e63fdda1..6a605130014 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,57 +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_column_ids());
- const auto& column =
*read_schema->column(read_schema->column_id(column_index));
- const auto& opts = index_context->column_iter_opts();
- DORIS_CHECK(opts.stats != nullptr);
- const int32_t root_uid =
- column.parent_unique_id() >= 0 ? column.parent_unique_id() :
column.unique_id();
- // DROP/ADD can leave an old segment without the current root UID. Do not
open its
- // historical same-named column or initialize readers for a root that is
absent.
- if (!segment->tablet_schema()->has_column_unique_id(root_uid)) {
- return Status::OK();
- }
- std::shared_ptr<segment_v2::ColumnReader> column_reader;
- Status st = segment->get_column_reader(root_uid, &column_reader,
opts.stats, &opts.io_ctx);
- 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);
- auto* reader = dynamic_cast<VariantColumnReader*>(column_reader.get());
- 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 60c44b0dd16..3da4a62951e 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 {
@@ -228,5 +267,34 @@ 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;
+ const std::vector<ColumnId> column_ids;
+ auto index_context = std::make_shared<IndexExecContext>(
+ column_ids, iterators, storage_types, status_map, nullptr,
nullptr, iterator_options,
+ std::make_shared<Schema>(std::vector<TabletColumnPtr> {},
column_ids));
+ 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 f9788477d4f..12d6c047967 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"
@@ -9253,6 +9258,163 @@ 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<ColumnId> col_ids {0};
+ 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->col_ids, run->no_indexes, run->types, run->status_map,
nullptr, segment, opts,
+ std::make_shared<Schema>(std::vector<TabletColumnPtr> {leaf},
+ std::vector<ColumnId> {0}));
+ 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_streaming_compaction_writer_streams_regular_array_paths_across_batches) {
if (!nested_group_write_path_available()) {
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]