Sample by a Hash Function (Scala)

It’s really common in Big Data ad hoc analysis we need to down sample the data. However for most of the cases, we need to down sample based on some hash function of a Key of the data. For example, to process credit card data, we want to perform the sampling consistently across all the data files which contend account ID as the key. The pseudo code for this is

1
2
if Hash(account_ID) % 100 < 5: Keep
else: Drop

In Spark, we can use the MurmurHash3 function in Scala to do the sampling:

1
2
3
4
5
import scala.util.hashing.{MurmurHash 3 = >MH 3 }
.....
val seed = 12345
val rate = 0.05
val sample = data.filter(line = >(MH 3 .stringHash(line.take( 10 ),seed)& 0x7FFFFFFF )<(rate* 0x7FFFFFFF ))

Here I take the first 10 characters as the key and applied the MH3 hash. Since MH3.stringHash returns an Int, I apply a binary “and” to drop the 1st bit and applied the sample rate comparison.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值