查询Hazelcast分层树结构

时间:2016-06-28 05:07:28

标签: mapreduce hazelcast

我正在试图弄清楚如何在Hazelcast中查询分层树结构。假设我有一个组织类:

public class Organization {
  private long id;
  private long parentId;
}

我有一个User类:

public class NestupUser extends BaseEntity {
  private long id;
  private String firstName;
  private String lastName;
  private String email;
  private String password;
  private long organizationId;
}

现在,给定一个组织我希望找到该组织的所有用户以及将该组织作为父组织的所有组织,将这些组织作为父组织等。

我认为这可以作为某种MapReduce,但是有可能作为MapReduce的一部分启动更多的MapReduce任务吗?

任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

我最终建立了一个非规范化的多图,因此我可以找到给定组织ID的所有可达组织。这是在启动时设置结构的代码,如果它尚未由另一个节点设置的话。这个类还实现了条目监听器接口,以便在事情发生变化时获得回调以保持结构同步(未显示,但不难):

@PostConstruct
public void init() {
    IMap<String, Organization> organizationMap = organizationService.getMap();
    listenerRegistration = organizationMap.addLocalEntryListener(this);
    MultiMap<String, String> orgStructureMap = getOrgStructureMap();
    if (orgStructureMap.keySet().size() == 0) {
        Collection<Organization> all = organizationService.getAll(null);
        Set<String> visited = new HashSet<>();
        for (Organization next : all) {
            if (!visited.contains(next.getId())) {
                while (next != null && next.getParentId() != null && !visited.contains(next.getParentId())) {
                    next = next.getParentOrganization();
                }
                recurseReferences(visited, next);
            }
        }
    }
}

private void recurseReferences(Set<String> visited, Organization org) {
    addAllReferences(org);
    visited.add(org.getId());
    Set<Organization> childOrganizations = org.getChildOrganizations();
    for (Organization child : childOrganizations) {
        recurseReferences(visited, child);
    }
}

private void addAllReferences(Organization organization) {
    MultiMap<String, String> orgStructureMap = getOrgStructureMap();
    String parentId = organization.getParentId();
    if (parentId != null) {
        Set<Map.Entry<String, String>> entries = orgStructureMap.entrySet();
        for (Map.Entry<String, String> next : entries) {
            if (next.getValue().equals(parentId)) {
                orgStructureMap.put(next.getKey(),organization.getId());
            }
        }
    }
    orgStructureMap.put(organization.getId(), organization.getId());
}



private void removeAllReferences(Organization organization) {
    MultiMap<String, String> orgStructureMap = getOrgStructureMap();
    Set<String> keys = orgStructureMap.keySet();
    for (String key : keys) {
        orgStructureMap.remove(key, organization.getId());
    }
}