Utilizzo di NESTED TABLES con tabelle padre-figlio

Un JOIN viene utilizzato per combinare righe di due o più tabelle, in base a una colonna correlata tra di esse. In una tabella gerarchica, la tabella figlio eredita le colonne chiave primaria della relativa tabella padre. Questa operazione viene eseguita in modo implicito, senza includere le colonne padre nell'istruzione CREATE TABLE del figlio. Tutte le tabelle nella gerarchia hanno le stesse colonne chiave partizione.

È possibile utilizzare la clausola NESTED TABLES per unire le tabelle in Oracle NoSQL Database.

Panoramica delle schede NESTED

La clausola NESTED TABLES specifica le tabelle partecipanti e le separa in 3 gruppi. In primo luogo, viene specificata la tabella di destinazione da cui vengono recuperati i dati. Quindi la clausola ANCESTORS, se presente, specifica il numero di tabelle che devono essere predecessori della tabella di destinazione nella gerarchia di tabelle. Infine, la clausola DESCENDANTS, se presente, specifica il numero di tabelle che devono essere discendenti della tabella di destinazione nella gerarchia di tabelle.

Nota

Semanticamente, una clausola NESTED TABLES equivale a una serie di operazioni left-outer-join "centered" intorno alla tabella di destinazione.
Caratteristiche delle tabelle NESTED:
  • Esegue una query su più tabelle nella stessa gerarchia
  • Non è uno standard ANSI-SQL
  • Supporta il join delle tabelle di pari livello

Tabella - Tabelle nidificate rispetto a LOJ

Tabelle nidificate LOJ
Esegue una query su più tabelle nella stessa gerarchia Esegue una query su più tabelle nella stessa gerarchia
Non è uno standard ANSI-SQL Standard ANSI-SQL
Supporta l'unione delle tabelle di pari livello Non supporta join di tabelle di pari livello

Se si desidera seguire gli esempi, scaricare lo script parentchildtbls_loaddata.sql ed eseguirlo come mostrato di seguito. Questo script crea la tabella utilizzata nell'esempio e carica i dati nella tabella.

Avviare KVSTORE o KVLite e aprire SQL.shell.
 java -jar lib/kvstore.jar kvlite -secure-config disable
 java -jar lib/sql.jar -helper-hosts localhost:5000 -store kvstore
Il file parentchildtbls_loaddata.sql contiene le informazioni riportate di seguito.
### Begin Script ###
load -file parentchild.ddl
import -table ticket  -file ticket.json
import -table ticket.bagInfo  -file bagInfo.json
import -table ticket.passengerInfo  -file passengerInfo.json
import -table ticket.bagInfo.flightLegs  -file flightLegs.json
### End Script ###
Utilizzando il comando load, eseguire lo script.
load -file parentchildtbls_loaddata.sql
È possibile creare tabelle utilizzate negli esempi e caricare i dati nelle tabelle utilizzando OCI Console. Dalla console OCI, utilizzare la modalità di input DDL avanzata per creare le tabelle seguenti utilizzando le istruzioni DDL riportate di seguito.
### CREATE table ticket if not present ###
CREATE TABLE IF NOT EXISTS ticket(ticketNo LONG, 
confNo STRING, 
PRIMARY KEY(ticketNo));

### CREATE table ticket.baginfo if not present ###
CREATE TABLE IF NOT EXISTS ticket.bagInfo(id LONG,tagNum LONG,routing STRING,
lastActionCode STRING,
lastActionDesc STRING,
lastSeenStation STRING,
lastSeenTimeGmt TIMESTAMP(4),
bagArrivalDate TIMESTAMP(4), PRIMARY KEY(id));

### CREATE table ticket.bagInfo.flightLegs if not present ###
CREATE TABLE IF NOT EXISTS ticket.bagInfo.flightLegs(flightNo STRING, 
flightDate TIMESTAMP(4),
fltRouteSrc STRING,
fltRouteDest STRING,
estimatedArrival TIMESTAMP(4), 
actions JSON, PRIMARY KEY(flightNo));

### CREATE table ticket.passengerInfo if not present ###
CREATE TABLE IF NOT EXISTS ticket.passengerInfo(contactPhone STRING, 
fullName STRING,
gender STRING, PRIMARY KEY(contactPhone));

Per la procedura di creazione di una tabella con un'istruzione DDL, vedere Creazione di una tabella Singleton: modalità di input DDL avanzata.

Per caricare i dati nella tabella creata dalla console OCI, fare clic sul nome della tabella. Vengono visualizzati i dettagli della tabella. Fare clic su Carica dati. Fare clic su Seleziona file da caricare e specificare il file JSON da caricare. È possibile scaricare i file DDL e JSON per le tabelle figlio padre qui.

Esempi di utilizzo di NESTED TABLES

Diverse tabelle utilizzate negli esempi:
  • ticket
    ticketNo LONG
    confNo STRING
    PRIMARY KEY(ticketNo)
  • ticket.bagInfo
    id LONG
    tagNum LONG
    routing STRING
    lastActionCode STRING
    lastActionDesc STRING
    lastSeenStation STRING,
    lastSeenTimeGmt TIMESTAMP(4)
    bagArrivalDate TIMESTAMP(4)
    PRIMARY KEY(id)
  • ticket.bagInfo.flightLegs
    flightNo STRING
    flightDate TIMESTAMP(4)
    fltRouteSrc STRING
    fltRouteDest STRING
    estimatedArrival TIMESTAMP(4),
    actions JSON
    PRIMARY KEY(flightNo)
  • ticket.passengerInfo
    contactPhone STRING
    fullName STRING
    gender STRING
    PRIMARY KEY(contactPhone)

Esempi SQL

Esempio 1: recuperare i dettagli di tutti i passeggeri a cui è stato rilasciato un biglietto.
SELECT fullname, contactPhone, gender 
FROM NESTED TABLES 
(ticket a descendants(ticket.passengerInfo b))

Spiegazione: questo è un esempio di join in cui la tabella di destinazione ticket viene unita con la tabella figlio passengerInfo.

Output:
{"fullname":"Elane Lemons","contactPhone":"600-918-8404","gender":"F"}
{"fullname":"Adelaide Willard","contactPhone":"421-272-8082","gender":"M"}
{"fullname":"Dierdre Amador","contactPhone":"165-742-5715","gender":"M"}
{"fullname":"Doris Martin","contactPhone":"289-564-3497","gender":"F"}
{"fullname":"Adam Phillips","contactPhone":"893-324-1064","gender":"M"}
Esempio 1a: recuperare i dettagli del passeggero con il numero di biglietto 1762324912391.
SELECT fullname, contactPhone, gender 
FROM NESTED TABLES 
(ticket a descendants(ticket.passengerInfo b))
WHERE a.ticketNo=1762324912391

Spiegazione: questo è un esempio di join in cui la tabella di destinazioneticket viene unita alla relativa tabella figlio passengerInfo. È inoltre possibile limitare il set di risultati applicando una condizione di filtro al risultato del join. Si sta limitando il risultato a un determinato numero di ticket.

Output:
{"fullname":"Elane Lemons","contactPhone":"600-918-8404","gender":"F"}
Esempio 2: recuperare tutti i dettagli del bagaglio per tutti i passeggeri a cui è stato rilasciato un biglietto.
SELECT * FROM NESTED TABLES 
(ticket a descendants(ticket.bagInfo b))

Spiegazione: questo è un esempio di join in cui la tabella di destinazione ticket viene unita con la tabella figlio bagInfo.

Output:
{"a":{"ticketNo":1762344493810,"confNo":"LE6J4Z"},
"b":{"ticketNo":1762344493810,"id":79039899165297,"tagNum":17657806255240,"routing":"MIA/LAX/MEL",
"lastActionCode":"OFFLOAD","lastActionDesc":"OFFLOAD","lastSeenStation":"MEL",
"lastSeenTimeGmt":"2019-02-01T16:13:00.0000Z","bagArrivalDate":"2019-02-01T16:13:00.0000Z"}}

{"a":{"ticketNo":1762324912391,"confNo":"LN0C8R"},
"b":{"ticketNo":1762324912391,"id":79039899168383,"tagNum":1765780623244,"routing":"MXP/CDG/SLC/BZN",
"lastActionCode":"OFFLOAD","lastActionDesc":"OFFLOAD","lastSeenStation":"BZN",
"lastSeenTimeGmt":"2019-03-15T10:13:00.0000Z","bagArrivalDate":"2019-03-15T10:13:00.0000Z"}}

{"a":{"ticketNo":1762392135540,"confNo":"DN3I4Q"},
"b":{"ticketNo":1762392135540,"id":79039899156435,"tagNum":17657806224224,"routing":"GRU/ORD/SEA",
"lastActionCode":"OFFLOAD","lastActionDesc":"OFFLOAD","lastSeenStation":"SEA",
"lastSeenTimeGmt":"2019-02-15T21:21:00.0000Z","bagArrivalDate":"2019-02-15T21:21:00.0000Z"}}

{"a":{"ticketNo":1762376407826,"confNo":"ZG8Z5N"},
"b":{"ticketNo":1762376407826,"id":7903989918469,"tagNum":17657806240229,"routing":"JFK/MAD",
"lastActionCode":"OFFLOAD","lastActionDesc":"OFFLOAD","lastSeenStation":"MAD",
"lastSeenTimeGmt":"2019-03-07T13:51:00.0000Z","bagArrivalDate":"2019-03-07T13:51:00.0000Z"}}

{"a":{"ticketNo":1762355527825,"confNo":"HJ4J4P"},
"b":{"ticketNo":1762355527825,"id":79039899197492,"tagNum":17657806232501,"routing":"BZN/SEA/CDG/MXP",
"lastActionCode":"OFFLOAD","lastActionDesc":"OFFLOAD","lastSeenStation":"MXP",
"lastSeenTimeGmt":"2019-03-22T10:17:00.0000Z","bagArrivalDate":"2019-03-22T10:17:00.0000Z"}}
Esempio 2a: recupera tutti i dettagli del bag per un determinato numero di ticket.
SELECT * FROM 
NESTED TABLES (ticket a descendants(ticket.bagInfo b))
WHERE a.ticketNo=1762324912391

Spiegazione: questo è un esempio di join in cui la tabella di destinazioneticket viene unita alla relativa tabella figlio bagInfo. È inoltre possibile limitare il set di risultati applicando una condizione di filtro al risultato del join. Si sta limitando il risultato a un determinato numero di ticket.

Output:
{"a":{"ticketNo":1762324912391,"confNo":"LN0C8R"},
"b":{"ticketNo":1762324912391,"id":79039899168383,"tagNum":1765780623244,"routing":"MXP/CDG/SLC/BZN",
"lastActionCode":"OFFLOAD","lastActionDesc":"OFFLOAD","lastSeenStation":"BZN",
"lastSeenTimeGmt":"2019-03-15T10:13:00.0000Z","bagArrivalDate":"2019-03-15T10:13:00.0000Z"}}

Nota

Se si sposta la limitazione del predicato non join nella clausola ON, il set di risultati include tutte le righe che soddisfano la condizione della clausola ON. Le righe della tabella esterna destra che non soddisfano la condizione ON vengono popolate con valori NULL come mostrato di seguito.
SELECT * FROM 
NESTED TABLES(ticket a descendants(ticket.bagInfo b 
ON a.ticketNo=b.ticketNo
AND a.ticketNo=1762324912391))
Output:
{"a":{"ticketNo":1762355527825,"confNo":"HJ4J4P"},"b":null}
{"a":{"ticketNo":1762344493810,"confNo":"LE6J4Z"},"b":null}
{"a":{"ticketNo":1762324912391,"confNo":"LN0C8R"}, "b":{"ticketNo":1762324912391,"id":79039899168383,"tagNum":1765780623244,"routing":"MXP/CDG/SLC/BZN",
"lastActionCode":"OFFLOAD","lastActionDesc":"OFFLOAD","lastSeenStation":"BZN", 
"lastSeenTimeGmt":"2019-03-15T10:13:00.0000Z","bagArrivalDate":"2019-03-15T10:13:00.0000Z"}}
{"a":{"ticketNo":1762392135540,"confNo":"DN3I4Q"},"b":null}
{"a":{"ticketNo":1762376407826,"confNo":"ZG8Z5N"},"b":null}
Esempio 3: recuperare tutti i dettagli delle tappe del volo per tutti i passeggeri.
SELECT * FROM 
NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))

Spiegazione: questo è un esempio di join in cui la tabella di destinazione ticket viene unita con il relativo discendente bagInfo. Una tabella discendente può essere qualsiasi livello gerarchicamente sotto una tabella (ad esempio fightLegs è il figlio di bagInfo, ovvero il figlio di ticket, quindi flightLegs è un discendente di ticket). Verranno recuperate tutte le righe della tabella ticket. Se una riga qualsiasi della tabella ticket non contiene una riga corrispondente nella tabella flightLegs, verranno visualizzati valori NULL per le righe della tabella flightLegs.

Output:
{"a":{"ticketNo":1762344493810,"confNo":"LE6J4Z"},
"b":{"ticketNo":1762344493810,"id":79039899165297,"flightNo":"BM604","flightDate":"2019-02-01T06:00:00.0000Z",
"fltRouteSrc":"MIA","fltRouteDest":"LAX","estimatedArrival":"2019-02-01T11:00:00.0000Z",
"actions":[{"actionAt":"MIA","actionCode":"ONLOAD to LAX","actionTime":"2019-02-01T06:13:00Z"},
{"actionAt":"MIA","actionCode":"BagTag Scan at MIA","actionTime":"2019-02-01T05:47:00Z"},
{"actionAt":"MIA","actionCode":"Checkin at MIA","actionTime":"2019-02-01T04:38:00Z"}]}}

{"a":{"ticketNo":1762344493810,"confNo":"LE6J4Z"},
"b":{"ticketNo":1762344493810,"id":79039899165297,"flightNo":"BM667","flightDate":"2019-02-01T06:13:00.0000Z",
"fltRouteSrc":"LAX","fltRouteDest":"MEL","estimatedArrival":"2019-02-01T16:15:00.0000Z",
"actions":[{"actionAt":"MEL","actionCode":"Offload to Carousel at MEL","actionTime":"2019-02-01T16:15:00Z"},
{"actionAt":"LAX","actionCode":"ONLOAD to MEL","actionTime":"2019-02-01T15:35:00Z"},
{"actionAt":"LAX","actionCode":"OFFLOAD from LAX","actionTime":"2019-02-01T15:18:00Z"}]}}

{"a":{"ticketNo":1762324912391,"confNo":"LN0C8R"},
"b":{"ticketNo":1762324912391,"id":79039899168383,"flightNo":"BM170","flightDate":"2019-03-15T08:13:00.0000Z",
"fltRouteSrc":"SLC","fltRouteDest":"BZN","estimatedArrival":"2019-03-15T10:14:00.0000Z",
"actions":[{"actionAt":"BZN","actionCode":"Offload to Carousel at BZN","actionTime":"2019-03-15T10:13:00Z"},
{"actionAt":"SLC","actionCode":"ONLOAD to BZN","actionTime":"2019-03-15T10:06:00Z"},
{"actionAt":"SLC","actionCode":"OFFLOAD from SLC","actionTime":"2019-03-15T09:59:00Z"}]}}

{"a":{"ticketNo":1762324912391,"confNo":"LN0C8R"},
"b":{"ticketNo":1762324912391,"id":79039899168383,"flightNo":"BM490","flightDate":"2019-03-15T08:13:00.0000Z",
"fltRouteSrc":"CDG","fltRouteDest":"SLC","estimatedArrival":"2019-03-15T10:14:00.0000Z",
"actions":[{"actionAt":"CDG","actionCode":"ONLOAD to SLC","actionTime":"2019-03-15T09:42:00Z"},
{"actionAt":"CDG","actionCode":"BagTag Scan at CDG","actionTime":"2019-03-15T09:17:00Z"},
{"actionAt":"CDG","actionCode":"OFFLOAD from CDG","actionTime":"2019-03-15T09:19:00Z"}]}}

{"a":{"ticketNo":1762324912391,"confNo":"LN0C8R"},
"b":{"ticketNo":1762324912391,"id":79039899168383,"flightNo":"BM936","flightDate":"2019-03-15T08:00:00.0000Z",
"fltRouteSrc":"MXP","fltRouteDest":"CDG","estimatedArrival":"2019-03-15T09:00:00.0000Z",
"actions":[{"actionAt":"MXP","actionCode":"ONLOAD to CDG","actionTime":"2019-03-15T08:13:00Z"},
{"actionAt":"MXP","actionCode":"BagTag Scan at MXP","actionTime":"2019-03-15T07:48:00Z"},
{"actionAt":"MXP","actionCode":"Checkin at MXP","actionTime":"2019-03-15T07:38:00Z"}]}}

{"a":{"ticketNo":1762392135540,"confNo":"DN3I4Q"},
"b":{"ticketNo":1762392135540,"id":79039899156435,"flightNo":"BM79","flightDate":"2019-02-15T01:00:00.0000Z",
"fltRouteSrc":"GRU","fltRouteDest":"ORD","estimatedArrival":"2019-02-15T11:00:00.0000Z",
"actions":[{"actionAt":"GRU","actionCode":"ONLOAD to ORD","actionTime":"2019-02-15T01:21:00Z"},
{"actionAt":"GRU","actionCode":"BagTag Scan at GRU","actionTime":"2019-02-15T00:55:00Z"},
{"actionAt":"GRU","actionCode":"Checkin at GRU","actionTime":"2019-02-14T23:49:00Z"}]}}

{"a":{"ticketNo":1762392135540,"confNo":"DN3I4Q"}
,"b":{"ticketNo":1762392135540,"id":79039899156435,"flightNo":"BM907","flightDate":"2019-02-15T01:21:00.0000Z",
"fltRouteSrc":"ORD","fltRouteDest":"SEA","estimatedArrival":"2019-02-15T21:22:00.0000Z",
"actions":[{"actionAt":"SEA","actionCode":"Offload to Carousel at SEA","actionTime":"2019-02-15T21:16:00Z"},
{"actionAt":"ORD","actionCode":"ONLOAD to SEA","actionTime":"2019-02-15T20:52:00Z"},
{"actionAt":"ORD","actionCode":"OFFLOAD from ORD","actionTime":"2019-02-15T20:44:00Z"}]}}

{"a":{"ticketNo":1762376407826,"confNo":"ZG8Z5N"},
"b":{"ticketNo":1762376407826,"id":7903989918469,"flightNo":"BM495","flightDate":"2019-03-07T07:00:00.0000Z",
"fltRouteSrc":"JFK","fltRouteDest":"MAD","estimatedArrival":"2019-03-07T14:00:00.0000Z",
"actions":[{"actionAt":"MAD","actionCode":"Offload to Carousel at MAD","actionTime":"2019-03-07T13:54:00Z"},
{"actionAt":"JFK","actionCode":"ONLOAD to MAD","actionTime":"2019-03-07T07:00:00Z"},
{"actionAt":"JFK","actionCode":"BagTag Scan at JFK","actionTime":"2019-03-07T06:53:00Z"},
{"actionAt":"JFK","actionCode":"Checkin at JFK","actionTime":"2019-03-07T05:03:00Z"}]}}

{"a":{"ticketNo":1762355527825,"confNo":"HJ4J4P"},
"b":{"ticketNo":1762355527825,"id":79039899197492,"flightNo":"BM386","flightDate":"2019-03-22T07:23:00.0000Z",
"fltRouteSrc":"CDG","fltRouteDest":"MXP","estimatedArrival":"2019-03-22T10:24:00.0000Z",
"actions":[{"actionAt":"MXP","actionCode":"Offload to Carousel at MXP","actionTime":"2019-03-22T10:15:00Z"},
{"actionAt":"CDG","actionCode":"ONLOAD to MXP","actionTime":"2019-03-22T10:09:00Z"},
{"actionAt":"CDG","actionCode":"OFFLOAD from CDG","actionTime":"2019-03-22T10:01:00Z"}]}}

{"a":{"ticketNo":1762355527825,"confNo":"HJ4J4P"},
"b":{"ticketNo":1762355527825,"id":79039899197492,"flightNo":"BM578","flightDate":"2019-03-22T07:23:00.0000Z",
"fltRouteSrc":"SEA","fltRouteDest":"CDG","estimatedArrival":"2019-03-21T23:24:00.0000Z",
"actions":[{"actionAt":"SEA","actionCode":"ONLOAD to CDG","actionTime":"2019-03-22T11:26:00Z"},
{"actionAt":"SEA","actionCode":"BagTag Scan at SEA","actionTime":"2019-03-22T10:57:00Z"},
{"actionAt":"SEA","actionCode":"OFFLOAD from SEA","actionTime":"2019-03-22T11:07:00Z"}]}}

{"a":{"ticketNo":1762355527825,"confNo":"HJ4J4P"},
"b":{"ticketNo":1762355527825,"id":79039899197492,"flightNo":"BM704","flightDate":"2019-03-22T07:00:00.0000Z",
"fltRouteSrc":"BZN","fltRouteDest":"SEA","estimatedArrival":"2019-03-22T09:00:00.0000Z",
"actions":[{"actionAt":"BZN","actionCode":"ONLOAD to SEA","actionTime":"2019-03-22T07:23:00Z"},
{"actionAt":"BZN","actionCode":"BagTag Scan at BZN","actionTime":"2019-03-22T06:58:00Z"},
{"actionAt":"BZN","actionCode":"Checkin at BZN","actionTime":"2019-03-22T05:20:00Z"}]}}
Esempio 3a: recuperare tutti i dettagli della tappa del volo per un determinato numero di biglietto.
SELECT * FROM 
NESTED TABLES (ticket.bagInfo.flightLegs b ancestors(ticket a))
WHERE a.ticketNo=1762344493810

Spiegazione: questo è un esempio di join in cui la tabella di destinazioneticket viene unita con il relativo discendente bagInfo. È inoltre possibile limitare il set di risultati applicando una condizione di filtro al risultato del join. Si sta limitando il risultato a un determinato numero di ticket.

Il risultato ha due righe, il che implica che ci sono due gambe di volo per questo numero di biglietto.

Output:
"a":{"ticketNo":1762344493810,"confNo":"LE6J4Z"},
"b":{"ticketNo":1762344493810,"id":79039899165297,"flightNo":"BM604",
"flightDate":"2019-02-01T06:00:00.0000Z","fltRouteSrc":"MIA","fltRouteDest":"LAX",
"estimatedArrival":"2019-02-01T11:00:00.0000Z",
"actions":[{"actionAt":"MIA","actionCode":"ONLOAD to LAX","actionTime":"2019-02-01T06:13:00Z"},
{"actionAt":"MIA","actionCode":"BagTag Scan at MIA","actionTime":"2019-02-01T05:47:00Z"},
{"actionAt":"MIA","actionCode":"Checkin at MIA","actionTime":"2019-02-01T04:38:00Z"}]}}

{"a":{"ticketNo":1762344493810,"confNo":"LE6J4Z"},
"b":{"ticketNo":1762344493810,"id":79039899165297,"flightNo":"BM667",
"flightDate":"2019-02-01T06:13:00.0000Z","fltRouteSrc":"LAX","fltRouteDest":"MEL",
"estimatedArrival":"2019-02-01T16:15:00.0000Z",
"actions":[{"actionAt":"MEL","actionCode":"Offload to Carousel at MEL","actionTime":"2019-02-01T16:15:00Z"},
{"actionAt":"LAX","actionCode":"ONLOAD to MEL","actionTime":"2019-02-01T15:35:00Z"},
{"actionAt":"LAX","actionCode":"OFFLOAD from LAX","actionTime":"2019-02-01T15:18:00Z"}]}}
Esempio 4: recuperare l'ID del sacchetto e il numero di luppoli per tutti i bagagli di tutti i passeggeri.
SELECT b.id,count(*) AS NUMBER_HOPS 
FROM NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))
GROUP BY b.id

Spiegazione: è possibile raggruppare i dati in base all'ID del sacchetto (utilizzando GROUP BY) e ottenere il conteggio delle gambe del volo (utilizzando count() ) per ogni sacchetto.

Output:
{"id":79039899168383,"NUMBER_HOPS":3}
{"id":79039899156435,"NUMBER_HOPS":2}
{"id":7903989918469,"NUMBER_HOPS":1}
{"id":79039899165297,"NUMBER_HOPS":2}
{"id":79039899197492,"NUMBER_HOPS":3}
Esempio 4a: trovare il numero di luppoli per tutte le borse di un passeggero specifico.
SELECT b.id,count(*) AS NUMBER_HOPS FROM 
NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))
WHERE a.ticketNo=1762355527825 
GROUP BY b.id

Spiegazione: raggruppare i dati in base all'ID borsa (utilizzando GROUP BY) e ottenere il conteggio delle tappe di volo (utilizzando count()) per ogni borsa. Inoltre, si filtrano i risultati per un determinato numero di ticket.

Output:
{"id":79039899197492,"NUMBER_HOPS":3}
Esempio 5: recuperare l'ID del sacchetto e i dettagli di instradamento di tutti i sacchetti arrivati dopo il 2019.
SELECT b.id, routing FROM 
NESTED TABLES(ticket a descendants(ticket.bagInfo b))
WHERE CAST (b.bagArrivalDate AS Timestamp(0))>= 
CAST ("2019-01-01T00:00:00" AS Timestamp(0))

Spiegazione: questo è un esempio di join in cui la tabella di destinazioneticket viene unita alla tabella figlio bagInfo. La condizione di filtro viene applicata in bagArrivalDate. La funzione CAST viene utilizzata per convertire la stringa in indicatore orario e quindi i valori vengono confrontati.

Output:
{"id":79039899197492,"routing":"BZN/SEA/CDG/MXP"}
{"id":79039899165297,"routing":"MIA/LAX/MEL"}
{"id":79039899168383,"routing":"MXP/CDG/SLC/BZN"}
{"id":79039899156435,"routing":"GRU/ORD/SEA"}
{"id":7903989918469,"routing":"JFK/MAD"}

Esempi di API di query

Per eseguire la query, utilizzare l'API NoSQLHandle.query().

Scarica il codice completo TableJoins.java dagli esempi qui.
   /* fetch rows based on joins*/
private static void fetchRows(NoSQLHandle handle,String sql_stmt) throws Exception {
   try (
      QueryRequest queryRequest = new QueryRequest().setStatement(sql_stmt);
      QueryIterableResult results = handle.queryIterable(queryRequest)) {
         System.out.println("Query results:");
         for (MapValue res : results) {
            System.out.println("\t" + res);
         }
      }
}

System.out.println("Fetching data using NESTED TABLES:");
String sql_stmt_nt ="SELECT * FROM NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))";
/* fetching rows using nested tables*/
fetchRows(handle,sql_stmt_nt);

Per eseguire la query, utilizzare il metodo borneo.NoSQLHandle.query().

Scarica il codice completo TableJoins.py dagli esempi qui.
# Fetch data from the table based on joins
def fetch_data(handle,sqlstmt):
   request = QueryRequest().set_statement(sqlstmt)
   print('Query results for: ' + sqlstmt)
   result = handle.query(request)
   for r in result.get_results():
      print('\t' + str(r))

sql_stmt_nt='SELECT * FROM NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))'
print('Fetching data using NESTED TABLES ')
fetch_data(handle,sql_stmt_nt)

Per eseguire una query, utilizzare la funzione Client.Query.

Scarica il codice completo TableJoins.go dagli esempi qui.

func fetchData(client *nosqldb.Client, err error, 
               tableName string, querystmt string)(){
   prepReq := &nosqldb.PrepareRequest{ Statement: querystmt,}

   prepRes, err := client.Prepare(prepReq)
   if err != nil {
      fmt.Printf("Prepare failed: %v\n", err)
      return
   }

   queryReq := &nosqldb.QueryRequest{
		 PreparedStatement: &prepRes.PreparedStatement,}
   var results []*types.MapValue

   for {
      queryRes, err := client.Query(queryReq)
      if err != nil {
         fmt.Printf("Query failed: %v\n", err)
	  return
      }
      res, err := queryRes.GetResults()

      if err != nil {
         fmt.Printf("GetResults() failed: %v\n", err)
  	return
      }

      results = append(results, res...)
      if queryReq.IsDone() {
         break
      }
   }
   for i, r := range results {
      fmt.Printf("\t%d: %s\n", i+1, 
                  jsonutil.AsJSON(r.Map()))
   }
}

querystmt_nt:= "SELECT * FROM NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b)"
fmt.Println("Fetching data using NESTED TABLES")
fetchData(client, err,querystmt_nt)

Per eseguire una query, utilizzare il metodo query.

JavaScript: scarica il codice completo TableJoins.js dagli esempi qui.
//fetches data from the table
async function fetchData(handle,querystmt) {
   const opt = {};
   try {
      do {
         const result = await handle.query(querystmt, opt);
         for(let row of result.rows) {
            console.log('  %O', row);
         }
         opt.continuationKey = result.continuationKey;
      } while(opt.continuationKey);
   } catch(error) {
      console.error('  Error: ' + error.message);
   }
}

const stmt_nt = 'SELECT * FROM NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))';
console.log("Fetching data using NESTED TABLES");
await fetchData(handle,stmt_nt);
TypeScript: scarica il codice completo TableJoins.ts dagli esempi qui.
interface StreamInt {
   acct_Id: Integer;
   profile_name: String;
   account_expiry: TIMESTAMP;
   acct_data: JSON;
}
/* fetches data from the table */
async function fetchData(handle: NoSQLClient,querystmt: string) {
   const opt = {};
   try {
      do {
         const result = await handle.query<StreamInt>(querystmt, opt);
         for(let row of result.rows) {
            console.log('  %O', row);
         }
         opt.continuationKey = result.continuationKey;
      } while(opt.continuationKey);
   } catch(error) {
      console.error('  Error: ' + error.message);
   }
}

const stmt_nt = 'SELECT * FROM NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))';
console.log("Fetching data using NESTED TABLES");
await fetchData(handle,stmt_nt);

Per eseguire una query, è possibile chiamare il metodo QueryAsync o chiamare il metodo GetQueryAsyncEnumerable e ripetere l'iterazione sull'enumerabile asincrono risultante.

Scarica il codice completo TableJoins.cs dagli esempi qui.
private static async Task fetchData(NoSQLClient client,String querystmt){
   var queryEnumerable = client.GetQueryAsyncEnumerable(querystmt);
   await DoQuery(queryEnumerable);
}

private static async Task DoQuery(IAsyncEnumerable<QueryResult<RecordValue>> queryEnumerable){
   Console.WriteLine("  Query results:");
   await foreach (var result in queryEnumerable) {
      foreach (var row in result.Row
      {
         Console.WriteLine();
         Console.WriteLine(row.ToJsonString());
      }
   }
}

private const string stmt_nt ="SELECT * FROM NESTED TABLES (ticket a descendants(ticket.bagInfo.flightLegs b))";
Console.WriteLine("Fetching data using NESTED TABLES: ");
await fetchData(client,stmt_nt);