mahout做推荐时uid,pid为string类型

很幸运找到这篇文件,解了燃眉之急。

http://blog.csdn.net/pan12jian/article/details/38703569

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

查看mahout源码,其实把string类型变成long采用的是MD5加密方式。源码如下

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) {
  }
  
}

其实根据这个思想,写项目时也可以不调用此接口。在写程序时,可以先用mapreduce对原CSV文件进行处理把所有的数据变为long类型,并记录一个(string key,long value)的文件,然后进行推荐,用结果数据和前mapreduce输出做join即可得出结果。

原文地址:https://www.cnblogs.com/sunxucool/p/4286657.html