2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【データ基盤構築/BigQuery】URLの表記揺れの名寄せを行う

Last updated at Posted at 2022-10-31

今回の課題

社内のマスタデータからBigQueryにデータを取り込んだところ、URLに表記揺れがあった。
処理をしやすいように名寄せ処理を行う必要があった。

名寄せ処理が必要なデータを目視で探した

下記のクエリを実行して、データの除去や名寄せが必要なデータを目視でざっと探してみた。

--dateをdate型に変換。page_pathが「/contents/」で始まるURLに絞る。page_pathの「index」「&」「?」文字列以降のデータを削除。
with master as (
    select
        page_title
        , page_path
    from
        `テーブル名`
    where
        regexp_contains(page_path, r'^/contents/') --「/contents/」で始まるURLに絞る。   
)

--page_pathカラムがすべて「/」で終了するように調整。
, master2 as (
    select
        page_title
        , split(page_path, '/') as page_path_array
    from
        master
)

--必要なカラムを抽出
select 
    page_path_array
    , offset
from 
    master2 as m
cross join unnest(m.page_path_array) as page_path_array
with offset as offset
group by
    page_path_array 
    , offset

上記クエリの解説

上記のクエリを実行した結果、下記の名寄せ処理の条件の項目のURLを名寄せする必要があると分かった。

名寄せ処理の条件

下記のように名寄せを行った。

  1. /contents/から始まるURLに絞り込む(それ以外は除外する)
  2. indexが付いているURLを除外(URLの最後にindex.htmlといった記述があるものを除外したい。)
  3. パラメータ付きのURLを除外(?~, &~となっているURL)
  4. /で終わっていないURLは、/を付け足しする。
  5. 上記を除外した後で他に最後のスラッシュ後に余計なものが付与されているデータを除去する。(offsetが4なのに、https://~という文字列が付いているURLがあったので、それを除去したい。)

※除外しきれないURLがあった際、そういったデータはゴミデータとして除外してしまうのもあり。

実装方法

  • 名寄せ処理の条件1~4について
    page_pathindex, &, ?文字列以降のデータを削除した状態から、
    更に/で終っているかどうかを正規表現で判定して/で終わっていなければ/を末尾に付与する。

  • 名寄せ処理の条件5について
    1~4を除外した後に、最後の/の後ろにhttps:~が付与されていたので、
    下記クエリの(.*/https:/).*$で除外した。

with master as (
    select
        page_title
       , regexp_replace(normalize(page_path, NFKC), r'(index|&|\?).*|[^a-zA-Z0-9-/:-@-~_]|[ +]|(.*/https:).*$', "") as page_path_fix --データの揺れを調整
    from
        `テーブル名`
    where
        regexp_contains(page_path, r'^/contents/') --「/contents/」で始まるURLに絞り込む。
)

select
    page_title
    , page_path -- 一応、元のpage_pathも保持しておく
    , if(regexp_contains(page_path, r'.*/$'), concat(page_path, ""), concat(page_path, "/")) as page_path_fix -- page_pathカラムが全て「/」で終了するように調整。
from
    master
;

補足

以上で、名寄せ処理が完了した。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?