简体   繁体   中英

Guava Table alternative

We have partitioned database and data of each user is stored at specific server.

My use case is fairly simple:

  • Users has conversations.
  • For one conversation there is two representing record at database (Each user has its own conversation record).

In case a delete operation for user, I would like to delete all conversations between each user. That is to say, I need to delete all conversations related to user in each server. I desperately need grouped data per server.

Table<Integer, Integer, Set<Integer>> setPerUser = HashBasedTable.create();

for(Conversation conversation : conversations) {
   Integer serverIndex = getServerForUser(conversation);
   Integer userId = conversation.getUserId();
   Set<Integer> uci = setPerUser.get(serverIndex, userId);
   if(uci == null) {
      uci = Sets.newHashSet();
      setPerUser.put(serverIndex, userId, uci);
   }
   uci.add(conversation.id);
}

At the beginning I thought that each row can represent servers and column users. It seems that Table data structure is not suitable for this case. In this case Table is representing is too sparse data. Although Table can represent M x N data, I have just M + N data.

What is the correct data structure to represent this data?

Edit:

Of course Table can handle this situation but I am not sure about whether it is fitting or not for this problem. What make me think about Table is having row and column methods which implies a complicated algorithm. In my use case columns has one value which means each user has an only one corresponding server but each row has multiple values mean each server has multiple users.

I think using an existing data structure is not going to work for your use case.

Instead, you should design Objects corresponding to your data:

public Class User{
  int id;
  Set<Conversation> conversations;
}

public class Conversation{
  int id;
  Set<User> parcipitants;
}

(Getters, Setters, equals() / hashCode() ommitted in both cases)

Now keep two maps to lookup users and conversations:

private Map<Integer, Conversation> conversationsById;
private Map<Integer, User> usersById;

Write methods like getOrCreateConversation(Integer id) and getOrCreateUser(Integer id) etc.

Also, you should think about using a persistence technology like JPA or Hibernate, because these are excellent at maintaining such relationships.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM