mahout做推荐的输入只能是long类型,但在某些网站中,存储的数据不是long类型,是string类型。
现在的手机APP,每个手机都有其device_id,也是string类型。如果能以string类型作为uid,即使用户不注册,不登录。只要采用device_id作为其uid,也可以做精准推荐。
mahout提供了一个接口,能把string转为唯一的long类型数据,然后以map方式存储起来,计算完成后再把long转为string类型。
下面是我的一个小例子
package test; import org.apache.mahout.cf.taste.impl.model.MemoryIDMigrator; public class TestMT { public static void main(String[] args) { // TODO Auto-generated method stub String test = "d140615p10693zc"; MemoryIDMigrator thing2long = new MemoryIDMigrator(); Long testLong = thing2long.toLongID(test); System.out.println(testLong); thing2long.storeMapping(testLong, test); String a =thing2long.toStringID(testLong); System.out.println(a); } }
4365567189612030889 d140615p10693zc
public abstract class AbstractIDMigrator implements IDMigrator { private final MessageDigest md5Digest; protected AbstractIDMigrator() { try { md5Digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { // Can't happen throw new IllegalStateException(nsae); } } /** * @return most significant 8 bytes of the MD5 hash of the string, as a long */ protected final long hash(String value) { byte[] md5hash; synchronized (md5Digest) { md5hash = md5Digest.digest(value.getBytes(Charsets.UTF_8)); md5Digest.reset(); } long hash = 0L; for (int i = 0; i < 8; i++) { hash = hash << 8 | md5hash[i] & 0x00000000000000FFL; } return hash; } @Override public long toLongID(String stringID) { return hash(stringID); } @Override public void refresh(Collection<Refreshable> alreadyRefreshed) { } }