hi all, how to parse json in flink if json data li...
# troubleshooting
a
hi all, how to parse json in flink if json data like this:
{"elements": [{"id": "d9956ac2-6e3d-465e-8bf2-49dfa8b7b4cf", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:10.834276685", "complete_time": "2023-01-10T16:45:13.47560873"}, {"id": "86dadeca-10e8-4b36-a059-0f5659b0219f", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:14.388085978", "complete_time": "2023-01-10T16:45:16.745961631"}, {"id": "b1b4e898-af61-4dfa-9da4-cefc61f92937", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:17.635952434", "complete_time": "2023-01-10T16:45:19.833378191"}, {"id": "b993b90d-6821-4738-a5f8-477a4d4b2efb", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:20.750092211", "complete_time": "2023-01-10T16:45:38.030293061"}, {"id": "a76730c3-848b-4dc5-a507-a4fdf29fb2f5", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:39.820873143", "complete_time": "2023-01-10T16:45:40.947897919"}, {"id": "e1f6aebb-fca2-4409-9c7c-fb877965ead8", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:42.189817035", "complete_time": "2023-01-10T16:45:42.932613085"}, {"id": "12eaa28e-d167-4526-8bcf-8c2aa14a5ffe", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:44.150674301", "complete_time": "2023-01-10T16:45:46.227463871"}, {"id": "acf80be7-7f24-484b-9efe-2eb55951997f", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:47.208226003", "complete_time": "2023-01-10T17:23:22.749778856"}, {"id": "4094b103-da6d-44c9-b0d5-75603dec494b", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T17:23:24.714714922", "complete_time": "2023-01-10T17:23:28.90150165"}, {"id": "620abfa4-3cdc-4206-b0a0-12c9389eb522", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T17:23:29.805643536", "complete_time": "2023-01-10T17:23:32.825677892"}]}
SELECT id AS course_history_id, JSON_VALUE(progress, '$.elements[*].id') AS progress_id, JSON_VALUE(progress, '$.elements[*].status') AS status, JSON_VALUE(progress, '$.elements[*].open_time') AS open_time, JSON_VALUE(progress, '$.elements[*].complete_time') AS complete_time FROM Progress_KLC_Source;
but if i fill in [] like 0 data appear SELECT id AS course_history_id, JSON_VALUE(progress, '$.elements[0].id') AS progress_id, JSON_VALUE(progress, '$.elements[0].status') AS status, JSON_VALUE(progress, '$.elements[0].open_time') AS open_time, JSON_VALUE(progress, '$.elements[0].complete_time') AS complete_time FROM Progress_KLC_Source;
any idea?
h
What source does Progress_KLC_Source come from?
a
mysql-cdc
and i want to know how to parse that json into column too. thanks
w
also interested. Seems like UDF's the only option? something like JSON_EXTRACT_ARRAY(json_str, json_path) -> ARRAY of json_str would be quite helpful 🤔
a
any references for that (tutorial or any link)? cause i am new in flink
w
@astrajingga dewala this link is a good start. To save your time a bit,
Copy code
@udf(result_type=result_schema)
    def extract_elem(data):
        json_data = json.loads(data)
        ret = []
        for elem in json_data['elements']:
            entry = Row(id=elem['id'],
                        status=elem['status'],
                        last_pos=elem['last_pos'],
                        open_time=datetime.strptime(elem['open_time'][:-5], "%Y-%m-%dT%H:%M:%S.%f"), # implement nano second long ts parsing here
                        complete_time=datetime.strptime(elem['complete_time'][:-5], "%Y-%m-%dT%H:%M:%S.%f"),
                        )
            ret.append(entry)
        return ret
I guess you're trying to do something like this
a
ok, thank u @Woohyuck Choi, i will try. emmm any video in youtube or articel to start make and execution similar that script?
w
not that I know of, the tutorials from the official docs and code snippets here are the only resources I know of. But it's fairly simple, I just whipped this out, you can try running:
Copy code
import logging
import json
import sys
from datetime import datetime

from pyflink.common import Row
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import StreamTableEnvironment, DataTypes
from pyflink.table.expressions import col
from pyflink.table.udf import udf


def main(env: StreamExecutionEnvironment):
    tbl_env = StreamTableEnvironment.create(env)
    table = tbl_env.from_elements(elements=[
        Row("""{"elements": [{"id": "d9956ac2-6e3d-465e-8bf2-49dfa8b7b4cf", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:10.834276685", "complete_time": "2023-01-10T16:45:13.47560873"}, {"id": "86dadeca-10e8-4b36-a059-0f5659b0219f", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:14.388085978", "complete_time": "2023-01-10T16:45:16.745961631"}, {"id": "b1b4e898-af61-4dfa-9da4-cefc61f92937", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:17.635952434", "complete_time": "2023-01-10T16:45:19.833378191"}, {"id": "b993b90d-6821-4738-a5f8-477a4d4b2efb", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:20.750092211", "complete_time": "2023-01-10T16:45:38.030293061"}, {"id": "a76730c3-848b-4dc5-a507-a4fdf29fb2f5", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:39.820873143", "complete_time": "2023-01-10T16:45:40.947897919"}, {"id": "e1f6aebb-fca2-4409-9c7c-fb877965ead8", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:42.189817035", "complete_time": "2023-01-10T16:45:42.932613085"}, {"id": "12eaa28e-d167-4526-8bcf-8c2aa14a5ffe", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:44.150674301", "complete_time": "2023-01-10T16:45:46.227463871"}, {"id": "acf80be7-7f24-484b-9efe-2eb55951997f", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T16:45:47.208226003", "complete_time": "2023-01-10T17:23:22.749778856"}, {"id": "4094b103-da6d-44c9-b0d5-75603dec494b", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T17:23:24.714714922", "complete_time": "2023-01-10T17:23:28.90150165"}, {"id": "620abfa4-3cdc-4206-b0a0-12c9389eb522", "status": "FINISH", "last_pos": null, "open_time": "2023-01-10T17:23:29.805643536", "complete_time": "2023-01-10T17:23:32.825677892"}]}""")
    ],
        schema=DataTypes.ROW([DataTypes.FIELD('data', DataTypes.STRING())]),
        verify_schema=False,
    )

    result_schema = DataTypes.ARRAY(DataTypes.ROW([
        DataTypes.FIELD('id', DataTypes.STRING()),
        DataTypes.FIELD('status', DataTypes.STRING()),
        DataTypes.FIELD('last_pos', DataTypes.INT()),
        DataTypes.FIELD('open_time', DataTypes.TIMESTAMP()),
        DataTypes.FIELD('complete_time', DataTypes.TIMESTAMP()),
    ]))

    @udf(result_type=result_schema)
    def extract_elem(data):
        json_data = json.loads(data)
        ret = []
        for elem in json_data['elements']:
            entry = Row(id=elem['id'],
                        status=elem['status'],
                        last_pos=elem['last_pos'],
                        open_time=datetime.strptime(elem['open_time'][:-5], "%Y-%m-%dT%H:%M:%S.%f"),
                        complete_time=datetime.strptime(elem['complete_time'][:-5], "%Y-%m-%dT%H:%M:%S.%f"),
                        )
            ret.append(entry)
        return ret

    select_table = table.select(extract_elem(col('data'))).alias('arr_json')

    tbl_env.create_temporary_view('default_catalog.test.test_udf',
                                  select_table,
                                  )
    query = """
SELECT
    entry_json.id AS id,
    entry_json.status AS status,
    entry_json.last_pos AS last_pos,
    entry_json.open_time AS open_time,
    entry_json.complete_time AS complete_time
FROM
    `default_catalog`.`test`.`test_udf` base
CROSS JOIN
    UNNEST(base.arr_json) entry_json
    """
    tbl_env.execute_sql(query).print()


if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
    env = StreamExecutionEnvironment \
        .get_execution_environment()

    main(env)
a
finally done, thank u for help @Woohyuck Choi
👍 1