|
| 1 | +# standardSQL |
| 2 | +# jsonld_depth_percentiles.sql |
| 3 | +# Find the most nested entity in a JSON-LD document |
| 4 | +CREATE TEMP FUNCTION getJSONLDEntitiesRelationships(rendered STRING) |
| 5 | +RETURNS ARRAY<STRUCT<_from STRING, relationship STRING, _to STRING, depth NUMERIC>> |
| 6 | +LANGUAGE js AS """ |
| 7 | + try { |
| 8 | + const types = new Map(); |
| 9 | +
|
| 10 | + const loadTypes = (o) => { |
| 11 | + if (Array.isArray(o)) { |
| 12 | + o.forEach(loadTypes); |
| 13 | + } else if (o instanceof Object) { |
| 14 | + if (o['@id'] && o['@type']) { |
| 15 | + types.set(o['@id'], o['@type']); |
| 16 | + } |
| 17 | +
|
| 18 | + Object.values(o).forEach(loadTypes); |
| 19 | + } |
| 20 | + } |
| 21 | +
|
| 22 | + const arrayify = (value) => Array.isArray(value) ? value : [value]; |
| 23 | +
|
| 24 | + const getEntitiesAndRelationships = (o, _from, relationship, depth = 0) => { |
| 25 | + if (Array.isArray(o)) return o.map(value => getEntitiesAndRelationships(value, _from, relationship, depth)).flat(); |
| 26 | +
|
| 27 | + if (o instanceof Object) { |
| 28 | + const type = types.get(o['@id']) || o['@type']; |
| 29 | + return [{_from, relationship, _to: type, depth}, ...Object.entries(o).map(([k, value]) => getEntitiesAndRelationships(value, type, k, depth + 1))].flat(); |
| 30 | + } |
| 31 | +
|
| 32 | + return []; |
| 33 | + } |
| 34 | +
|
| 35 | + rendered = JSON.parse(rendered); |
| 36 | + const jsonld_scripts = rendered.jsonld_scripts.map(JSON.parse); |
| 37 | + loadTypes(jsonld_scripts); |
| 38 | +
|
| 39 | + return jsonld_scripts.map(jsonld_script => getEntitiesAndRelationships(jsonld_script, undefined, undefined, 0)).flat(); |
| 40 | + } catch (e) { |
| 41 | + return []; |
| 42 | + } |
| 43 | +"""; |
| 44 | + |
| 45 | +WITH rendered_data AS ( |
| 46 | + SELECT |
| 47 | + client, |
| 48 | + root_page AS url, |
| 49 | + getJSONLDEntitiesRelationships(JSON_EXTRACT(JSON_VALUE(JSON_EXTRACT(payload, '$._structured-data')), '$.structured_data.rendered')) AS jsonld_entities_relationships |
| 50 | + FROM |
| 51 | + `httparchive.all.pages` |
| 52 | + WHERE |
| 53 | + date = '2024-06-01' |
| 54 | +) |
| 55 | + |
| 56 | +SELECT |
| 57 | + client, |
| 58 | + percentile, |
| 59 | + APPROX_QUANTILES(jsonld_entity_relationship.depth, 1000)[OFFSET(percentile * 10)] AS depth, |
| 60 | + ARRAY_TO_STRING(ARRAY_AGG(DISTINCT url LIMIT 5), ' ') AS sample_urls |
| 61 | +FROM |
| 62 | + rendered_data, |
| 63 | + UNNEST(jsonld_entities_relationships) AS jsonld_entity_relationship, |
| 64 | + UNNEST([10, 25, 50, 75, 90, 100]) AS percentile |
| 65 | +GROUP BY |
| 66 | + client, |
| 67 | + percentile |
| 68 | +ORDER BY |
| 69 | + client, |
| 70 | + percentile |
0 commit comments