Skip to content

[RFC] Implement Nested in the V2 Engine - #1210

Closed
GumpacG wants to merge 4 commits into
opensearch-project:mainfrom
Bit-Quill:dev-spike-nested
Closed

GumpacG wants to merge 4 commits into
opensearch-project:mainfrom
Bit-Quill:dev-spike-nested

Conversation

@GumpacG

@GumpacG GumpacG commented Dec 27, 2022 •

Copy link
Copy Markdown
Collaborator

Description

This proposal will outline a suggestion for the scope and implementation of the nested function in the V2 engine. This Draft PR is only meant for discussion and not to be merged.

Requirements

nested in the new engine needs to support all functionality of nested in the legacy engine. This includes:

  • nested in SELECT, WHERE, GROUP BY. example queries:

    • SELECT nested(message.info) FROM multi_nested

    • SELECT nested(message.*) FROM multi_nested

    • SELECT nested(message.info) FROM multi_nested WHERE nested('message', message.info = 'a' OR message.info = 'a')

    • SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested(message.info)='b';

    • SELECT nested(message.info) FROM multi_nested GROUP BY nested(message.info)

    • SELECT nested(message.info) FROM multi_nested GROUP BY message.info

  • alias of the result should be the argument of the nested function

  • nested in function calls like SELECT nested(message.info) FROM multi_nested WHERE wildcardquery(nested(message.info), 'z*')

  • multilevel nested field queries like SELECT nested(message.author.address.street) FROM opensearch-sql_test_index_multi_nested

  • multiple nested functions in one query which is a limitation on elasticsearch like SELECT nested(message.author.address.street), nested(message.info), nested(message.dayOfWeek) FROM opensearch-sql_test_index_multi_nested

  • nested accepts strings as arguments for identifiers (This still needs to be investigated if it should not be supported). Example queries are:

    • SELECT nested("field.subield") FROM test;

    • SELECT nested("field"."subield") FROM test;

    • SELECT nested('field.subield') FROM test;

    • SELECT nested('field'.'subield') FROM test;

Limitations

If we decide to not support strings as argument, then this will become a breaking change for 3.x

Implementation

The new SQL engine implementation of nested function will be similar to the implementation of nested function in legacy. The logical plan builder implementation will be the same. Legacy’s logical plan builder is a part of NestedFieldProjection while the new engine will contain it in OpenSearchRequestBuilder. This is currently implemented in this PoC for nested in only the SELECT clause. Implementation for nested in WHERE and GROUP BY may be different.

Proof of Concept

The PoC does not satisfy all requirements for nested in SELECT. It only supports an end to end implementation of SELECT nested(message.info) FROM opensearch-sql_test_index_nested_type;. Further testing and support for more cases will be added once we are in agreement of the PoC.

SQL queries to support for each stage of implementation

// Support nested in SELECT (POC)
SELECT nested(message.info), someField FROM opensearch-sql_test_index_nested_type;

// Support for *
SELECT nested(message.*) FROM opensearch-sql_test_index_nested_type;

// WHERE support
SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested(comment.likes) > 1;
SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested(comment.likes) < 3;
SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested(message.info)='b';
SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested(message.info) = IN_TERMS('a', 'b');
SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested('message', message.info = 'a' AND message.author ='h');
SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested('message', message.info = 'a' AND message.author ='i');
SELECT * FROM opensearch-sql_test_index_nested_type WHERE nested(message.info) = 'a';
SELECT comment.data FROM opensearch-sql_test_index_nested_type WHERE MATCH_QUERY(NESTED(comment.data), 'aa');
SELECT comment.data FROM opensearch-sql_test_index_nested_type WHERE SCORE(MATCH_QUERY(NESTED(comment.data), 'ab'), 10);

// GROUP BY support
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info)
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY message.info

// Multilevel nested support
SELECT nested(message.author.address.street) FROM opensearch-sql_test_index_multi_nested;
SELECT nested(message.author.address) FROM opensearch-sql_test_index_multi_nested;
SELECT nested(message.author.address.street), nested(message.info), nested(message.dayOfWeek) FROM opensearch-sql_test_index_multi_nested;

// Additional tests from legacy
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info),filter('myFilter',message.info = 'a'),reverse_nested(comment.data,'~comment');
SELECT min(nested(message.dayOfWeek)) as minDays FROM opensearch-sql_test_index_nested_type;
SELECT sum(reverse_nested(comment.likes,'~comment')) bla FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info),filter('myFilter',message.info = 'a');
SELECT sum(reverse_nested(myNum)) bla FROM opensearch-sql_test_index_nested_type GROUP BY nested(message.info),filter('myFilter',message.info = 'a');
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info),filter('myFilter',message.info = 'a'),reverse_nested(someField);
SELECT sum(nested(message.dayOfWeek)) as sumDays FROM opensearch-sql_test_index_nested_type;
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info),filter('myFilter',message.info = 'a'),histogram('field'='comment.likes','reverse_nested'='~comment','interval'='2' , 'alias' = 'someAlias' );
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info),filter('myFilter',message.info = 'a'),histogram('field'='myNum','reverse_nested'='','interval'='2', 'alias' = 'someAlias' );
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info),filter('myFilter',message.info = 'a'),reverse_nested(someField,'');
SELECT COUNT(*) FROM opensearch-sql_test_index_nested_type GROUP BY  nested(message.info),filter('myFilter',message.info = 'a');

// Support for string arguments as legacy supports
SELECT nested("field.subield") FROM test;
SELECT nested("field"."subield") FROM test;
SELECT nested('field.subield') FROM test;
SELECT nested('field'.'subield') FROM test;

Schedule

Priority Description Target Version
P0 nested function working in SELECT, WHERE, and GROUP BY 2.x
P0 Filter and histogram should work with nested fields as specified in the legacy IT tests 2.x
P1 Fix bugs in #52 if they still exist 2.x

Issues Resolved

#1111

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.

@dai-chen

dai-chen commented Dec 29, 2022 •

Copy link
Copy Markdown
Collaborator

@GumpacG Thanks for working on this PoC! A high level question is: can/should we implement this in some way which can support standard PartiQL/SQL++ as well?

As you many know, nested function is legacy stuff from NLPChina codebase. PartiQL/SQL++ has more standard and clear definition in their spec. So I assume the latter is our long term goal for better user adoption and better interaction with other systems.

Here is my random thoughts on how to support PartiQL and then we can discuss if we can do the same for nested function. Take queries in your WHERE Support section for example. They will be as similar form as below by following https://partiql.org/tutorial.html#unnesting-a-nested-collection:

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

First, AST will look like:

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

After analyzed/planned: (Q for QualifedName after analyzed. New Unnest operator is a special version of Join which represents correlation between index and its nested field):

Project(Q(e.name, STRING), Q(p.name, STRING))
- Filter(Like(Q(p.name, STRING))
 - Unnest(Q(e.projects, ARRAY), p)
  - Relation(Table(employees), e)

After optimized with Filter operator pushed down: (During execution, Unnest operator flat each row itself (tupleValue) by Cartesian Product e.projects (array value))

Project(Q(e.name, STRING), Q(p.name, STRING))
- Filter(Like(Q(p.name, STRING)) -- Need to filter again because doc with any nested value match will return
 - Unnest(Q(e.projects, ARRAY), p) -- OpenSearch does not flatten on inner hits
  - OpenSearchIndexScan(employees,
   dsl='
   "query": {
    "nested": {
      "path": "projects",
      "query": {
        "bool": {
          "must": [
            { "wildcard": { "projects.name": "%security" }} 
          ]
        }
      }
    }
   }',
   output={
    e.name: stringValue(name),
    e.projects: arrayValue(projects)
   }
  )

If some solution like above makes sense, the question is: can we treat nested function just difference in language grammar?

SELECT e.name, NESTED(projects.name)
FROM employees e,
WHERE NESTED(projects.name) LIKE '%security%'

Otherwise, I'm afraid that:

  1. Our engine will have totally different logic for both
  2. nested function can only work with OpenSearch because of missing clear abstraction for in-memory implementation


nestedField
: qualifiedName
| stringLiteral (DOT stringLiteral)*

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.

Although legacy supports this, I think we may consider deprecate it.

If so, we just need a nestedFunctionName rule under scalarFunctionName?

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.

@dai-chen If we go in this direction we would have to merge to 3.x since this will be a breaking change. This also means that legacy will have to be deprecated in 3.x instead of 2.x.
Another option would be to support string arguments in 2.x in order to deprecate in 2.x. Then we can push a change for 3.x that will change the behaviour.

What do you think?

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.

Sure. Are we doing the same in relevancy search function? I recall we have similar issue discussed last time. If we go this direction for relevancy function, probably we can do this breaking change in 3.x together?

@GumpacG

GumpacG commented Jan 3, 2023

Copy link
Copy Markdown
Collaborator Author

@dai-chen thanks for your comments. It makes sense to add PartiQL support however, it may be out of the scope of legacy deprecation. I think it can be an enhancement for after legacy deprecation. I created an issue to track this. #1218

Please let me know if you have any thoughts.

@dai-chen dai-chen added feature RFC Request For Comments labels Jan 9, 2023
@dai-chen

Copy link
Copy Markdown
Collaborator

@dai-chen thanks for your comments. It makes sense to add PartiQL support however, it may be out of the scope of legacy deprecation. I think it can be an enhancement for after legacy deprecation. I created an issue to track this. #1218

Please let me know if you have any thoughts.

@GumpacG Sure. I was thinking it would be great if we can have single code path after logical plan. I also don't want to make it complicated at this point, so I'm good if the code changes are not too much and easy to refactor when introducing PartQL support in V2 in future.

Btw, here are 2 sample queries previously we have limitation. Could you confirm if any chance to support in current approach in V2?

  1. Deep nested field: SELECT * FROM transaction WHERE nested(segments.userData.userZip) = '1234'
  2. Nested field in aggregation: SELECT avg(segments.segmentTime) FROM transactions

Thanks!

@GumpacG

GumpacG commented Jan 10, 2023

Copy link
Copy Markdown
Collaborator Author

We are still pretty early on in the implementation of the nested function in SELECT and do not have those limitations implemented yet but we have it in our tasks to support these queries.

Comment on lines +55 to +57
public boolean isNested() {
return this.toString().contains(".");
}

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.

I'm wondering, rather than check in this tricky way as what legacy does, should we add nested data type? Because in V2 engine, we have strict semantic check mechanism and can define function signature, ex. nested(nestDataType).

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.

We have added stricter parser grammar for the nested function. We could extend the Field class for nested types, or add some functionality through optional arguments in a new Field constructor. Are either of these options what you had in mind?

Comment on lines +294 to +296
public T visitNestedFunction(NestedFunction node, C context) {
return visitChildren(node, context);
}

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.

So nested function is special node just like highlight function. Any chance to make it just a regular function registered to function repository? How can we move this to opensearch module? As discussed, all OpenSearch specific functions including relevancy search and highlight should be moved out of core soon.

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.

Has been updated as a regular function. I am not sure which approach will be needed for moving necessary functions to the opensearch module.

@GumpacG
GumpacG changed the base branch from 2.x to main February 7, 2023 18:13
@forestmvey

forestmvey commented Feb 7, 2023 •

Copy link
Copy Markdown
Collaborator

We have added some logic for a naive implementation of nested in a GROUP BY clause. Revisions will be needed for nested aggregation to work alongside composite-aggregation. This should demonstrate the basic query sequence which we can accomplish the push down operation for non-aggregation nested queries and nested aggregation queries.

Supported aggregation query: SELECT count(*) FROM nested_objects GROUP BY nested(message.info);

sequenceDiagram
    participant SQLService
    participant ParserBaseRoot
    participant AstExpressionBuilder

    participant QueryService
    participant Analyzer
    participant Unnested
    participant ExpressionAnalyzer
    participant Planner
    participant DefaultImplementor
    participant AggregationQueryBuilder

SQLService->>ParserBaseRoot:visitRoot
  ParserBaseRoot->>AstExpressionBuilder:visitNestedFunction
  AstExpressionBuilder-->>ParserBaseRoot:Function
ParserBaseRoot-->>SQLService:UnresolvedPlan

SQLService->>QueryService:analyze
  QueryService->>Analyzer:visitProject
    Analyzer->>Unnested:accept
      Unnested->>ExpressionAnalyzer:visitFunction
        ExpressionAnalyzer-->>Unnested:Function
      Unnested-->>Analyzer:LogicalNested
    Analyzer-->>QueryService:UnresolvedPlan
  QueryService->>Planner:plan
    Planner->>DefaultImplementor:visitProject
      DefaultImplementor->>AggregationQueryBuilder:buildAggregationBuilder
        AggregationQueryBuilder-->>DefaultImplementor:NestedAggregationBuilder:MetricParser
      DefaultImplementor->>OpenSearchRequestBuilder:pushDownAggregation
    DefaultImplementor-->>Planner:PhysicalPlan
  Planner-->>QueryService:PhysicalPlan
QueryService-->>SQLService:PhysicalPlan
Loading

@forestmvey

Copy link
Copy Markdown
Collaborator

@GumpacG Thanks for working on this PoC! A high level question is: can/should we implement this in some way which can support standard PartiQL/SQL++ as well?

As you many know, nested function is legacy stuff from NLPChina codebase. PartiQL/SQL++ has more standard and clear definition in their spec. So I assume the latter is our long term goal for better user adoption and better interaction with other systems.

Here is my random thoughts on how to support PartiQL and then we can discuss if we can do the same for nested function. Take queries in your WHERE Support section for example. They will be as similar form as below by following https://partiql.org/tutorial.html#unnesting-a-nested-collection:

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

First, AST will look like:

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

After analyzed/planned: (Q for QualifedName after analyzed. New Unnest operator is a special version of Join which represents correlation between index and its nested field):

Project(Q(e.name, STRING), Q(p.name, STRING))
- Filter(Like(Q(p.name, STRING))
 - Unnest(Q(e.projects, ARRAY), p)
  - Relation(Table(employees), e)

After optimized with Filter operator pushed down: (During execution, Unnest operator flat each row itself (tupleValue) by Cartesian Product e.projects (array value))

Project(Q(e.name, STRING), Q(p.name, STRING))
- Filter(Like(Q(p.name, STRING)) -- Need to filter again because doc with any nested value match will return
 - Unnest(Q(e.projects, ARRAY), p) -- OpenSearch does not flatten on inner hits
  - OpenSearchIndexScan(employees,
   dsl='
   "query": {
    "nested": {
      "path": "projects",
      "query": {
        "bool": {
          "must": [
            { "wildcard": { "projects.name": "%security" }} 
          ]
        }
      }
    }
   }',
   output={
    e.name: stringValue(name),
    e.projects: arrayValue(projects)
   }
  )

If some solution like above makes sense, the question is: can we treat nested function just difference in language grammar?

SELECT e.name, NESTED(projects.name)
FROM employees e,
WHERE NESTED(projects.name) LIKE '%security%'

Otherwise, I'm afraid that:

  1. Our engine will have totally different logic for both
  2. nested function can only work with OpenSearch because of missing clear abstraction for in-memory implementation

Thanks for this in-depth comment for an implementation that can work with PartiQL. We have updated the code with this implementation in mind. Further down the road we should be able to share this implementation with PartiQL. Please let us know what you think of the new implementation and if it was more what you had in mind.

@codecov-commenter

codecov-commenter commented Feb 7, 2023 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 32.07547% with 144 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.26%. Comparing base (d608412) to head (da8a674).
⚠️ Report is 1080 commits behind head on main.

Files with missing lines Patch % Lines
...ch/sql/opensearch/response/OpenSearchResponse.java 4.08% 47 Missing ⚠️
...l/opensearch/request/OpenSearchRequestBuilder.java 2.17% 45 Missing ⚠️
...ensearch/response/agg/NestedAggregationParser.java 17.64% 14 Missing ⚠️
.../opensearch/sql/planner/logical/LogicalNested.java 0.00% 5 Missing ⚠️
...pensearch/sql/planner/physical/UnnestOperator.java 0.00% 5 Missing ⚠️
...java/org/opensearch/sql/sql/parser/AstBuilder.java 28.57% 4 Missing and 1 partial ⚠️
...ain/java/org/opensearch/sql/analysis/Analyzer.java 0.00% 3 Missing ⚠️
...opensearch/sql/expression/ReferenceExpression.java 0.00% 2 Missing and 1 partial ⚠️
...pensearch/sql/sql/parser/AstExpressionBuilder.java 0.00% 3 Missing ⚠️
.../opensearch/sql/sql/parser/AstUnnestedBuilder.java 50.00% 2 Missing and 1 partial ⚠️
... and 10 more

❌ Your project status has failed because the head coverage (96.26%) is below the target coverage (99.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #1210      +/-   ##
============================================
- Coverage     98.36%   96.26%   -2.11%     
- Complexity     3643     3644       +1     
============================================
  Files           343      348       +5     
  Lines          9017     9227     +210     
  Branches        585      605      +20     
============================================
+ Hits           8870     8882      +12     
- Misses          142      334     +192     
- Partials          5       11       +6     
Flag Coverage Δ
sql-engine 96.26% <32.07%> (-2.11%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dai-chen

dai-chen commented Feb 7, 2023

Copy link
Copy Markdown
Collaborator

@forestmvey Thanks for the update! Will take another look. Meanwhile I dived into the relation between PartiQL and SQL Lateral Join. Will share my thoughts for your reference shortly.

@MaxKsyunz

Copy link
Copy Markdown
Collaborator

@forestmvey Thanks for the update! Will take another look. Meanwhile I dived into the relation between PartiQL and SQL Lateral Join. Will share my thoughts for your reference shortly.

#1104 (comment)

@dai-chen

dai-chen commented Feb 9, 2023

Copy link
Copy Markdown
Collaborator

@forestmvey @MaxKsyunz I shared my recent finding for how to better support PartiQL in V2 engine here for your future reference: #1104 (comment).

According to my investigation, considering PartiQL unnest grammar as a special case of ANSI SQL Lateral Join seems a good solution. However, one of the blocker in v2 engine is currently we only support symbol resolving from a single table in Analyzer. In the short term, I think we're good to migrate nested function in v2 first in this PR. We can discuss further later. Thanks!

@GumpacG

GumpacG commented Feb 9, 2023

Copy link
Copy Markdown
Collaborator Author

@dai-chen as discussed regarding arrays of objects, we want to follow PartiQL behaviour. However, it is still unclear if we should flatten or not. With the examples below, would you be able let us know which direction we should go?

Legacy Behaviour

Legacy behaviour for the query SELECT nested(message.info) FROM nested_simple which flattens and separates values of arrays into different rows (more details in #1305) has the output:

"total": 6,
    "datarows": [
        [
            "a"
        ],
        [
            "b"
        ],
        [
            "c"
        ],
        [
            "c"
        ],
        [
            "a"
        ],
        [
            "zz"
        ]
    ],

With data (message is of type nested):

{"index":{"_id":"1"}}
{"message":{"info":"a","author":"e","dayOfWeek":1},"comment":{"data":"ab","likes":3},"myNum":1,"someField":"b"}
{"index":{"_id":"2"}}
{"message":{"info":"b","author":"f","dayOfWeek":2},"comment":{"data":"aa","likes":2},"myNum":2,"someField":"a"}
{"index":{"_id":"3"}}
{"message":{"info":"c","author":"g","dayOfWeek":1},"comment":{"data":"aa","likes":3},"myNum":3,"someField":"a"}
{"index":{"_id":"4"}}
{"message":[{"info":"c","author":"h","dayOfWeek":4},{"info":"a","author":"i","dayOfWeek":5}],"comment":{"data":"ab","likes":1},"myNum":4,"someField":"b"}
{"index":{"_id":"5"}}
{"message": [{"info":"zz","author":"zz","dayOfWeek":6}],"comment":{"data":["aa","bb"],"likes":10},"myNum":[3,4],"someField":"a"}

PartiQL behaviour

Test data:

{ 
    'test': { 
        'message': <<
            { 
                'info': 'a'
            },
            { 
                'info': 'b'
            },
            { 
                'info': 'c'
            },
            [
                { 
                    'info': 'c'
                },
                {
                    'info': 'a'
                }
            ],
            [
                { 
                    'info': 'zz'
                }
            ]
        >>
    } 
}

Query: SELECT message.info FROM test.message as message;
Output:

<<
  {
    'info': 'a'
  },
  {
    'info': 'b'
  },
  {
    'info': 'c'
  },
  {},
  {}
>>

Query: SELECT message.* FROM test.message as message;
Output:

<<
  {
    'info': 'a'
  },
  {
    'info': 'b'
  },
  {
    'info': 'c'
  },
  {
    '_1': [
      {
        'info': 'c'
      },
      {
        'info': 'a'
      }
    ]
  },
  {
    '_1': [
      {
        'info': 'zz'
      }
    ]
  }
>>

@dai-chen

dai-chen commented Feb 9, 2023

Copy link
Copy Markdown
Collaborator

@GumpacG Thanks for the context! I will double check.

Guian Gumpac and others added 4 commits February 14, 2023 10:36
Signed-off-by: Guian Gumpac <[email protected]>
Signed-off-by: forestmvey <[email protected]>
Signed-off-by: Guian Gumpac <[email protected]>
@dai-chen

Copy link
Copy Markdown
Collaborator

@GumpacG I think there are problems in your data and query

  1. Test data: In your table test.message, some rows are object while the others are array. I'm not sure if you're using catalog name test as table? Please compare with the test data provided by PartiQL.
  2. Test query: your query is accessing each row directly, that's why it's not flatten. Please check my test below. I think our nested function is equivalent to PartiQL comma join which indicates unnest implicitly.
$ cat Tutorial/code/q2.env
{
  'hr': {
      'employeesNest': <<
         {
          'id': 3,
          'name': 'Bob Smith',
          'title': null,
          'projects': [ { 'name': 'AWS Redshift Spectrum querying' },
                        { 'name': 'AWS Redshift security' },
                        { 'name': 'AWS Aurora security' }
                      ]
          },
          {
              'id': 4,
              'name': 'Susan Smith',
              'title': 'Dev Mgr',
              'projects': []
          },
          {
              'id': 6,
              'name': 'Jane Smith',
              'title': 'Software Eng 2',
              'projects': [ { 'name': 'AWS Redshift security' } ]
          }
      >>
    }
}

$ ./bin/partiql -e Tutorial/code/q2.env

PartiQL> SELECT p.name FROM hr.employeesNest n, n.projects p;
==='
<<
  {
    'name': 'AWS Redshift Spectrum querying'
  },
  {
    'name': 'AWS Redshift security'
  },
  {
    'name': 'AWS Aurora security'
  },
  {
    'name': 'AWS Redshift security'
  }
>>
---
OK!


PartiQL> SELECT p FROM hr.employeesNest n, n.projects p;
==='
<<
  {
    'p': {
      'name': 'AWS Redshift Spectrum querying'
    }
  },
  {
    'p': {
      'name': 'AWS Redshift security'
    }
  },
  {
    'p': {
      'name': 'AWS Aurora security'
    }
  },
  {
    'p': {
      'name': 'AWS Redshift security'
    }
  }
>>
---
OK!

@GumpacG

GumpacG commented Feb 16, 2023

Copy link
Copy Markdown
Collaborator Author

@dai-chen thanks for clarifying. I modified my PartiQL data to reflect our test data and V2 nested implementation should include flattening. Including an example here for reference. As a result #1305 should be closed as legacy behaviour is expected.

PartiQL data:

{ 
    'root': {
        'test': << 
        {
            'message': {
                'info': 'a'
            },
            'comment': {
                'numComments': 1
            }
        },
        {
            'message':  { 
                'info': 'b'
            },
            'comment': {
                'numComments': 2
            }
        },
        {
            'message':  { 
                'info': 'c'
            },
            'comment': {
                'numComments': 3
            }
        },
        {
            'message':  [
                { 
                    'info': 'c'
                },
                {
                    'info': 'a'
                }
            ],
            'comment': {
                'numComments': 4
            }
        },
        {
            'message':  [
                { 
                    'info': 'zz'
                }
            ],
            'comment': {
                'numComments': [5, 6]
            }
        }
        >> 
    }
}

PartiQL query and result:

PartiQL> SELECT message.info, comment.numComments FROM root.test as a, a.message as message, a.comment as comment;
==='
<<
  {
    'info': 'a',
    'numComments': 1
  },
  {
    'info': 'b',
    'numComments': 2
  },
  {
    'info': 'c',
    'numComments': 3
  },
  {
    'info': 'c',
    'numComments': 4
  },
  {
    'info': 'a',
    'numComments': 4
  },
  {
    'info': 'zz',
    'numComments': [
      5,
      6
    ]
  }
>>
---
OK!

@GumpacG

GumpacG commented Mar 23, 2023

Copy link
Copy Markdown
Collaborator Author

Closing this as the spike and POC are done.

@GumpacG GumpacG closed this Mar 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature RFC Request For Comments

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants