In [22]:
%%bigquery df
CREATE TEMPORARY FUNCTION hashed(airport STRING, numbuckets INT64) AS (
ABS(MOD(FARM_FINGERPRINT(airport), numbuckets))
);
WITH airports AS (
SELECT
DISTINCT(departure_airport)
FROM `bigquery-samples.airline_ontime_data.flights`
)
SELECT
departure_airport,
hashed(departure_airport, 3) AS hash3,
hashed(departure_airport, 10) AS hash10,
hashed(departure_airport, 1000) AS hash1000,
FROM airports
In [23]:
df.head(n=10)
Out[23]:
In [24]:
len(df)
Out[24]:
Some airports had very few flights
In [27]:
%%bigquery
SELECT
departure_airport, COUNT(1) AS num_flights
FROM `bigquery-samples.airline_ontime_data.flights`
GROUP BY departure_airport
ORDER BY num_flights ASC
LIMIT 10
Out[27]:
In [37]:
import pandas as pd
def calc_collision_prob(num_total, num_hash):
no_collision_prob = 1.0
for i in range(num_total):
# i of the previous buckets is occupied now
collision_likelihood = float(i) / num_hash
no_collision_prob *= (1 - collision_likelihood)
return 1 - no_collision_prob
data = []
for num_hash in [3, 10, 100, 1000, 10000, 100000]:
data.append([num_hash,
len(df)/num_hash,
calc_collision_prob(len(df), num_hash)
])
prob = pd.DataFrame(data, columns=['num_hash_buckets', 'entries_per_bucket', 'collision_prob'])
prob
Out[37]:
In [29]:
calc_collision_prob(5, 1000) # num_hash >> num_total
Out[29]:
In [33]:
%%bigquery
CREATE TEMPORARY FUNCTION hashed(airport STRING, numbuckets INT64) AS (
ABS(MOD(FARM_FINGERPRINT(airport), numbuckets))
);
WITH airports AS (
SELECT
departure_airport, COUNT(1) AS num_flights
FROM `bigquery-samples.airline_ontime_data.flights`
GROUP BY departure_airport
)
SELECT
departure_airport, num_flights
FROM airports
WHERE hashed(departure_airport, 100) = hashed('ORD', 100)
Out[33]:
Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License