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 e42a0fb2708 [opt](inverted index) Skip regexp expansion terms that
lack the expression's literal (#70592)
e42a0fb2708 is described below
commit e42a0fb270821764b80bd974ad06a8be4cf917c3
Author: Jack <[email protected]>
AuthorDate: Sat Dec 5 11:09:06 2026 +0800
[opt](inverted index) Skip regexp expansion terms that lack the
expression's literal (#70592)
### Background
`MATCH_REGEXP` on a text index expands to the dictionary terms the
expression matches. An expression without a fixed prefix walks the whole
dictionary and runs the regular expression on every term.
### What problem does this PR solve?
Issue Number: None
Related PR: #70373 (the same prefilter for leading-wildcard globs),
#70593 (prunes SNII dictionary blocks on this literal)
PR Type: Performance
Problem Summary:
Unanchored `MATCH_REGEXP` ran the regular expression on every dictionary
term, although only terms holding its literal can match. This PR derives
the literal every match must contain and skips the other terms before
matching, cutting the expansion's CPU by 30-38% on V3 and 10-20% on
SNII.
### Details
- **Why it was slow:** every term went through the UTF conversion (V3)
and a Hyperscan scan.
- **Optimization:** the longest literal run of the expression's
top-level concatenation becomes the pattern's required text, only for an
expression without an enumeration prefix (CLucene tests the text before
the prefix, so `^cach.` would otherwise walk past its range).
- **Results:** 100M rows, caches off: V3 5.6-5.9 to 3.5-4.1 CPU-seconds,
SNII 3.7-4.0 to 3.0-3.5; anchored and literal-free expressions
unchanged; identical results.
- **Applicability and cost:** unanchored regular expressions with a
literal; one parse per pattern.
### Testing
BE UT `TermPatternRegexpLiteral*`; regression
`test_storage_format_snii_regexp_literal` (19 expressions, SNII against
V3, expected output generated without this change); clang-tidy and the
hygiene gate.
---
.../index/inverted/query/exec/term_pattern.cpp | 72 ++++++-
.../index/inverted/query/exec/term_pattern.h | 4 +-
.../exec/term_pattern_required_literal_test.cpp | 97 ++++++++++
.../test_storage_format_snii_regexp_literal.out | 215 +++++++++++++++++++++
.../test_storage_format_snii_regexp_literal.groovy | 93 +++++++++
5 files changed, 478 insertions(+), 3 deletions(-)
diff --git a/be/src/storage/index/inverted/query/exec/term_pattern.cpp
b/be/src/storage/index/inverted/query/exec/term_pattern.cpp
index 79ce086071f..d401044c658 100644
--- a/be/src/storage/index/inverted/query/exec/term_pattern.cpp
+++ b/be/src/storage/index/inverted/query/exec/term_pattern.cpp
@@ -23,6 +23,7 @@
#include "common/logging.h"
#include "runtime/runtime_state.h"
#include "storage/index/index_query_context.h"
+#include "storage/index/inverted/query/logical/gram/regex_ast.h"
#include "util/hyperscan_util.h"
namespace doris::index_query {
@@ -75,6 +76,66 @@ std::string_view longest_literal_run(std::string_view
pattern) {
return longest;
}
+// The longest literal every match of a regular expression holds: the
consecutive literal code
+// points of a concatenation, through anchors (which take no text) and into a
group repeated at
+// least once; a class, `.`, an alternation and a quantifier that may take
nothing end the run.
+// Under `(?i)` the parser turns letters into classes, so they name no literal.
+void collect_regexp_literal(const segment_v2::gram::RegexNode& node,
std::string* run,
+ std::string* longest) {
+ using Type = segment_v2::gram::RegexNode::Type;
+ const auto end_run = [&] {
+ if (run->size() > longest->size()) {
+ *longest = *run;
+ }
+ run->clear();
+ };
+ switch (node.type) {
+ case Type::EMPTY:
+ return;
+ case Type::LIT:
+ run->append(node.lit);
+ return;
+ case Type::CAT:
+ for (const auto& kid : node.kids) {
+ collect_regexp_literal(*kid, run, longest);
+ }
+ return;
+ case Type::PLUS:
+ case Type::REPEAT:
+ end_run();
+ if (node.type == Type::PLUS || node.rmin >= 1) {
+ std::string inner;
+ for (const auto& kid : node.kids) {
+ collect_regexp_literal(*kid, &inner, longest);
+ }
+ if (inner.size() > longest->size()) {
+ *longest = inner;
+ }
+ }
+ return;
+ case Type::CLASS:
+ case Type::ANY:
+ case Type::ALT:
+ case Type::STAR:
+ case Type::QUEST:
+ end_run();
+ return;
+ }
+}
+
+// Empty for a pattern the parser does not accept: the expansion then tests
every term.
+std::string regexp_required_literal(std::string_view pattern) {
+ std::unique_ptr<segment_v2::gram::RegexNode> root;
+ bool case_insensitive = false;
+ if (!segment_v2::gram::parse_regex(pattern, &root,
&case_insensitive).ok()) {
+ return {};
+ }
+ std::string run;
+ std::string longest;
+ collect_regexp_literal(*root, &run, &longest);
+ return run.size() > longest.size() ? run : longest;
+}
+
int on_match(unsigned int /*id*/, unsigned long long /*from*/, unsigned long
long /*to*/,
unsigned int /*flags*/, void* context) {
*static_cast<bool*>(context) = true;
@@ -138,7 +199,16 @@ Status TermPattern::create(TermPatternKind kind,
std::string_view pattern, TermP
return Status::MemoryAllocFailed("cannot allocate Hyperscan scratch");
}
out->_scratch.reset(scratch);
- out->_enumeration_prefix = regexp_enumeration_prefix(pattern);
+ // Hyperscan reads the expression as a C string, so a raw NUL ends it. The
prefix and the
+ // literal come from that same text, or they would skip terms the
expression matches.
+ const std::string_view compiled(terminated.c_str());
+ out->_enumeration_prefix = regexp_enumeration_prefix(compiled);
+ // As for a glob: an expression with a prefix already stops where the
prefix ends, and CLucene
+ // checks the prefix only after this text, so '^cach.' would walk on past
"cach" through every
+ // later term that lacks "cach". Only an expression that enumerates the
whole dictionary keeps it.
+ if (out->_enumeration_prefix.empty()) {
+ out->_text = regexp_required_literal(compiled);
+ }
return Status::OK();
}
diff --git a/be/src/storage/index/inverted/query/exec/term_pattern.h
b/be/src/storage/index/inverted/query/exec/term_pattern.h
index 0442292bfea..75ff07e5498 100644
--- a/be/src/storage/index/inverted/query/exec/term_pattern.h
+++ b/be/src/storage/index/inverted/query/exec/term_pattern.h
@@ -142,8 +142,8 @@ public:
const std::string& enumeration_prefix() const { return
_enumeration_prefix; }
// Text every matching term holds, or empty. A format skips the terms
without it before decoding
- // them: kSuffix and kContains take their text, and a glob that enumerates
the whole dictionary
- // takes its longest literal run ("cache" for "*cache*").
+ // them: kSuffix and kContains take their text, and a glob or regular
expression that enumerates
+ // the whole dictionary takes its longest literal ("cache" for "*cache*"
and for "cache.*").
const std::string& required_text() const { return _text; }
// False when no term can match, as for a regular expression Hyperscan
cannot compile.
diff --git
a/be/test/storage/index/inverted/query/exec/term_pattern_required_literal_test.cpp
b/be/test/storage/index/inverted/query/exec/term_pattern_required_literal_test.cpp
new file mode 100644
index 00000000000..e6b63fca379
--- /dev/null
+++
b/be/test/storage/index/inverted/query/exec/term_pattern_required_literal_test.cpp
@@ -0,0 +1,97 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <gtest/gtest.h>
+
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+#include "common/status.h"
+#include "storage/index/inverted/query/exec/term_pattern.h"
+
+namespace doris::index_query {
+namespace {
+
+std::string required_literal(std::string_view pattern) {
+ TermPattern term_pattern;
+ const Status status = TermPattern::create(TermPatternKind::kRegexp,
pattern, &term_pattern);
+ EXPECT_TRUE(status.ok()) << pattern << ": " << status.to_string();
+ return term_pattern.required_text();
+}
+
+} // namespace
+
+// The literal of a regular expression is the longest run of literal code
points every match
+// holds; anything optional, alternative, case-folded or a class ends the run.
An expression with
+// an enumeration prefix names none: the prefix already bounds its walk, and a
format that tests
+// the literal before the prefix would walk on past the prefix range.
+TEST(TermPatternRegexpLiteral, NamesTheLongestLiteralEveryMatchHolds) {
+ const std::vector<std::pair<std::string, std::string>> cases = {
+ {"cache", "cache"}, {"^cache$", ""}, {"^cach.", ""},
+ {"^.*cache", "cache"}, {"cach.", "cach"}, {"cache\\.go",
"cache.go"},
+ {"ab(cd)ef", "abcdef"}, {"abc(de)+f", "abc"}, {"x(abcd)+y",
"abcd"},
+ {"x{0,3}yz", "yz"}, {"(abc){2}", "abc"}, {"a*bcd", "bcd"},
+ {"cach?e", "cac"}, {"c[ab]che", "che"}, {"\\d+timeout",
"timeout"},
+ {"timeout\\b", "timeout"}, {"\\Qa*b\\E", "a*b"}, {"猫.狗", "猫"},
+ {"cache|error", ""}, {"(?i)cache", ""}, {"[a-z]+", ""},
+ };
+ for (const auto& [pattern, literal] : cases) {
+ EXPECT_EQ(required_literal(pattern), literal) << pattern;
+ }
+}
+
+// The literal only narrows the terms tested; the expression still decides
each match.
+TEST(TermPatternRegexpLiteral, LiteralOnlyNarrowsTheTerms) {
+ TermPattern term_pattern;
+ ASSERT_TRUE(TermPattern::create(TermPatternKind::kRegexp, "cach.",
&term_pattern).ok());
+ EXPECT_EQ(term_pattern.required_text(), "cach");
+ EXPECT_TRUE(term_pattern.matches("cache"));
+ EXPECT_TRUE(term_pattern.matches("mcached"));
+ EXPECT_FALSE(term_pattern.matches("cach"));
+ EXPECT_FALSE(term_pattern.matches("error"));
+}
+
+// A pattern the regular-expression engine rejects matches nothing and names
no literal.
+TEST(TermPatternRegexpLiteral, InvalidPatternNamesNoLiteral) {
+ TermPattern term_pattern;
+ ASSERT_TRUE(TermPattern::create(TermPatternKind::kRegexp, "cache(",
&term_pattern).ok());
+ EXPECT_FALSE(term_pattern.can_match());
+ EXPECT_EQ(term_pattern.required_text(), "");
+}
+
+// Hyperscan reads the expression as a C string, so a raw NUL ends it. The
literal and the prefix
+// must come from that same text, or they would skip terms the expression
matches.
+TEST(TermPatternRegexpLiteral, RawNulEndsTheExpression) {
+ TermPattern unanchored;
+ ASSERT_TRUE(TermPattern::create(TermPatternKind::kRegexp,
std::string("cache\0missing", 13),
+ &unanchored)
+ .ok());
+ EXPECT_TRUE(unanchored.matches("cache"));
+ EXPECT_EQ(unanchored.required_text(), "cache");
+
+ TermPattern anchored;
+ ASSERT_TRUE(TermPattern::create(TermPatternKind::kRegexp,
std::string("^cache\0missing", 14),
+ &anchored)
+ .ok());
+ EXPECT_TRUE(anchored.matches("cache"));
+
EXPECT_TRUE(std::string_view("cache").starts_with(anchored.enumeration_prefix()))
+ << anchored.enumeration_prefix();
+}
+
+} // namespace doris::index_query
diff --git
a/regression-test/data/inverted_index_p0/storage_format/test_storage_format_snii_regexp_literal.out
b/regression-test/data/inverted_index_p0/storage_format/test_storage_format_snii_regexp_literal.out
new file mode 100644
index 00000000000..f6da0ead0da
--- /dev/null
+++
b/regression-test/data/inverted_index_p0/storage_format/test_storage_format_snii_regexp_literal.out
@@ -0,0 +1,215 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !body_0 --
+cache SNII 30000
+cache SNII 30001
+cache SNII 30002
+cache SNII 30003
+cache SNII 30006
+cache SNII 30007
+cache V3 30000
+cache V3 30001
+cache V3 30002
+cache V3 30003
+cache V3 30006
+cache V3 30007
+
+-- !body_1 --
+cach. SNII 30000
+cach. SNII 30001
+cach. SNII 30002
+cach. SNII 30003
+cach. SNII 30006
+cach. SNII 30007
+cach. V3 30000
+cach. V3 30001
+cach. V3 30002
+cach. V3 30003
+cach. V3 30006
+cach. V3 30007
+
+-- !body_2 --
+^zcache$ SNII 30002
+^zcache$ V3 30002
+
+-- !body_3 --
+^cach. SNII 30003
+^cach. SNII 30007
+^cach. V3 30003
+^cach. V3 30007
+
+-- !body_4 --
+^.*cache SNII 30000
+^.*cache SNII 30001
+^.*cache SNII 30002
+^.*cache SNII 30003
+^.*cache SNII 30006
+^.*cache SNII 30007
+^.*cache V3 30000
+^.*cache V3 30001
+^.*cache V3 30002
+^.*cache V3 30003
+^.*cache V3 30006
+^.*cache V3 30007
+
+-- !body_5 --
+(?i)CACHE SNII 30000
+(?i)CACHE SNII 30001
+(?i)CACHE SNII 30002
+(?i)CACHE SNII 30003
+(?i)CACHE SNII 30006
+(?i)CACHE SNII 30007
+(?i)CACHE V3 30000
+(?i)CACHE V3 30001
+(?i)CACHE V3 30002
+(?i)CACHE V3 30003
+(?i)CACHE V3 30006
+(?i)CACHE V3 30007
+
+-- !body_6 --
+cache|zcache SNII 30000
+cache|zcache SNII 30001
+cache|zcache SNII 30002
+cache|zcache SNII 30003
+cache|zcache SNII 30006
+cache|zcache SNII 30007
+cache|zcache V3 30000
+cache|zcache V3 30001
+cache|zcache V3 30002
+cache|zcache V3 30003
+cache|zcache V3 30006
+cache|zcache V3 30007
+
+-- !body_7 --
+m.*ed SNII 30001
+m.*ed V3 30001
+
+-- !body_8 --
+c[ab]che SNII 30000
+c[ab]che SNII 30001
+c[ab]che SNII 30002
+c[ab]che SNII 30003
+c[ab]che SNII 30004
+c[ab]che SNII 30006
+c[ab]che SNII 30007
+c[ab]che V3 30000
+c[ab]che V3 30001
+c[ab]che V3 30002
+c[ab]che V3 30003
+c[ab]che V3 30004
+c[ab]che V3 30006
+c[ab]che V3 30007
+
+-- !body_9 --
+cach?e SNII 30000
+cach?e SNII 30001
+cach?e SNII 30002
+cach?e SNII 30003
+cach?e SNII 30006
+cach?e SNII 30007
+cach?e V3 30000
+cach?e V3 30001
+cach?e V3 30002
+cach?e V3 30003
+cach?e V3 30006
+cach?e V3 30007
+
+-- !body_10 --
+(che)+ SNII 30000
+(che)+ SNII 30001
+(che)+ SNII 30002
+(che)+ SNII 30003
+(che)+ SNII 30004
+(che)+ SNII 30005
+(che)+ SNII 30006
+(che)+ SNII 30007
+(che)+ V3 30000
+(che)+ V3 30001
+(che)+ V3 30002
+(che)+ V3 30003
+(che)+ V3 30004
+(che)+ V3 30005
+(che)+ V3 30006
+(che)+ V3 30007
+
+-- !body_11 --
+x{0,3}ache SNII 30000
+x{0,3}ache SNII 30001
+x{0,3}ache SNII 30002
+x{0,3}ache SNII 30003
+x{0,3}ache SNII 30006
+x{0,3}ache SNII 30007
+x{0,3}ache V3 30000
+x{0,3}ache V3 30001
+x{0,3}ache V3 30002
+x{0,3}ache V3 30003
+x{0,3}ache V3 30006
+x{0,3}ache V3 30007
+
+-- !body_12 --
+[0-9]+cache SNII 30006
+[0-9]+cache V3 30006
+
+-- !body_13 --
+ca(ch)+e SNII 30000
+ca(ch)+e SNII 30001
+ca(ch)+e SNII 30002
+ca(ch)+e SNII 30003
+ca(ch)+e SNII 30006
+ca(ch)+e SNII 30007
+ca(ch)+e V3 30000
+ca(ch)+e V3 30001
+ca(ch)+e V3 30002
+ca(ch)+e V3 30003
+ca(ch)+e V3 30006
+ca(ch)+e V3 30007
+
+-- !body_14 --
+cach(e|ing) SNII 30000
+cach(e|ing) SNII 30001
+cach(e|ing) SNII 30002
+cach(e|ing) SNII 30003
+cach(e|ing) SNII 30006
+cach(e|ing) SNII 30007
+cach(e|ing) V3 30000
+cach(e|ing) V3 30001
+cach(e|ing) V3 30002
+cach(e|ing) V3 30003
+cach(e|ing) V3 30006
+cach(e|ing) V3 30007
+
+-- !tag_cach_ --
+cach. SNII 30000
+cach. SNII 30001
+cach. SNII 30002
+cach. SNII 30003
+cach. SNII 30007
+cach. V3 30000
+cach. V3 30001
+cach. V3 30002
+cach. V3 30003
+cach. V3 30007
+
+-- !tag__cach_ --
+^cach. SNII 30003
+^cach. SNII 30007
+^cach. V3 30003
+^cach. V3 30007
+
+-- !tag_che_ --
+che$ SNII 30000
+che$ SNII 30002
+che$ SNII 30003
+che$ SNII 30004
+che$ SNII 30005
+che$ SNII 30006
+che$ V3 30000
+che$ V3 30002
+che$ V3 30003
+che$ V3 30004
+che$ V3 30005
+che$ V3 30006
+
+-- !tag___i_CBCHE --
+(?i)CBCHE SNII 30004
+(?i)CBCHE V3 30004
+
diff --git
a/regression-test/suites/inverted_index_p0/storage_format/test_storage_format_snii_regexp_literal.groovy
b/regression-test/suites/inverted_index_p0/storage_format/test_storage_format_snii_regexp_literal.groovy
new file mode 100644
index 00000000000..03bbaa902aa
--- /dev/null
+++
b/regression-test/suites/inverted_index_p0/storage_format/test_storage_format_snii_regexp_literal.groovy
@@ -0,0 +1,93 @@
+// 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.
+
+// A regular expression without an enumeration prefix names the literal every
match holds, and
+// an expansion skips the terms without it before running the expression.
Every expression here
+// must return the same rows on SNII and V3 over dictionaries of several
blocks, whether it names
+// a literal (inside a concatenation, through anchors, inside a repeated
group), names none (an
+// alternation, a case-folded or optional part, a class) or is anchored on a
prefix.
+suite("test_storage_format_snii_regexp_literal", "p0") {
+ sql "DROP TABLE IF EXISTS test_snii_regexp_literal"
+ sql "DROP TABLE IF EXISTS test_v3_regexp_literal"
+ for (format in ["SNII", "V3"]) {
+ def table = format == "SNII" ? "test_snii_regexp_literal" :
"test_v3_regexp_literal"
+ sql """
+ CREATE TABLE ${table} (
+ id INT,
+ body VARCHAR(200),
+ tag VARCHAR(50),
+ INDEX idx_body (`body`) USING INVERTED PROPERTIES("parser" =
"english"),
+ INDEX idx_tag (`tag`) USING INVERTED
+ ) ENGINE=OLAP
+ DUPLICATE KEY(`id`)
+ DISTRIBUTED BY RANDOM BUCKETS 1
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1",
+ "inverted_index_storage_format" = "${format}"
+ )
+ """
+ // 30000 rows of distinct tokens fill several dictionary blocks around
the rows below.
+ sql """
+ INSERT INTO ${table}
+ SELECT number, concat('item', lpad(cast(number as string), 6,
'0'), ' k', number * 7),
+ concat('tag', lpad(cast(number as string), 6, '0'))
+ FROM numbers("number" = "30000")
+ """
+ sql """
+ INSERT INTO ${table} VALUES
+ (30000, 'acache miss on the first read', 'acache'),
+ (30001, 'the entry was mcached twice', 'mcached'),
+ (30002, 'zcache hit', 'zcache'),
+ (30003, 'cache', 'cache'),
+ (30004, 'cbche and caabche', 'cbche'),
+ (30005, 'chechecheche', 'chechecheche'),
+ (30006, 'xxxache 7cache', 'xxxache'),
+ (30007, 'cacheable caching', 'cacheable'),
+ (30008, NULL, NULL)
+ """
+ sql "sync"
+ }
+
+ def expressions = [
+ "cache", "cach.", "^zcache\$", "^cach.", "^.*cache", "(?i)CACHE",
"cache|zcache", "m.*ed",
+ "c[ab]che", "cach?e", "(che)+", "x{0,3}ache", "[0-9]+cache",
"ca(ch)+e", "cach(e|ing)",
+ ]
+ for (int i = 0; i < expressions.size(); i++) {
+ def expression = expressions[i]
+ "order_qt_body_${i}"("""
+ SELECT '${expression}' AS expression, format, id
+ FROM (
+ SELECT 'SNII' AS format, id FROM test_snii_regexp_literal WHERE
body MATCH_REGEXP '${expression}'
+ UNION ALL
+ SELECT 'V3' AS format, id FROM test_v3_regexp_literal WHERE body
MATCH_REGEXP '${expression}'
+ ) results
+ ORDER BY format, id
+ """)
+ }
+ for (expression in ["cach.", "^cach.", "che\$", "(?i)CBCHE"]) {
+ def tag = expression.replaceAll("[^a-zA-Z]", "_")
+ "order_qt_tag_${tag}"("""
+ SELECT '${expression}' AS expression, format, id
+ FROM (
+ SELECT 'SNII' AS format, id FROM test_snii_regexp_literal WHERE
tag MATCH_REGEXP '${expression}'
+ UNION ALL
+ SELECT 'V3' AS format, id FROM test_v3_regexp_literal WHERE tag
MATCH_REGEXP '${expression}'
+ ) results
+ ORDER BY format, id
+ """)
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]