Skip to content

22. Parse UTM Parameters

Difficulty: Medium · Topics: Strings, Conditional Logic, Filtering & Selection

visits has visit_id and the landing url. Marketing wants the campaign parameters from the query string.

Return visit_id, source (the value of utm_source) and campaign (the value of utm_campaign). A parameter that is absent must be null, not an empty string. Only real parameters count: my_utm_source=x is a different parameter.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

visits

visit_idurl
1https://shop.in/?utm_source=google&utm_campaign=diwali
2https://shop.in/sale?utm_campaign=summer&utm_source=newsletter
3https://shop.in/about
4https://shop.in/?ref=x&utm_source=instagram

Expected output

visit_idsourcecampaign
1googlediwali
2newslettersummer
3nullnull
4instagramnull

Hints

Hint 1A parameter starts right after ? or &: [?&]utm_source=([^&#]+) captures its value up to the next & or #.
Hint 2regexp_extract returns an empty string when nothing matches.
Hint 3Turn the empty string into null with F.when(col == "", None).otherwise(col).

Learn the concepts

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · Learn · All problems