You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@mahout.apache.org by N! <12...@qq.com> on 2014/01/24 08:05:57 UTC

Re: Using setPreference() to update recommendations in DataModel in Memory

Sean Owen <srowen <at> gmail.com> writes:


> 
> It throws an exception except in a few implementations, mostly the
> ones based on a database. It isn't something that's really used -- you
> instead update the backing store indirectly. Yes, the model is batch
> re-reads of data once in a while. Updates are not in real time in this
> model.



Hi Sean:
           I write an implementation of GenericDataModel , to make setPreference and removePreference methods be able to update the data in memory in real time way. Here is the code below,correct me if I am wrong.


public synchronized void setPreference(long userID, long itemID, float value) 
	  {
		  if(!this.isUserExist(userID) || !this.isItemExist(itemID))
		  {
			  throw new UnsupportedOperationException();
		  }
		  if(!preferenceFromUsers.containsKey(userID))
		  {
			  List<Preference> currentPrefs = Lists.newArrayList();
			  currentPrefs.add(new GenericPreference(userID, itemID, value));
			  PreferenceArray preferenceArray = new GenericUserPreferenceArray(currentPrefs);
			  preferenceFromUsers.put(userID,preferenceArray);
		  }
		  else
		  {
			  PreferenceArray preferenceFromUser = preferenceFromUsers.get(userID);
			  if(preferenceFromUser.hasPrefWithItemID(itemID))
			  {
				  for(Preference p:preferenceFromUser)
				  {
					  if(p.getItemID()==itemID)
					  {
						  p.setValue(value);
						  break;
					  }
				  }  
			  }else
			  {
				  List<Preference> currentPrefs = Lists.newArrayList();
				  for(Preference p:preferenceFromUser)
				  {
					  currentPrefs.add(new GenericPreference(p.getUserID(), p.getItemID(), p.getValue()));
				  }
				  currentPrefs.add(new GenericPreference(userID, itemID, value));
				  PreferenceArray preferenceArray = new GenericUserPreferenceArray(currentPrefs);
				  preferenceFromUsers.put(userID,preferenceArray);
			  }
			  
		  }
		  //same as construction method of GenericDataModel
		  this.refreshGenericDataModelCustom(preferenceFromUsers, null);
	  }



          public synchronized boolean isUserExist(long userID)
	  {
		  boolean flag = false;
		  for(long userIdTmp:userIDs)
		  {
			  if(userIdTmp==userID)
			  {
				  flag = true;
				  break;
			  }
		  }
		  return flag;
	  }
	  public synchronized boolean isItemExist(long itemID)
	  {
		  boolean flag = false;
		  for(long itemIDTmp:itemIDs)
		  {
			  if(itemIDTmp==itemID)
			  {
				  flag = true;
				  break;
			  }
		  }
		  return flag;
	  }