简体   繁体   中英

BigQuery's query filter by json type

My database table like below.

Row Name Info
1 Tom {"count":0, "error":[0,"failed",0]}
2 Joe {"count":0, "error":["failed","failed","failed"]}
3 Joe {"count":0, "error":[0,0,0]}
4 Tom {"count":0, "error":["failed","failed",0]}

I hope filter data by "Info.error's array" in the following order.

  1. all is 0
  2. exclude all failed
  3. at least one is 0

result data

Row Name Info
1 Tom {"count":0, "error":[0,"failed",0]}
3 Joe {"count":0, "error":[0,0,0]}
4 Tom {"count":0, "error":["failed","failed",0]}

So, how should enter the SQL syntax? Thanks a lot.

In order to find out the amount of a particular value in a json array you can use the following snippet:

  (SELECT
    COUNTIF(JSON_EXTRACT_SCALAR(error) = "0")
  FROM
    UNNEST(JSON_EXTRACT_ARRAY(ex_table.Info, '$.error')) AS error ) count_zeros,
   
  (SELECT
    COUNTIF(JSON_EXTRACT_SCALAR(error) = "failed")
  FROM
    UNNEST(JSON_EXTRACT_ARRAY(ex_table.Info, '$.error')) AS error ) count_failed

Using these two new variables, you can then create your actual filters.

1.

 WHERE
  count_zero = ARRAY_LENGTH(Info.error)
 WHERE 
  NOT count_failed = ARRAY_LENGTH(Info.error)
WHERE  
  count_zero > 0

You should be able to simplify your rule set as rule 3 accounts for all scenarios you have listed. Given your sample data try the following:

select *,
from sample_data
WHERE "0" in (SELECT * from UNNEST(JSON_VALUE_ARRAY(info, "$.error")))

It produces:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM