clickhouse

How to run query against JSON extract data in ClickHouse?


I have the following Clickhouse table:

id, custom, otherfield1, otherfield2.

In the custom, we put a JSON inside of it that looks like

{"activityId": 1234, "someJsonField": "blah"}

so now I want to query 10 rows where the activityId field is 1234. How do I go about doing this?

SELECT 
    custom,
    JSONExtractString(custom, 'activityId') AS ActivityId
FROM muh_table
where ActivityId = "1234"
limit 1

But then I get error, basically saying the column doesn't exist. What's the correct syntax in getting this SQL written out?


Solution

  • You might have to share some more details. This worked fine for me:

    create or replace table zhen (
        id UInt32,
        custom String
    )
    ENGINE = MergeTree
    PRIMARY KEY id;
    
    INSERT INTO zhen VALUES 
        (1, '{"activityId": 1234, "someJsonField": "blah1"}'),
        (2, '{"activityId": 1234, "someJsonField": "blah2"}'),
        (3, '{"activityId": 5678, "someJsonField": "blah3"}');
    
    SELECT 
        id,
        JSONExtractString(custom, 'activityId') AS ActivityId
    FROM zhen
    WHERE ActivityId = '1234';
    

    Response is:

    ┌─id─┬─ActivityId─┐
    │  1 │ 1234       │
    │  2 │ 1234       │
    └────┴────────────┘