Query With Arrays and Maps
ksqlDB enables using complex types, like arrays and maps, in your queries.
You use familiar syntax, like myarray ARRAY<type>
and myarray[0]
to
declare and access these types.
The following example shows how to create a ksqlDB table from an
Apache Kafka® topic that has array and map fields. Also, it shows how to
run queries to access the array and map data. It assumes a Kafka topic,
named users
. To see this example in action, create the users
topic
by following the procedure in
Write Streaming Queries Against Apache Kafka® Using ksqlDB.
Important
When you start the ksql-datagen process for the users
topic, set the
quickstart
parameter to users_
, to add the array and map fields to
the user
records. Be sure to append the _
character. The array and
map fields are named interests
and contactinfo
and have type
ARRAY
Create a Table With Array and Map Fields¶
Run the following query to create a ksqlDB table on the users
topic. The
array and map fields are defined in the interests ARRAY<STRING>
and
contactinfo MAP<STRING,STRING>
declarations.
1 2 3 4 5 6 7 8 9 10 |
|
Your output should resemble:
1 2 3 4 |
|
The table is ready for you to run queries against it.
Query a Table That Has Array and Map Fields¶
With the users
table created, you can query the array field and the
map field. Run the following CREATE TABLE AS SELECT statement to create
a persistent query that has the first item in the user's interests
array and the user's city and zip code from the contactinfo
map.
1 2 3 4 5 6 7 8 9 |
|
Your output should resemble:
1 2 3 4 |
|
Run the following SELECT query to view the table:
1 2 3 |
|
Your output should resemble:
1 2 3 4 5 6 7 8 9 10 |
|
Press Ctrl+C to terminate the query.
You can access array elements by using positive or negative index values. For example, to get the user's last interest run the following SELECT statement:
1 2 3 4 5 6 |
|
Your output should resemble:
1 2 3 4 5 6 7 8 9 10 |
|
Press Ctrl+C to terminate the query.
Next Steps¶
Page last revised on: 2020-04-29