Skip to content

Support project expression pushdown with derived field script - #4288

Closed
songkant-aws wants to merge 50 commits into
opensearch-project:mainfrom
songkant-aws:project-pushdown
Closed

songkant-aws wants to merge 50 commits into
opensearch-project:mainfrom
songkant-aws:project-pushdown

Conversation

@songkant-aws

@songkant-aws songkant-aws commented Sep 12, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Support project expression pushdown with derived field script.

This is the first phase of script project pushdown with partial script project supported. Follow-up like supporting partial filter pushdown after script project pushdown will be implemented later.

DerivedFieldScript Pros and Cons:

Pros:

  1. DerivedFieldScript is evaluated at Search phase, which means it allows some non script filtering
  2. Part of aggregations over derived field are supported. See: https://docs.opensearch.org/latest/field-types/supported-field-types/derived/#aggregations

Cons:

  1. Limited type is supported. See: https://docs.opensearch.org/latest/field-types/supported-field-types/derived/#emitting-values-in-scripts. It needs one more layer to process correct data type in Calcite for not supported data types.
  2. Scoring and sorting is not supported

Script field Pros and Cons:

Pros:

  1. The output is Object, it allows Calcite flexibly process the right data type.

Cons:

  1. Script_fields is evaluated post SearchPhase. It doesn't support filtering.
  2. Sorting is not supported as well
  3. Can't be involved in aggregation

Benchmark Results After Optimization

CalcitePPLBig5IT:
Summary:
asc_sort_timestamp: 8 ms
asc_sort_timestamp_can_match_shortcut: 13 ms
asc_sort_timestamp_no_can_match_shortcut: 12 ms
asc_sort_with_after_timestamp: 9 ms
bin_bins: 7 ms
bin_span_log: 8 ms
bin_span_time: 16 ms
composite_date_histogram_daily: 23 ms
composite_terms: 52 ms
composite_terms_keyword: 27 ms
date_histogram_hourly_agg: 13 ms
date_histogram_minute_agg: 22 ms
default: 9 ms
desc_sort_timestamp: 10 ms
desc_sort_timestamp_can_match_shortcut: 16 ms
desc_sort_timestamp_no_can_match_shortcut: 24 ms
desc_sort_with_after_timestamp: 9 ms
keyword_in_range: 23 ms
keyword_terms: 17 ms
keyword_terms_low_cardinality: 13 ms
multi_terms_keyword: 25 ms
query_string_on_message: 14 ms
query_string_on_message_filtered: 34 ms
query_string_on_message_filtered_sorted_num: 39 ms
range: 12 ms
range_auto_date_histo: 37 ms
range_auto_date_histo_with_metrics: 72 ms
range_field_conjunction_big_range_big_term_query: 10 ms
range_field_conjunction_small_range_big_term_query: 8 ms
range_field_conjunction_small_range_small_term_query: 15 ms
range_field_disjunction_big_range_small_term_query: 10 ms
range_numeric: 11 ms
range_with_asc_sort: 17 ms
range_with_desc_sort: 15 ms
scroll: 7 ms
sort_keyword_can_match_shortcut: 14 ms
sort_keyword_no_can_match_shortcut: 14 ms
sort_numeric_asc: 14 ms
sort_numeric_asc_with_match: 17 ms
sort_numeric_desc: 22 ms
sort_numeric_desc_with_match: 15 ms
term: 17 ms
terms_significant_1: 19 ms
terms_significant_2: 16 ms
Total 44 queries succeed. Average duration: 18 ms

CalcitePPLClickBenchIT:
Summary:
q1: 21 ms
q10: 59 ms
q11: 26 ms
q12: 31 ms
q13: 15 ms
q14: 21 ms
q15: 18 ms
q16: 13 ms
q17: 14 ms
q18: 10 ms
q19: 19 ms
q2: 18 ms
q20: 8 ms
q21: 11 ms
q22: 19 ms
q23: 24 ms
q24: 17 ms
q25: 15 ms
q26: 13 ms
q27: 15 ms
q28: 32 ms
q3: 21 ms
q31: 29 ms
q32: 31 ms
q33: 24 ms
q34: 12 ms
q35: 15 ms
q36: 18 ms
q37: 24 ms
q38: 22 ms
q39: 23 ms
q4: 16 ms
q40: 26 ms
q41: 27 ms
q42: 23 ms
q43: 31 ms
q5: 12 ms
q6: 12 ms
q7: 17 ms
q8: 21 ms
q9: 23 ms
Total 41 queries succeed. Average duration: 20 ms

Related Issues

Resolves #3387

Check List

  • New functionality includes testing.
  • New functionality has been documented.
  • New functionality has javadoc added.
  • New functionality has a user manual doc added.
  • New PPL command checklist all confirmed.
  • API changes companion pull request created.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

Comment on lines +123 to +125
OpenSearchIndexScanRule::isScriptProjectPushed)
.and(OpenSearchIndexScanRule::isProjectPushed)
.and(OpenSearchIndexScanRule::noLimitPushed)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally, we don't need such complex condition check. Script project pushdown can be merged to project pushdown method. Will optimize it later.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merged two kinds of project into one method. This reduces the dependency on each other and reduces the times of rewriting plan. Additionally, if we introduce more rules related to project pushdown, it could be easier to modify current logic.

@songkant-aws songkant-aws changed the title [Feature] Support project expression pushdown with derived field script Support project expression pushdown with derived field script Sep 12, 2025
@songkant-aws
songkant-aws marked this pull request as ready for review September 12, 2025 10:45
@songkant-aws

Copy link
Copy Markdown
Collaborator Author

Could you review this PR with another look? @qianheng-aws @LantaoJin @yuancu

yuancu
yuancu previously approved these changes Oct 21, 2025

@yuancu yuancu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Comment on lines +98 to +101
"source=opensearch-sql_test_index_account"
+ "| eval age = age + 2"
+ "| fields age, lastname"));
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems in the plan the new age field becomes age0. I'm curious where is it set back to name age

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems the column names in our final results are derived from the original plan(i.e. logical plan), so the final plan(i.e. physical plan) is allowed to produce a different row type as long as the types can match.

qianheng-aws
qianheng-aws previously approved these changes Oct 21, 2025
@qianheng-aws

Copy link
Copy Markdown
Collaborator

@LantaoJin Please take another look at this PR.

@songkant-aws
songkant-aws dismissed stale reviews from qianheng-aws and yuancu via dd22241 October 22, 2025 07:48
qianheng-aws
qianheng-aws previously approved these changes Oct 22, 2025
@songkant-aws

songkant-aws commented Oct 23, 2025 •

Copy link
Copy Markdown
Collaborator Author

@qianheng-aws @LantaoJin

To be conservative here, I added some minor protection in the script project cost computation.

With mini benchmark of very few rows(less than 5 rows), if we push down around 15 derived fields, the performance is almost equal to no pushdown query. To balance the pushdown benefit and cost, I pick an upper limit like half of 15, aka 7 script here. If the derived field script is less than 7, we think it will more likely bring performance benefit to the query.

So a minor improvement logic is, if the derived scripts to be pushed is more than 7. We will give more penalty cost like rows * penalty * over threshold delta * over threshold delta. It may allow more script column pushdown for wide schema index. In general, it will allow pushing down around 7 script columns or less.

@LantaoJin

Copy link
Copy Markdown
Member

@qianheng-aws @LantaoJin

To be conservative here, I added some minor protection in the script project cost computation.

With mini benchmark of very few rows(less than 5 rows), if we push down around 15 derived fields, the performance is almost equal to no pushdown query. To balance the pushdown benefit and cost, I pick an upper limit like half of 15, aka 7 script here. If the derived field script is less than 7, we think it will more likely bring performance benefit to the query.

So a minor improvement logic is, if the derived scripts to be pushed is more than 7. We will give more penalty cost like rows * penalty * over threshold delta * over threshold delta. It may allow more script column pushdown for wide schema index. In general, it will allow pushing down around 7 script columns or less.

synced offline. we need to benchmark on big size dataset. And I think this feature is only worth to enable with sort script pushdown as project expression only pushdown would be a high cost operator for OpenSearch cluster.

* Considering the case of wide schema table, it will likely allow more than this
* cap derived field script pushdown.
*
* For example, say we have a 300 column wide table. We want to pushdown 9 derived fields.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the approach of blocking pushing down script_project with scripts more than 9 more straightforward?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking the same thing. But in other side, pruning a wide schema table to keep very less fields is probably still valuable. Anyway, this feature will be shown with very less performance improvement by a potential waste of CPU for each shard. I will close this PR.

// almost equal to no pushdown query. To balance the pushdown benefit and cost, we pick an upper
// limit like half of 15, aka 7 script here. If the derived field script is less than 7,
// We think it will more likely bring performance benefit to the query.
private static final int SCRIPT_PROJECT_SOFT_CAP = 7;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should these threshold be configurable?

@songkant-aws

Copy link
Copy Markdown
Collaborator Author

I did some benchmark test.

Query top 10000 documents in single shard cluster with nearly 100,000,000 rows profile:

curl -XPOST "http://localhost:9200/hits/_search" -H 'Content-Type: application/json' -d'
{
  "_source":{"includes":["Income"],"excludes":[]},
  "fields": ["Income"],
  "profile": true,
  "size": 10000
}' | jq 'del(.hits)'

Profile Result:

{
    "took": 146,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "profile": {
        "shards": [{
            "id": "[m0qfG2CATIe2x6HE4-iRUg][hits][0]",
            "searches": [{
                "query": [{
                    "type": "MatchAllDocsQuery",
                    "description": "*:*",
                    "time_in_nanos": 547264,
                    "breakdown": {
                        ...
                        "match": 0,
                        "match_count": 0,
                        "next_doc": 245313,
                        "next_doc_count": 10030,
                        "score": 246361,
                        "score_count": 10001,
                        ...
                    }
                }],
                "rewrite_time": 4310,
                "collector": [{
                    "name": "TopScoreDocCollector",
                    "reason": "search_top_hits",
                    "time_in_nanos": 1592568
                }]
            }],
            "aggregations": [],
            ....
        }]
    }
}

Query top 10000 documents and compute derived field in single shard cluster with nearly 100,000,000 rows profile:

curl -XPOST "http://localhost:9200/hits/_search" -H 'Content-Type: application/json' -d'
{
  "derived": {
    "IncomePlus": {
      "type": "long",
      "script": {
        "source": "emit(doc[\"Income\"].value * 100)"
      }
    }
  },
  "_source":{"includes":["Income"],"excludes":[]},
  "fields": ["Income", "IncomePlus"],
  "profile": true,
  "size": 10000
}' | jq 'del(.hits)'

Profile result:

{
    "took": 147,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "profile": {
        "shards": [{
            "id": "[m0qfG2CATIe2x6HE4-iRUg][hits][0]",
            "inbound_network_time_in_millis": 0,
            "outbound_network_time_in_millis": 0,
            "searches": [{
                "query": [{
                    "type": "MatchAllDocsQuery",
                    "description": "*:*",
                    "time_in_nanos": 542526,
                    "breakdown": {
                        ....
                        "next_doc": 249458,
                        "next_doc_count": 10030,
                        "score": 240228,
                        "score_count": 10001,
                        ...
                    }
                }],
                "rewrite_time": 5040,
                "collector": [{
                    "name": "TopScoreDocCollector",
                    "reason": "search_top_hits",
                    "time_in_nanos": 1866090
                }]
            }],
            "aggregations": [],
            ...
        }]
    }
}

This experiment demonstrates computing derived field not involved in filter query has similar performance to list required columns. Because both of them go through MatchAllDocsQuery, aka it takes top 10000 first and then executes script for derived field.

@songkant-aws

Copy link
Copy Markdown
Collaborator Author

The second experiment proves the derived field script will be executed in each shard

Create index:

curl -XPUT "http://localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "value": { "type": "integer" },
      "name": { "type": "keyword" }
    }
  }
}'

Put some data

curl -XPUT "http://localhost:9200/my_index/_doc/1" -H 'Content-Type: application/json' -d'
{ "name": "doc1", "value": 100 }'

curl -XPUT "http://localhost:9200/my_index/_doc/2" -H 'Content-Type: application/json' -d'
{ "name": "doc2", "value": 200 }'

curl -XPUT "http://localhost:9200/my_index/_doc/3" -H 'Content-Type: application/json' -d'
{ "name": "doc3", "value": 300 }'

Query:

curl -XPOST "http://localhost:9200/hits/_search" -H 'Content-Type: application/json' -d'
{
  "derived": {
    "IncomePlus": {
      "type": "long",
      "script": {
        "source": "emit(doc[\"value\"].value * 100)"
      }
    }
  },
  "_source":{"includes":["value"],"excludes":[]},
  "fields": ["value", "IncomePlus"],
  "profile": true,
  "size": 10000
}' | jq 'del(.hits)'

Profile result:

{
  "took": 177,
  "timed_out": false,
  "_shards": {
    "total": 3,
    "successful": 3,
    "skipped": 0,
    "failed": 0
  },
  "profile": {
    "shards": [
      {
        "id": "[1U42st6jQQqsbFGye3RAPA][my_index][0]",
        "inbound_network_time_in_millis": 0,
        "outbound_network_time_in_millis": 0,
        "searches": [
          {
            "query": [
              {
                "type": "MatchAllDocsQuery",
                ....

The above profile result shows the query hits all of shards and performs script execution.

@songkant-aws

songkant-aws commented Oct 24, 2025 •

Copy link
Copy Markdown
Collaborator Author

Derived field will be executed on each row when it's involved in filter query

Derived field of filter query on single shard cluster with 100,000,000 rows:

curl -XPOST "http://localhost:9200/hits/_search" -H 'Content-Type: application/json' -d'
{
  "derived": {
    "IncomePlus": {
      "type": "long",
      "script": {
        "source": "emit(doc[\"Income\"].value * 100)"
      }
    }
  },
  "_source":{"includes":["Income"],"excludes":[]},
  "query": {
        "range": {
            "IncomePlus": {
                "gt": 1000
            }
        }
    },
  "fields": ["Income", "IncomePlus"],
  "profile": true,
  "size": 10000
}' | jq 'del(.hits)'

Profile result:

{
    "took": 55552,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "profile": {
        "shards": [{
            "id": "[m0qfG2CATIe2x6HE4-iRUg][hits][0]",
            "inbound_network_time_in_millis": 0,
            "outbound_network_time_in_millis": 0,
            "searches": [{
                "query": [{
                    "type": "DerivedFieldQuery",
                    "description": "DerivedFieldQuery (Query: [ IndexOrDocValuesQuery(indexQuery=IncomePlus:[1001 TO 9223372036854775807], dvQuery=IncomePlus:[1001 TO 9223372036854775807])])",
                    "time_in_nanos": 61814297771,
                    "breakdown": {
                        "advance": 0,
                        "advance_count": 0,
                        "build_scorer": 4584279,
                        "build_scorer_count": 58,
                        "compute_max_score": 0,
                        "compute_max_score_count": 0,
                        "create_weight": 428422,
                        "create_weight_count": 1,
                        "match": 58462604120,
                        "match_count": 99997497,
                        "next_doc": 3346680950,
                        "next_doc_count": 99997526,
                        "score": 0,
                        "score_count": 0,
                        "set_min_competitive_score": 0,
                        "set_min_competitive_score_count": 0,
                        "shallow_advance": 0,
                        "shallow_advance_count": 0
                    }
                }],
                "rewrite_time": 17920,
                "collector": [{
                    "name": "TopScoreDocCollector",
                    "reason": "search_top_hits",
                    "time_in_nanos": 538682
                }]
            }],
            "aggregations": [],
            "fetch": []
        }]
    }
}

Filter script has far better performance than computing derived field with filter query

curl -XPOST "http://localhost:9200/hits/_search" -H 'Content-Type: application/json' -d'
{
  "_source":{"includes":["Income"],"excludes":[]},
  "query": {
    "script": {
      "script": {
        "source": "doc[\"Income\"].value * 100 > 1000"
      }
    }
  },
  "profile": true,
  "size": 10000
}' | jq 'del(.hits)'

Profile result:

{
  "took": 2935,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "profile": {
    "shards": [
      {
        "id": "[m0qfG2CATIe2x6HE4-iRUg][hits][0]",
        "inbound_network_time_in_millis": 0,
        "outbound_network_time_in_millis": 0,
        "searches": [
          {
            "query": [
              {
                "type": "ScriptQuery",
                "description": "ScriptQuery(Script{type=inline, lang='painless', idOrCode='doc[\"Income\"].value * 100 > 1000', options={}, params={}})",
                "time_in_nanos": 7160725980,
                "breakdown": {
                  "advance": 0,
                  "advance_count": 0,
                  "build_scorer": 395953,
                  "build_scorer_count": 58,
                  "compute_max_score": 0,
                  "compute_max_score_count": 0,
                  "create_weight": 2580,
                  "create_weight_count": 1,
                  "match": 4674453073,
                  "match_count": 99997497,
                  "next_doc": 2485874374,
                  "next_doc_count": 99997526,
                  "score": 0,
                  "score_count": 0,
                  "set_min_competitive_score": 0,
                  "set_min_competitive_score_count": 0,
                  "shallow_advance": 0,
                  "shallow_advance_count": 0
                }
              }
            ],
            "rewrite_time": 3570,
            "collector": [
              {
                "name": "TopScoreDocCollector",
                "reason": "search_top_hits",
                "time_in_nanos": 81160
              }
            ]
          }
        ],
        "aggregations": [],
        "fetch": []
      }
    ]
  }
}

The above benchmark proves derived field script will be only executed on each document when it's involved in filter query. But its performance is far worse than the same filter script.

@songkant-aws

Copy link
Copy Markdown
Collaborator Author

@LantaoJin I will close this feature PR and mark it 'won't do'. I have done several benchmarks and pasted result in above comments. Here are the conclusions:

  1. If derived fields are simply selected in the source output, it will take top 10000 documents and perform script execution on 10000 inputs.
  2. Derived field scripts will be performed on each shard.
  3. If derived fields are involved in filter query, it will perform script execution on whole data each shard and then take filtered top 10000 results. This process has bad performance on large datasets.

This PR introduces a process where derived fields are computed via script on each shard for the top 10,000 documents. OpenSearch’s FetchPhase then collects these documents and returns the results to the coordinator node.

However, this approach offers limited performance gains—since the same script runs on the same input size, whether sequentially on one node or in parallel across multiple nodes. The primary benefit is offloading CPU pressure from the coordinator node, at the cost of increased CPU usage across the data nodes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Calcite Engine Framework: pushdown whole project instead of reference

4 participants