GCP

Improving nested_fields data access experience with a persistent user-defined function (aka UDF) in Google Big Query

CK CK 3788 
Created at  
1,506 0 0

When you have a table containing an array of RECORDS, you may get confused about how to get its element value.

In Google BigQuery, a persistent user-defined function (UDF) is a function stored in your BigQuery project that can be reused across multiple queries, improving performance by avoiding repeated compilation and potentially reducing execution time for frequently used custom logic. To create one, you use the CREATE FUNCTION statement specifying the function's name, arguments, return type, and the SQL code defining its behavior, using the PERSISTENT keyword; the function's code is then stored within your project and can be called from various queries using its name.
 

When you have nested_fields from Apache Kafka composed of key and value, the first action you should take is to create a function for better access. Below query is creating a function CK_GET_VAL(key_string, arr):

CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.CK_GET_VAL`(string_key STRING, arr ARRAY<STRUCT<key STRING, value STRING>>)
RETURNS STRING
AS (
  (SELECT COALESCE((SELECT value FROM UNNEST(arr) WHERE key = string_key LIMIT 1), NULL))
);

Once the function is created successfully, you can get the value stored in nested_fields like below:

SELECT
    dt,
    `{project_id}.{dataset_id}.CK_GET_VAL`('cid', nested_fields) AS client_id,  -- Backticks here
    `{project_id}.{dataset_id}.CK_GET_VAL`('t', nested_fields) AS event_type,  -- And here
    `{project_id}.{dataset_id}.CK_GET_VAL`('m', nested_fields) AS membership,  -- And here
    `{project_id}.{dataset_id}.CK_GET_VAL`('ep', nested_fields) AS episode_slug,  -- And here
FROM
    `{project_id}.{dataset_id}t.kafka_raw`  -- Backticks here
WHERE dt BETWEEN '2025-01-01 00:18:00+00' AND '2025-01-02 00:33:00+00'
LIMIT 100

 

If you want to check if CK_GET_VAL() is defined, you can check through BigQuery like below:

SELECT COUNT(*)
FROM `{project_id}.{dataset_id}.INFORMATION_SCHEMA.ROUTINES`
WHERE ROUTINE_NAME = '{function_id}'
Tags Apache Kafka Persistent User-Defined Function UDF nested_fields Facebook X
Comments 0
Similar posts
  1. Creating a serverless Apache Kafka publisher using AWS Lambda
    568
  2. Apache Kafka - a distributed, fault-tolerant, high-throughput streaming platform
    618
  3. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    193
  4. Real-time Data Streaming Solutions - Kafka vs. Kinesis Comparison
    857
  5. Architectural Diagram Gallery for Amazon MSK
    505
  6. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    176
  7. Java Kafka on CentOS 7: Install, Configure, & Run with Examples
    431
  8. Apache Kafka Explained: Powering Netflix, Building with PHP
    495
  9. Multi-AZ Kafka Architecture
    157
  10. Designing Resilient Infrastructure to Prevent Order Data Loss During Kafka Failures
    161
  11. Enterprise-Scale 100k+ TPS Order Processing System Architecture
    183
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Step-by-Step Guide to Using Google AI Gemini API with CURL
    3,210
  3. Creating a Service Account via Google Cloud Console (UI)
    1,069
  4. Creating a query based on record type data field in Google BigQuery
    1,642
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  3. How do I create animated background for Google Meet?
    23,256
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  7. Array of arguments passed to script in PHP
    99
  8. Invalid Auction Storms in Ad Tech
    108
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  10. The Two Clocks of Ad Server Architecture
    78
  11. Frequency Cap Architecture Overview
    527
  12. Collecting Proof-of-Play from 100,000 Screens
    154
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    304
  14. What is RedisVL?
    117
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  16. TPU & GPU Cluster Management Tools
    258
  17. The Concept of Scaffolding in AI Agents
    245
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  22. Machine Learning: Training vs. Ranking
    232
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  25. Designing a Data Curation System Around a Vector Database
    230
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    264
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233
  30. Understanding Data Lineage
    273