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 5bca60c84ab [opt](nereids) Fetch columns read only by search() or 
MATCH after the TopN (#70388)
5bca60c84ab is described below

commit 5bca60c84abcd92b5c98938f312748afab09e0c8
Author: Jack <[email protected]>
AuthorDate: Thu Dec 3 10:07:17 2026 +0800

    [opt](nereids) Fetch columns read only by search() or MATCH after the TopN 
(#70388)
    
    ### Background
    
    TopN lazy materialization reads only the sort keys and a row location in
    the scan, and fetches the other returned columns for the rows that
    survive the TopN. A column a filter above the scan reads stayed in the
    scan output, unless the experimental
    `topn_lazy_materialization_using_index` deferred every filter column.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #59572
    PR Type: Performance
    
    Problem Summary:
    
    A TopN that filters a column with search() or MATCH and returns it read
    that column for every match. Such a column is now fetched after the
    TopN, so the scan answers the predicate from the inverted index without
    reading it: a search-box query over 100M logs uses 59% less CPU and 38%
    less time.
    
    ### Details
    
    - **Why it was slow:** Body was read for 5.49M matches and carried
    through the sort to return 200 rows.
    - **Optimization:** a filter directly above a base-index OLAP scan keeps
    lazy the columns only search() and MATCH (alone or under AND/OR/NOT)
    read; the probe, the pruning and the consumed-slot check share that
    rule. A column that another operator below the TopN also reads, such as
    a join key, stays in the scan output.
    - **Results:** branch-4.2 port, old and new planning alternating on one
    cluster: search-box TopN queries 37-59% less CPU, TextBench and
    AgentLogs MATCH TopN queries 23-56% less; other queries within 4%;
    results identical.
    - **Applicability and cost:** surviving rows fetch the column by row
    location; a segment without the index reads it in the scan as before. No
    change to writing or storage.
    
    ### Testing
    
    FE unit tests in `TopnLazyMaterializeTest` (fails before the change;
    also covers a join below the TopN that reads the MATCH column) and
    `MaterializeProbeVisitorTest`; regression test
    `test_topn_lazy_index_predicate_slots`, with a debug point proving the
    scan does not read the column, and a segment without the index, where
    MATCH runs row by row and returns the same rows as without lazy
    materialization.
---
 .../post/materialize/LazyMaterializeTopN.java      |  44 ++++--
 .../post/materialize/LazySlotPruning.java          |   6 +-
 .../post/materialize/MaterializeProbeVisitor.java  |  79 +++++++---
 .../postprocess/TopnLazyMaterializeTest.java       |  82 ++++++++++
 .../materialize/MaterializeProbeVisitorTest.java   |  63 ++++++++
 .../test_topn_lazy_index_predicate_slots.out       |  97 ++++++++++++
 .../test_topn_lazy_index_predicate_slots.groovy    | 170 +++++++++++++++++++++
 7 files changed, 502 insertions(+), 39 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
index d791c4554a7..feba89103fd 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazyMaterializeTopN.java
@@ -328,10 +328,21 @@ public class LazyMaterializeTopN extends 
PlanPostProcessor {
      *
      * <p>Therefore every slot consumed by this TopN and by the operators 
below it (its own order keys, the
      * expressions of every descendant operator and the slots that are 
required materialized already) is
-     * resolved through its identity alias chain. The only consumed slots that 
are not required are the ones
-     * {@link MaterializeProbeVisitor#isIndexLazyFilter} keeps lazy: {@link 
LazySlotPruning#visitPhysicalFilter}
-     * drops those from the scan's lazy slots for the same reason, so the scan 
keeps producing them for the
-     * predicate and nothing below the TopN can be starved. Project 
expressions are handled by
+     * resolved through its identity alias chain. The one read that does not 
count is a filter reading its own
+     * {@link MaterializeProbeVisitor#indexLazySlots}: {@link 
LazySlotPruning#visitPhysicalFilter} keeps those
+     * slots in the scan for the predicate. Another operator that reads such a 
slot still needs it, as the join
+     * does in
+     *
+     * <pre>
+     *   TopN(order by k)
+     *     HashJoin(body = s)
+     *       Project(body, body AS y, k)
+     *         TopN(order by k)
+     *           Filter(body MATCH_ANY 'error')
+     *             OlapScan
+     * </pre>
+     *
+     * where probing the outer output {@code y} resolves to {@code body}. 
Project expressions are handled by
      * {@link #collectProjectExprInputSlots}, which knows that a transparent 
{@code Alias(Slot)} output may
      * still be fetched lazily.
      *
@@ -346,33 +357,34 @@ public class LazyMaterializeTopN extends 
PlanPostProcessor {
         collectIdentityAliasMap(topN.child(), aliasToChild);
 
         Set<Slot> consumedSlots = new HashSet<>();
-        Set<Slot> indexLazySlots = new HashSet<>();
-        collectConsumedSlots(topN, consumedSlots, indexLazySlots);
+        collectConsumedSlots(topN, consumedSlots);
         consumedSlots.addAll(requiredMaterializedSlots);
         for (Slot slot : consumedSlots) {
-            if (!indexLazySlots.contains(slot)) {
-                collectAliasChain(slot, aliasToChild, 
requiredMaterializedSlots);
-            }
+            collectAliasChain(slot, aliasToChild, requiredMaterializedSlots);
         }
     }
 
     /** Collect the slots consumed by {@code plan} itself and by every 
operator below it. */
-    private void collectConsumedSlots(Plan plan, Set<Slot> consumedSlots, 
Set<Slot> indexLazySlots) {
+    private void collectConsumedSlots(Plan plan, Set<Slot> consumedSlots) {
         if (plan instanceof PhysicalSetOperation) {
             // Set operations are not materialized lazily, so nothing below 
them can be lazy either.
             return;
         }
-        if (!(plan instanceof PhysicalProject)) {
+        if (plan instanceof PhysicalFilter) {
+            // The scan keeps producing the index lazy slots for the filter, 
so only the filter's other slots count.
+            Set<Slot> indexLazySlots = 
MaterializeProbeVisitor.indexLazySlots((PhysicalFilter<?>) plan);
+            for (Slot slot : plan.getInputSlots()) {
+                if (!indexLazySlots.contains(slot)) {
+                    consumedSlots.add(slot);
+                }
+            }
+        } else if (!(plan instanceof PhysicalProject)) {
             // Project expressions are covered by 
collectProjectExprInputSlots, which keeps the input of a
             // transparent Alias(Slot) lazy because that alias output may 
still be fetched later.
             consumedSlots.addAll(plan.getInputSlots());
         }
-        if (plan instanceof PhysicalFilter
-                && 
MaterializeProbeVisitor.isIndexLazyFilter((PhysicalFilter<?>) plan)) {
-            indexLazySlots.addAll(plan.getInputSlots());
-        }
         for (Plan child : plan.children()) {
-            collectConsumedSlots(child, consumedSlots, indexLazySlots);
+            collectConsumedSlots(child, consumedSlots);
         }
     }
 
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazySlotPruning.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazySlotPruning.java
index ffd4e5e3260..9670649b087 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazySlotPruning.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/LazySlotPruning.java
@@ -50,6 +50,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.Set;
 import java.util.stream.Collectors;
 
 /**
@@ -118,7 +119,8 @@ public class LazySlotPruning extends 
DefaultPlanRewriter<LazySlotPruning.Context
 
     @Override
     public Plan visitPhysicalFilter(PhysicalFilter<? extends Plan> filter, 
Context context) {
-        if (MaterializeProbeVisitor.isIndexLazyFilter(filter)) {
+        Set<Slot> indexLazySlots = 
MaterializeProbeVisitor.indexLazySlots(filter);
+        if (!indexLazySlots.isEmpty()) {
             /*
              materialization(materializedSlots=[a, b], lazy=[c])
              ->topn(b)
@@ -138,7 +140,7 @@ public class LazySlotPruning extends 
DefaultPlanRewriter<LazySlotPruning.Context
             boolean lazySlotsChanged = false;
 
             for (Slot slot : context.lazySlots) {
-                if (!filter.getInputSlots().contains(slot)) {
+                if (!indexLazySlots.contains(slot)) {
                     lazySlotsToScan.add(slot);
                 } else {
                     lazySlotsChanged = true;
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitor.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitor.java
index b3687db6606..90e594cc957 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitor.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitor.java
@@ -23,7 +23,12 @@ import 
org.apache.doris.connector.spi.search.ConnectorSearchLazyMaterialization;
 import org.apache.doris.datasource.plugin.PluginDrivenExternalTable;
 import 
org.apache.doris.nereids.processor.post.materialize.MaterializeProbeVisitor.ProbeContext;
 import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.CompoundPredicate;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Match;
 import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.SearchExpression;
 import org.apache.doris.nereids.trees.expressions.Slot;
 import org.apache.doris.nereids.trees.expressions.SlotReference;
 import 
org.apache.doris.nereids.trees.expressions.functions.table.ExternalSearch;
@@ -80,37 +85,69 @@ public class MaterializeProbeVisitor extends 
DefaultPlanVisitor<Optional<Materia
     }
 
     /**
-     * Whether {@code filter} keeps its predicate slots lazy.
+     * The predicate slots of {@code filter} that stay lazy above the TopN.
      *
-     * <p>With {@code topn_lazy_materialization_using_index} the predicate of 
a filter directly above an OLAP
-     * scan is evaluated while scanning, so its slots only have to be 
re-materialized above the TopN instead
-     * of being carried through it. This is the single definition of that 
shape:
-     * {@link MaterializeProbeVisitor#visitPhysicalFilter} reports those slots 
as lazy sources,
-     * {@link LazySlotPruning#visitPhysicalFilter} keeps them out of the 
scan's lazy slots (the scan still
-     * produces them for the predicate) and {@link LazyMaterializeTopN} must 
not require them materialized.
+     * <p>The scan evaluates the predicate of a filter directly above it, so a 
predicate slot only has to be
+     * produced by the scan for the predicate and can be fetched again above 
the TopN instead of being
+     * carried through it. By default that is done for the slots read only by 
conjuncts made of search() and
+     * MATCH: the inverted index answers those, so where the segments have the 
index the scan does not read the
+     * column, and only the rows that survive the TopN fetch it. With
+     * {@code topn_lazy_materialization_using_index} it is done for every 
predicate slot. For
+     *
+     * <pre>
+     *   filter(search('body:error') AND ts > '2026-01-01') -> scan(ts, body)
+     * </pre>
+     *
+     * body stays lazy by default, ts only with the session variable.
+     *
+     * <p>This is the single definition of these slots: {@link 
MaterializeProbeVisitor#visitPhysicalFilter}
+     * reports them as lazy sources, {@link 
LazySlotPruning#visitPhysicalFilter} keeps them out of the scan's
+     * lazy slots (the scan still produces them for the predicate) and {@link 
LazyMaterializeTopN} does not count
+     * the filter's read of them when it decides which slots stay materialized.
      */
-    static boolean isIndexLazyFilter(PhysicalFilter<? extends Plan> filter) {
+    static Set<Slot> indexLazySlots(PhysicalFilter<? extends Plan> filter) {
         if (!(filter.child() instanceof PhysicalOlapScan)) {
-            return false;
+            return ImmutableSet.of();
         }
-        if (!SessionVariable.getTopNLazyMaterializationUsingIndex()) {
-            return false;
+        PhysicalOlapScan scan = (PhysicalOlapScan) filter.child();
+        // As in visitPhysicalOlapScan: the row-id locates a row of the base 
index, and the table's storage
+        // semantics must let one row-id reconstruct the row.
+        if (scan.getSelectedIndexId() != scan.getTable().getBaseIndexId()
+                || !supportOlapTopnLazyMaterialize(scan.getTable())) {
+            return ImmutableSet.of();
         }
-        // Reject OLAP tables whose storage semantics cannot be reconstructed 
from one row-id.
-        return supportOlapTopnLazyMaterialize(((PhysicalOlapScan) 
filter.child()).getTable());
+        if (SessionVariable.getTopNLazyMaterializationUsingIndex()) {
+            return filter.getInputSlots();
+        }
+        Set<Slot> indexOnlySlots = new HashSet<>();
+        Set<Slot> otherSlots = new HashSet<>();
+        for (Expression conjunct : filter.getConjuncts()) {
+            if (isIndexPredicate(conjunct)) {
+                indexOnlySlots.addAll(conjunct.getInputSlots());
+            } else {
+                otherSlots.addAll(conjunct.getInputSlots());
+            }
+        }
+        indexOnlySlots.removeAll(otherSlots);
+        return indexOnlySlots;
+    }
+
+    // search() and MATCH, alone or combined by AND, OR and NOT: (body 
MATCH_ALL 'a b' OR body MATCH_ANY 'c').
+    private static boolean isIndexPredicate(Expression expression) {
+        if (expression instanceof SearchExpression || expression instanceof 
Match) {
+            return true;
+        }
+        return (expression instanceof CompoundPredicate || expression 
instanceof Not)
+                && 
expression.children().stream().allMatch(MaterializeProbeVisitor::isIndexPredicate);
     }
 
     @Override
     public Optional<MaterializeSource> visitPhysicalFilter(PhysicalFilter<? 
extends Plan> filter,
                                                            ProbeContext 
context) {
-        if (isIndexLazyFilter(filter)) {
-            if (filter.getInputSlots().contains(context.slot)) {
-                Relation relation = (Relation) filter.child();
-                return Optional.of(new MaterializeSource(
-                        relation, findRelationOutputSlot(relation, 
context.slot).orElse(context.slot)));
-            } else {
-                return filter.child().accept(this, context);
-            }
+        if (indexLazySlots(filter).contains(context.slot)) {
+            Relation relation = (Relation) filter.child();
+            return Optional.of(new MaterializeSource(
+                    relation, findRelationOutputSlot(relation, 
context.slot).orElse(context.slot)));
         }
         return this.visit(filter, context);
     }
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
index 96f987e0be0..fe98e514c63 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/postprocess/TopnLazyMaterializeTest.java
@@ -287,6 +287,88 @@ public class TopnLazyMaterializeTest extends SSBTestBase {
         }
     }
 
+    @Test
+    public void testSlotsOnlyIndexPredicatesReadStayLazyByDefault() throws 
Exception {
+        this.createTable("create table lazy_materialize_search_tbl("
+                + "k int, body string, other int, "
+                + "index idx_body(body) using inverted properties('parser' = 
'english')) "
+                + "duplicate key(k) distributed by hash(k) buckets 1 "
+                + "properties('replication_num' = '1')");
+        boolean feDebug = connectContext.getSessionVariable().feDebug;
+        connectContext.getSessionVariable().feDebug = false;
+        try {
+            // Only search() or MATCH reads body, and the inverted index 
answers those: the scan keeps body for
+            // the predicate without reading it, and only the rows that 
survive the TopN fetch it.
+            for (String predicate : ImmutableList.of("search('body:error')", 
"body match_any 'error'",
+                    "(body match_all 'disk node' or body match_any 'error')")) 
{
+                PhysicalPlan plan = postProcess("select k, body, other from 
lazy_materialize_search_tbl where "
+                        + predicate + " order by k limit 10");
+                Assertions.assertEquals(ImmutableList.of(1, 2), 
lazyColumnIndexes(plan), plan.treeString());
+            }
+            PhysicalPlan plan = postProcess("select k, body as b, other from 
lazy_materialize_search_tbl "
+                    + "where search('body:error') order by k limit 10");
+            Assertions.assertEquals(ImmutableList.of(1, 2), 
lazyColumnIndexes(plan), plan.treeString());
+
+            // Another conjunct reads body row by row, so the scan reads it 
anyway and keeps it materialized.
+            plan = postProcess("select k, body, other from 
lazy_materialize_search_tbl "
+                    + "where search('body:error') and body like '%x%' order by 
k limit 10");
+            Assertions.assertEquals(ImmutableList.of(2), 
lazyColumnIndexes(plan), plan.treeString());
+
+            // The TopN sorts by an alias of body, so body is materialized for 
the sort.
+            plan = postProcess("select body as x, body as y from 
lazy_materialize_search_tbl "
+                    + "where search('body:error') order by x limit 1");
+            Assertions.assertEquals(ImmutableList.of(), 
lazyColumnIndexes(plan), plan.treeString());
+        } finally {
+            connectContext.getSessionVariable().feDebug = feDebug;
+        }
+    }
+
+    @Test
+    public void testIndexPredicateSlotReadByAnotherOperatorStaysMaterialized() 
throws Exception {
+        this.createTable("create table lazy_materialize_search_join_tbl("
+                + "k int, body string, other int, "
+                + "index idx_body(body) using inverted properties('parser' = 
'english')) "
+                + "duplicate key(k) distributed by hash(k) buckets 1 "
+                + "properties('replication_num' = '1')");
+        this.createTable("create table lazy_materialize_search_join_dim_tbl(id 
int, s string) "
+                + "duplicate key(id) distributed by hash(id) buckets 1 "
+                + "properties('replication_num' = '1')");
+        boolean feDebug = connectContext.getSessionVariable().feDebug;
+        connectContext.getSessionVariable().feDebug = false;
+        try {
+            // MATCH reads body, and the join below the outer TopN reads it 
too. The outer TopN returns only the
+            // alias y of body, so body must stay materialized for the join.
+            String inner = "(select k, body, other from 
lazy_materialize_search_join_tbl "
+                    + "where body match_any 'error' order by k limit 10) a";
+            PhysicalPlan plan = postProcess("select b.y from (select body, 
body as y, k from " + inner + ") b "
+                    + "join lazy_materialize_search_join_dim_tbl d on b.body = 
d.s order by b.k limit 1");
+            Assertions.assertEquals(ImmutableList.of(), 
lazyColumnIndexes(plan), plan.treeString());
+
+            // other is still fetched lazily.
+            plan = postProcess("select b.y, b.other from (select body, body as 
y, k, other from " + inner + ") b "
+                    + "join lazy_materialize_search_join_dim_tbl d on b.body = 
d.s order by b.k limit 1");
+            Assertions.assertEquals(ImmutableList.of(2), 
lazyColumnIndexes(plan), plan.treeString());
+
+            // When only MATCH reads body, its alias is still fetched lazily 
through the nested TopNs.
+            plan = postProcess("select y, other from (select body as y, k, 
other from " + inner
+                    + " order by other limit 2) b order by k limit 1");
+            Assertions.assertEquals(ImmutableList.of(1), 
lazyColumnIndexes(plan), plan.treeString());
+        } finally {
+            connectContext.getSessionVariable().feDebug = feDebug;
+        }
+    }
+
+    // The base column indexes the plan fetches lazily, sorted.
+    private static List<Integer> lazyColumnIndexes(PhysicalPlan plan) {
+        List<PhysicalLazyMaterialize<? extends Plan>> materializeNodes = 
plan.collectToList(
+                node -> node instanceof PhysicalLazyMaterialize);
+        Assertions.assertTrue(materializeNodes.size() <= 1, plan.treeString());
+        List<Integer> lazyColumnIndexes = Lists.newArrayList();
+        materializeNodes.forEach(node -> 
node.getLazyBaseColumnIndices().forEach(lazyColumnIndexes::addAll));
+        lazyColumnIndexes.sort(Integer::compareTo);
+        return lazyColumnIndexes;
+    }
+
     private PhysicalPlan postProcess(String sql) {
         PlanChecker checker = PlanChecker.from(connectContext)
                 .analyze(sql)
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitorTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitorTest.java
index 2c0c21e7927..d3ca9734e58 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitorTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/processor/post/materialize/MaterializeProbeVisitorTest.java
@@ -26,10 +26,17 @@ import 
org.apache.doris.connector.spi.search.ConnectorSearchLazyMaterialization;
 import org.apache.doris.datasource.plugin.PluginDrivenExternalTable;
 import org.apache.doris.nereids.trees.expressions.Add;
 import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.Like;
+import org.apache.doris.nereids.trees.expressions.MatchAll;
+import org.apache.doris.nereids.trees.expressions.MatchAny;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.Or;
 import org.apache.doris.nereids.trees.expressions.Slot;
 import org.apache.doris.nereids.trees.expressions.SlotReference;
 import org.apache.doris.nereids.trees.expressions.functions.table.VectorSearch;
 import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
 import org.apache.doris.nereids.trees.plans.Plan;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalCatalogRelation;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalFilter;
@@ -37,6 +44,7 @@ import 
org.apache.doris.nereids.trees.plans.physical.PhysicalOlapScan;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalProject;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalTVFRelation;
 import org.apache.doris.nereids.types.IntegerType;
+import org.apache.doris.nereids.types.StringType;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.tablefunction.VectorSearchTableValuedFunction;
 
@@ -177,6 +185,61 @@ public class MaterializeProbeVisitorTest {
         Assertions.assertEquals(ImmutableSet.of(baseSlot, pushedDownSlot), 
requiredMaterializedSlots);
     }
 
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testIndexLazySlotsAreTheSlotsOnlyIndexPredicatesRead() {
+        SlotReference body = new SlotReference("body", StringType.INSTANCE);
+        SlotReference ts = new SlotReference("ts", IntegerType.INSTANCE);
+        PhysicalOlapScan scan = mockBaseOlapScan(body);
+        PhysicalFilter<PhysicalOlapScan> filter = 
Mockito.mock(PhysicalFilter.class);
+        Mockito.when(filter.child()).thenReturn(scan);
+        Mockito.when(filter.getConjuncts()).thenReturn(ImmutableSet.of(
+                new MatchAny(body, new StringLiteral("error")), new 
GreaterThan(ts, new IntegerLiteral(1))));
+        Assertions.assertEquals(ImmutableSet.of(body), 
MaterializeProbeVisitor.indexLazySlots(filter));
+
+        // MATCH combined by OR and NOT is answered by the index as well.
+        Mockito.when(filter.getConjuncts()).thenReturn(ImmutableSet.of(new Or(
+                new MatchAll(body, new StringLiteral("disk node")),
+                new Not(new MatchAny(body, new StringLiteral("error"))))));
+        Assertions.assertEquals(ImmutableSet.of(body), 
MaterializeProbeVisitor.indexLazySlots(filter));
+
+        // A conjunct evaluated row by row reads body as well, also inside an 
OR.
+        Mockito.when(filter.getConjuncts()).thenReturn(ImmutableSet.of(
+                new MatchAny(body, new StringLiteral("error")), new Like(body, 
new StringLiteral("%x%"))));
+        Assertions.assertEquals(ImmutableSet.of(), 
MaterializeProbeVisitor.indexLazySlots(filter));
+        Mockito.when(filter.getConjuncts()).thenReturn(ImmutableSet.of(new Or(
+                new MatchAny(body, new StringLiteral("error")), new 
GreaterThan(ts, new IntegerLiteral(1)))));
+        Assertions.assertEquals(ImmutableSet.of(), 
MaterializeProbeVisitor.indexLazySlots(filter));
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testFilterOverRollupKeepsPredicateSlotsMaterialized() {
+        ConnectContext oldContext = ConnectContext.get();
+        ConnectContext context = new ConnectContext();
+        context.getSessionVariable().topNLazyMaterializationUsingIndex = true;
+        context.setThreadLocalInfo();
+        try {
+            SlotReference slot = new SlotReference("a", IntegerType.INSTANCE);
+            PhysicalOlapScan scan = mockBaseOlapScan(slot);
+            // A rollup is selected: its rows are not the base index rows the 
row-id points to.
+            Mockito.when(scan.getSelectedIndexId()).thenReturn(2L);
+            PhysicalFilter<PhysicalOlapScan> filter = 
Mockito.mock(PhysicalFilter.class);
+            Mockito.when(filter.child()).thenReturn(scan);
+            
Mockito.when(filter.getInputSlots()).thenReturn(ImmutableSet.of(slot));
+
+            Assertions.assertEquals(ImmutableSet.of(), 
MaterializeProbeVisitor.indexLazySlots(filter));
+            Assertions.assertFalse(new 
MaterializeProbeVisitor().visitPhysicalFilter(
+                    filter, new 
MaterializeProbeVisitor.ProbeContext(slot)).isPresent());
+        } finally {
+            if (oldContext == null) {
+                ConnectContext.remove();
+            } else {
+                oldContext.setThreadLocalInfo();
+            }
+        }
+    }
+
     private PhysicalOlapScan mockBaseOlapScan(SlotReference outputSlot) {
         OlapTable table = Mockito.mock(OlapTable.class);
         Mockito.when(table.getBaseIndexId()).thenReturn(1L);
diff --git 
a/regression-test/data/fault_injection_p0/test_topn_lazy_index_predicate_slots.out
 
b/regression-test/data/fault_injection_p0/test_topn_lazy_index_predicate_slots.out
new file mode 100644
index 00000000000..c0ec00696a3
--- /dev/null
+++ 
b/regression-test/data/fault_injection_p0/test_topn_lazy_index_predicate_slots.out
@@ -0,0 +1,97 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !search_shape --
+PhysicalResultSink
+--PhysicalProject
+----PhysicalLazyMaterialize[materializedSlots:(topn_lazy_index_predicate_slots.id)
 
lazySlots:(topn_lazy_index_predicate_slots.body,topn_lazy_index_predicate_slots.level)]
+------PhysicalTopN[MERGE_SORT]
+--------PhysicalDistribute[DistributionSpecGather]
+----------PhysicalTopN[LOCAL_SORT]
+------------PhysicalProject
+--------------filter(search("body:error"))
+----------------PhysicalLazyMaterializeOlapScan[topn_lazy_index_predicate_slots
 lazySlots:(topn_lazy_index_predicate_slots.level)]
+
+-- !search --
+7      error error error       ERROR
+5      timeout error from upstream     ERROR
+
+-- !match_shape --
+PhysicalResultSink
+--PhysicalProject
+----PhysicalLazyMaterialize[materializedSlots:(topn_lazy_index_predicate_slots.id)
 
lazySlots:(topn_lazy_index_predicate_slots.body,topn_lazy_index_predicate_slots.level)]
+------PhysicalTopN[MERGE_SORT]
+--------PhysicalDistribute[DistributionSpecGather]
+----------PhysicalTopN[LOCAL_SORT]
+------------PhysicalProject
+--------------filter((topn_lazy_index_predicate_slots.body MATCH_ANY 'error'))
+----------------PhysicalLazyMaterializeOlapScan[topn_lazy_index_predicate_slots
 lazySlots:(topn_lazy_index_predicate_slots.level)]
+
+-- !match --
+1      disk error on node a    ERROR
+3      error while reading block       ERROR
+
+-- !or_shape --
+PhysicalResultSink
+--PhysicalProject
+----PhysicalLazyMaterialize[materializedSlots:(topn_lazy_index_predicate_slots.id)
 
lazySlots:(topn_lazy_index_predicate_slots.body,topn_lazy_index_predicate_slots.level)]
+------PhysicalTopN[MERGE_SORT]
+--------PhysicalDistribute[DistributionSpecGather]
+----------PhysicalTopN[LOCAL_SORT]
+------------PhysicalProject
+--------------filter(OR[(topn_lazy_index_predicate_slots.body MATCH_ALL 'disk 
node'),(topn_lazy_index_predicate_slots.body MATCH_ANY 'timeout')])
+----------------PhysicalLazyMaterializeOlapScan[topn_lazy_index_predicate_slots
 lazySlots:(topn_lazy_index_predicate_slots.level)]
+
+-- !or --
+1      disk error on node a    ERROR
+5      timeout error from upstream     ERROR
+
+-- !alias --
+1      disk error on node a
+3      error while reading block
+5      timeout error from upstream
+
+-- !like_shape --
+PhysicalResultSink
+--PhysicalProject
+----PhysicalLazyMaterialize[materializedSlots:(topn_lazy_index_predicate_slots.id,topn_lazy_index_predicate_slots.body)
 lazySlots:(topn_lazy_index_predicate_slots.level)]
+------PhysicalTopN[MERGE_SORT]
+--------PhysicalDistribute[DistributionSpecGather]
+----------PhysicalTopN[LOCAL_SORT]
+------------filter((topn_lazy_index_predicate_slots.body like '%block%') and 
search("body:error"))
+--------------PhysicalLazyMaterializeOlapScan[topn_lazy_index_predicate_slots 
lazySlots:(topn_lazy_index_predicate_slots.level)]
+
+-- !like --
+3      error while reading block       ERROR
+
+-- !search_without_reading_body --
+7      error error error       ERROR
+5      timeout error from upstream     ERROR
+
+-- !match_without_reading_body --
+1      disk error on node a    ERROR
+3      error while reading block       ERROR
+
+-- !fallback_shape --
+PhysicalResultSink
+--PhysicalProject
+----PhysicalLazyMaterialize[materializedSlots:(topn_lazy_index_predicate_slots_fallback.id)
 
lazySlots:(topn_lazy_index_predicate_slots_fallback.body,topn_lazy_index_predicate_slots_fallback.level)]
+------PhysicalTopN[MERGE_SORT]
+--------PhysicalDistribute[DistributionSpecGather]
+----------PhysicalTopN[LOCAL_SORT]
+------------PhysicalProject
+--------------filter((topn_lazy_index_predicate_slots_fallback.body MATCH_ANY 
'error'))
+----------------PhysicalLazyMaterializeOlapScan[topn_lazy_index_predicate_slots_fallback
 lazySlots:(topn_lazy_index_predicate_slots_fallback.level)]
+
+-- !fallback_match --
+1      disk error on node a    ERROR
+3      error while reading block       ERROR
+5      timeout error from upstream     ERROR
+
+-- !fallback_match_without_lazy_materialization --
+1      disk error on node a    ERROR
+3      error while reading block       ERROR
+5      timeout error from upstream     ERROR
+
+-- !match_without_index --
+1      disk error on node a    ERROR
+3      error while reading block       ERROR
+
diff --git 
a/regression-test/suites/fault_injection_p0/test_topn_lazy_index_predicate_slots.groovy
 
b/regression-test/suites/fault_injection_p0/test_topn_lazy_index_predicate_slots.groovy
new file mode 100644
index 00000000000..6c07e47068e
--- /dev/null
+++ 
b/regression-test/suites/fault_injection_p0/test_topn_lazy_index_predicate_slots.groovy
@@ -0,0 +1,170 @@
+// 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 TopN query fetches a column read only by search() or MATCH above the 
TopN, for the rows that survive it:
+// the scan answers the predicate from the inverted index and does not read 
the column.
+suite("test_topn_lazy_index_predicate_slots", "nonConcurrent") {
+    sql "DROP TABLE IF EXISTS topn_lazy_index_predicate_slots"
+    sql """
+        CREATE TABLE topn_lazy_index_predicate_slots (
+            `id` INT NOT NULL,
+            `body` STRING NULL,
+            `level` VARCHAR(16) NULL,
+            INDEX idx_body (`body`) USING INVERTED PROPERTIES("parser" = 
"english", "support_phrase" = "true")
+        ) 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 topn_lazy_index_predicate_slots VALUES
+            (1, 'disk error on node a', 'ERROR'),
+            (2, 'request served', 'INFO'),
+            (3, 'error while reading block', 'ERROR'),
+            (4, 'cache miss', 'WARN'),
+            (5, 'timeout error from upstream', 'ERROR'),
+            (6, NULL, 'INFO'),
+            (7, 'error error error', 'ERROR')
+    """
+    sql "sync"
+
+    // Only search() or MATCH reads body, so body is fetched lazily with level.
+    qt_search_shape """
+        explain shape plan
+        select id, body, level from topn_lazy_index_predicate_slots
+        where search('body:error') order by id desc limit 2
+    """
+    qt_search """
+        select id, body, level from topn_lazy_index_predicate_slots
+        where search('body:error') order by id desc limit 2
+    """
+    qt_match_shape """
+        explain shape plan
+        select id, body, level from topn_lazy_index_predicate_slots
+        where body match_any 'error' order by id limit 2
+    """
+    qt_match """
+        select id, body, level from topn_lazy_index_predicate_slots
+        where body match_any 'error' order by id limit 2
+    """
+    qt_or_shape """
+        explain shape plan
+        select id, body, level from topn_lazy_index_predicate_slots
+        where (body match_all 'disk node' or body match_any 'timeout') order 
by id limit 2
+    """
+    qt_or """
+        select id, body, level from topn_lazy_index_predicate_slots
+        where (body match_all 'disk node' or body match_any 'timeout') order 
by id limit 2
+    """
+    qt_alias """
+        select id, body as b from topn_lazy_index_predicate_slots
+        where search('body:error') and level = 'ERROR' order by id limit 3
+    """
+    // LIKE reads body row by row, so the scan reads body and keeps it.
+    qt_like_shape """
+        explain shape plan
+        select id, body, level from topn_lazy_index_predicate_slots
+        where search('body:error') and body like '%block%' order by id limit 2
+    """
+    qt_like """
+        select id, body, level from topn_lazy_index_predicate_slots
+        where search('body:error') and body like '%block%' order by id limit 2
+    """
+
+    try {
+        // Any read of body during the scan fails the query.
+        
GetDebugPoint().enableDebugPointForAllBEs("segment_iterator._read_columns_by_index",
 [column_name: "body"])
+        qt_search_without_reading_body """
+            select id, body, level from topn_lazy_index_predicate_slots
+            where search('body:error') order by id desc limit 2
+        """
+        qt_match_without_reading_body """
+            select id, body, level from topn_lazy_index_predicate_slots
+            where body match_any 'error' order by id limit 2
+        """
+        // Without lazy materialization the scan reads body for the output.
+        test {
+            sql """
+                select /*+ SET_VAR(topn_lazy_materialization_threshold=0) */ 
id, body, level
+                from topn_lazy_index_predicate_slots where 
search('body:error') order by id desc limit 2
+            """
+            exception "does not need to read data"
+        }
+    } finally {
+        
GetDebugPoint().disableDebugPointForAllBEs("segment_iterator._read_columns_by_index")
+    }
+
+    // Where a segment has no index, MATCH falls back to row-by-row evaluation 
and the scan reads body for it. Here the
+    // first segment is written before the index is added for new data only, 
the second one after.
+    sql "DROP TABLE IF EXISTS topn_lazy_index_predicate_slots_fallback"
+    sql """
+        CREATE TABLE topn_lazy_index_predicate_slots_fallback (
+            `id` INT NOT NULL,
+            `body` STRING NULL,
+            `level` VARCHAR(16) NULL
+        ) 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 topn_lazy_index_predicate_slots_fallback VALUES
+            (1, 'disk error on node a', 'ERROR'),
+            (2, 'request served', 'INFO'),
+            (3, 'error while reading block', 'ERROR')
+    """
+    sql "SET enable_add_index_for_new_data = true"
+    sql """
+        ALTER TABLE topn_lazy_index_predicate_slots_fallback
+        ADD INDEX idx_body (`body`) USING INVERTED PROPERTIES("parser" = 
"english")
+    """
+    
wait_for_last_col_change_finish("topn_lazy_index_predicate_slots_fallback", 
60000)
+    sql """
+        INSERT INTO topn_lazy_index_predicate_slots_fallback VALUES
+            (4, 'cache miss', 'WARN'),
+            (5, 'timeout error from upstream', 'ERROR'),
+            (6, NULL, 'INFO'),
+            (7, 'error error error', 'ERROR')
+    """
+    sql "sync"
+
+    // The plan still fetches body after the TopN; rows 1 and 3 match row by 
row, row 5 through the index.
+    qt_fallback_shape """
+        explain shape plan
+        select id, body, level from topn_lazy_index_predicate_slots_fallback
+        where body match_any 'error' order by id limit 3
+    """
+    qt_fallback_match """
+        select id, body, level from topn_lazy_index_predicate_slots_fallback
+        where body match_any 'error' order by id limit 3
+    """
+    qt_fallback_match_without_lazy_materialization """
+        select /*+ SET_VAR(topn_lazy_materialization_threshold=0) */ id, body, 
level
+        from topn_lazy_index_predicate_slots_fallback where body match_any 
'error' order by id limit 3
+    """
+    // With inverted index queries off, every segment evaluates MATCH row by 
row.
+    qt_match_without_index """
+        select /*+ SET_VAR(enable_inverted_index_query=false) */ id, body, 
level
+        from topn_lazy_index_predicate_slots where body match_any 'error' 
order by id limit 2
+    """
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to