Skip to content

[FEATURE] Add support for PartiQL in the V2 engine #1104

Closed as not planned
Closed as not planned

Description

@GumpacG

Is your feature request related to a problem?
Running doctests on the v2 engine without falling back to the legacy engine fails on partiql.rst.
Query: SELECT city, accounts, projects FROM people;

Error:
Failed example: sql_cmd.process('SELECT city, accounts, projects FROM people')Exception raised: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/doctest.py", line 1336, in __run exec(compile(example.source, filename, "single", File "<doctest partiql.rst[0]>", line 1, in <module> sql_cmd.process('SELECT city, accounts, projects FROM people') File "/Users/guiang/Documents/GitHub/opensearch-project-sql/doctest/test_docs.py", line 42, in process output = self.formatter.format_output(data) File "/Users/guiang/Documents/GitHub/opensearch-project-sql/sql-cli/src/opensearch_sql_cli/formatter.py", line 60, in format_output datarows = data["datarows"] TypeError: 'NoneType' object is not subscriptable

Activity

  1. added
    enhancement
    on Nov 24, 2022
  2. dai-chen commented on Feb 8, 2023

    @dai-chen
    Collaborator

    PartiQL Support in OpenSearch SQL V2 Engine

    Background

    Previously we identified 6 common usage in PartiQL and added limited support in legacy engine:

    • E1: Enable access to nested attributes with optional UNNEST keyword
    • E2: Enable access to nested attributes with LEFT JOIN
    • E3: Support full-text search and rank by similarity score
    • E4: Support Grouping by Elasticsearch Aggregation
    • E5: Check whether a nested collection satisfies a condition
    • E6: Support subqueries that aggregate over nested collections

    Proposed Solution

    The key challenge is in the design of logical and physical operator behind PartiQL grammar. Take the following query for example in this section:

    SELECT e.name, p.name
    FROM employees AS e,
         e.projects AS p
    WHERE p.name LIKE '%security%'
    

    Approach 1: Adding New Operator for Unnest Operation

    First option is to add a new UNNEST operator to handle the comma join in FROM clause entirely.

    Project(Q(e.name, STRING), Q(p.name, STRING))
    - Filter(Like(Q(p.name, STRING), '%security%'))
     - Unnest(Q(e.projects, ARRAY), p)
      - OpenSearchIndexScan(employees, e)
    
    • Pros
      • Very straightforward to understand and implement
    • Cons
      • Difficult to deduce the semantics for deep nested query
      • Need to implement each correlate operation defined in PartiQL for this new operator, ex. CROSS, INNER, OUTER, SEMI

    Approach 2: Reusing Nested Loop Join Operator [Preferred]

    Alternatively, we can reuse nested loop operator as below. See Examples section for more details.

    Project(Q(e.name, STRING), Q(p.name, STRING))
    - Filter(Like(Q(p.name, STRING), '%security%'))
     - NestedLoop(type=inner, on=true) -- Cross join
      - OpenSearchIndexScan(employees, e)
      - LateralScan(e.projects, p) -- Special scan whose input comes from left side scan operator
    
    • Pros
      • Reuse same operators as JOIN
      • Deep nested field is supported by multi-join automatically
    • Cons
      • Need to do some "trick" so right side can access each row generated by left side

    This is how SQL Lateral Join implemented and inspired by a sentence in PartiQL spec 5.7 SQL's LATERAL. Find more details in appendix.

    SQL 2003 used the LATERAL keyword to correlate FROM clause items. In the interest of compatibility with SQL, PartiQL
    also allows the use of the keyword LATERAL, though it does not do anything more than the comma itself would do.
    That is “l , LATERAL r” is equivalent to “l , r”.

    Examples

    E1: Enable access to nested attributes with optional UNNEST keyword

    Query:

    SELECT e.name, p.name
    FROM employees AS e,
         e.projects AS p
    WHERE p.name LIKE '%security%'
    

    AST may look like this:

    Project(e.name, p.name)
    - Filter(Like(p.name, '%security'))
     - Join(type=inner, on=true)
      - Relation(employees, e)
      - Relation(e.projects, p)
    

    Q stands for QualifiedName after analyzed:

    Project(Q(e.name, STRING), Q(p.name, STRING))
    - Filter(Like(Q(p.name, STRING))
     - Join(type=inner, on=true) 
      - TableScan(Table(employees), e)
      - LateralScan(Q(e.projects, ARRAY), p)
    

    After optimized with Filter operator pushed down:

    Project(Q(e.name, STRING), Q(p.name, STRING))
     - NestedLoop(type=inner, on=true)
      - OpenSearchIndexScan(employees,
       dsl='
       "query": {
        "nested": {
          "path": "projects",
          "query": {
            "bool": {
              "must": [
                { "wildcard": { "projects.name": "%security" }} 
              ]
            }
          }
        }
       }',
       output={
        e.name: stringValue(name),
        e.projects: arrayValue(projects)
       }
      )
      - LateralScan(e.projects
        output={
          p: structValue(e.projects[X]) // flatten and bind p to each of e.projects
        }
      )
    

    E2: Enable access to nested attributes with LEFT JOIN

    PartiQL Left Join is meant for preserving parent information even if parent doesn't has the nested field.

    Query:

    SELECT e.name, p.name
    FROM employees AS e,
    LEFT JOIN e.projects AS p
    WHERE p.name LIKE '%security%'
    

    AST:

    Project(e.name, p.name)
    - Filter(Like(p.name, '%security%'))
     - Join(type=left_outer, on=true)
      - Relation(employees, e)
      - Relation(e.projects, p)
    

    After analyzed:

    Project(Q(e.name, STRING), Q(p.name, STRING))
    - Filter(Like(Q(p.name, STRING), '%security%')
     - Join(type=left_outer, on=true) 
      - TableScan(Table(employees), e)
      - LateralScan(Q(e.projects, ARRAY), p)
    

    After optimized:

    Project(Q(e.name, STRING), Q(p.name, STRING))
     - Filter(Like(Q(p.name, STRING))  -- Cannot push down to DSL which may skip parent doc if no nested field meet the filtering condition or no nested field at all
      - NestedLoop(inner=left_outer, on=true)
       - OpenSearchIndexScan(employees,
        dsl='{}',
        output={
         e.name: stringValue(name),
         e.projects: arrayValue(projects)
        }
       )
       - LateralScan(e.projects
        output={
          p: structValue(e.projects[X])
        }
       )
    

    E5: Check whether a nested collection satisfies a condition

    Semi Join in PartiQL is also same behavior as ANSI SQL. Once semi join operator finds one match from right side, it moves on to next row from left side.

    Query:

    SELECT e.name
    FROM employees **AS** e
    WHERE EXISTS (
     SELECT *
     FROM e.projects AS p
     WHERE p.name LIKE '%security%'
    )
    

    AST:

    Project(e.name)
    - Join(type=semi, on=true)
     - Relation(employees, e)
     - RelationSubquery
      - Project(*)
       - Filter(Like(p.name, '%security%')
        - Relation(e.projects, p)
    

    After analyzed:

    Project(Q(e.name), STRING)
    - Join(type=semi, on=true)
     - TableScan(Table(employees), e)
     - Project(All)
      - Filter(Like(Q(p.name, STRING), '%security%')
       - LateralScan(Q(e.projects, ARRAY), p)
    

    After optimized:

    Project(Q(e.name, STRING), Q(p.name, STRING))
     - NestedLoop(inner=semi, on=true)
      - OpenSearchIndexScan(employees,
        dsl='{}',
        output={
         e.name: stringValue(name),
         e.projects: arrayValue(projects)
        }
       )
      - Project(All)
       - Filter(Like(Q(p.name, STRING), '%security%')
        - LateralScan(e.projects
         output={
          p: structValue(e.projects[X])
         }
        )
    

    Unnesting Arrays of Array (Deep Nested Field)

    Assume each project also has nested field members at next level.

    SELECT e.name, p.name
    FROM employees AS e,
         e.projects AS p,
         p.members AS m
    WHERE m.age > 30
    

    AST:

    Project(e.name, p.name)
    - Filter(Greater(p.name, 30))
     - Join(type=inner, on=true)
      - Relation(p.members, m)
      - Join(type=inner, on=true)
       - Relation(employees, e)
       - Relation(e.projects, p)
    

    After analyzed:

    Project(Q(e.name, STRING), Q(p.name, STRING))
    - Filter(Greater(Q(p.age, INT), 30))
     - Join(type=inner, on=true)
     |  - Join(type=inner, on=true)
     |  |- TableScan(Table(employees), e)
     |  |- LateralScan(Q(e.projects, ARRAY), p)
     |- LateralScan(Q(p.members, ARRAY), m)
    

    After optimized:

    Project(Q(e.name, STRING), Q(p.name, STRING))
     - NestedLoop(type=inner, on=true)
     |   - NestedLoop(type=inner, on=true)
     |   |- OpenSearchIndexScan(employees,
     |   | dsl='{ omit pushed down filter... }',
     |   |  output={
     |   |   e.name: stringValue(name),
     |   |   e.projects: arrayValue(projects)
     |   |  }
     |   |)
     |   |- LateralScan(e.projects
     |    output={
     |      p: structValue(e.projects[X]) // flatten and bind p to each of e.projects
     |    }
     |  )
     | - LateralScan(p.members
        output={
          m: structValue(p.members[X]) // flatten and bind m to each of p.members
        }
      )
    

    Physical Operator Reference Implementation

    Generic nested loop operator. LateralContract interface allows right side to fetch row from left side. <-- Need more investigation how to make this support generic lateral join

    class NestedLoop implements PhysicalOperator, LateralContract:
      val left : PhysicalOperator
      val right : PhysicalOperator
      val joinCond: Expression
      var lnext: ExprValue
     
      def hasNext(): boolean = {
        return next != null
      }
     
      def loadNext() = {
        for lnext in left.next():  // lnext is set here
          for rnext in right.next():
            joinCond.valueOf({lnext, rnext}) is True:
              next = output(lnext, rnext)
      }
    
      def getLeftOutput():
        return lnext
    
    class LateralScan implements PhysicalOperator:
     val lateral: LateralContract
     val ref: Reference  // nested field name
     val nextIt: Iterator<ExprValue>
    
     def hasNext(): boolean = {
       return next.hasNext()
     }
     
     def next(): ExprValue = {
       if not nextIt.hasNext():
         array = ref.valueOf(lateral.getLeftOutput())
         nextIt = array.iterator()
       return nextIt.next
     }
    

    Appendix

    Here explains what's lateral join and you will see how similar it is as PartiQL in the case of nested JSON value:

    A LATERAL join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a lateral join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. The difference between Lateral Join and Correlated Subquery is: There are things that a lateral join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows.

    For example in PostgreSQL 9.6: At execution time, variable p is binding to each row of table test. The right side of join has access to it and flatten p.data to left join each nested row bind to variable child with their parent row bind to p currently.

    CREATE TABLE test(id SERIAL PRIMARY KEY, data JSONB);
    
    INSERT INTO test(data) VALUES
       ('{"parent":null,"children":[2,3]}'),
       ('{"parent":1,   "children":[4,5]}'),
       ('{"parent":1,   "children":[]}'),
       ('{"parent":2,   "children":[]}'),
       ('{"parent":2,   "children":[]}');
    
    SELECT p.data, child
    FROM   test p
    LEFT JOIN LATERAL jsonb_array_elements_text(p.data->'children') child
    ON TRUE;
    

    Results:
    Screen Shot 2022-12-30 at 11 18 07 AM

    Query execution plan:
    Screen Shot 2022-12-30 at 11 18 57 AM

  3. added and removed
    enhancement
    on Feb 8, 2023
  4. MaxKsyunz commented on Feb 8, 2023

    @MaxKsyunz
    Collaborator

    @dai-chen

    How would nested loop work with push down to OpenSearch?

    In the example you used

    Project(Q(e.name, STRING), Q(p.name, STRING))
    - Filter(Like(Q(p.name, STRING), '%security%'))
     - NestedLoop(type=inner, on=Eq(e._id, ) -- Virtual id to join parent and inner doc
      - OpenSearchIndexScan(employees, e)
      - NestedScan(e.projects, p) -- Special scan whose input comes from left side scan operator
    

    neither Project nor Filter can be pushed down to OpenSearch but currently they both are. In fact, Filter seems to be pushed down unconditionally.

  5. dai-chen commented on Feb 8, 2023

    @dai-chen
    Collaborator

    @MaxKsyunz Thanks for your early review! Will let you know when I'm done today. Let me see if I can answer this in Examples section. Afterwards, I will link this to our Nested Function PR for more discussion. Thanks!

  6. added
    engine v2
    on Mar 26, 2026
  7. LantaoJin commented on Mar 26, 2026

    @LantaoJin
    Member

    Won't do as v2 only.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    engine v2featurenew-engine-gap

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions