I am writing a social media microservice application and using neo4j for my profile microservice. I am trying to create relationships between user profiles that will be friends. This is a type of many to many relationships. I am creating 10 users and I want them to be friends of each other.
Intended relation between nodes
I created a method to add friendship relationship between users that is listed below:
@Override
public final FriendResponse addUserToFriends(String profileId, String friendId) {
log.info("Adding friend with id: {} to profile with id: {}", friendId, profileId);
Profile profile = profileRepository.findByProfileId(profileId)
.orElseThrow(ProfileNotFoundException::new);
Profile friend = profileRepository.findByProfileId(friendId)
.orElseThrow(ProfileNotFoundException::new);
log.info("Found profile and friend.");
if (profile.isFriendWith(friend)) {
throw new UsersAlreadyFriendsException(profileId, friendId);
}
log.info("Adding friend...");
profile.addNewFriendship(friend);
profile = profileRepository.save(profile);
return profileMapper.mapProfileToFriendResponse(profile, -1, false);
}
In my profile node:
@Data
@Builder
@Node("Profile")
@NoArgsConstructor
@AllArgsConstructor
public class Profile {
@Id
@GeneratedValue(generatorClass = UUIDStringGenerator.class)
private String profileId;
@Relationship(type = "FRIENDS_WITH", direction = Relationship.Direction.OUTGOING)
private Set<Profile> friendships;
public final boolean isFriendWith(Profile profile) {
return friendships
.stream()
.anyMatch(friendship -> friendship.equals(profile));
}
public final void removeProfileFromFriends(Profile profile) {
friendships
.stream()
.filter(friendship -> friendship.equals(profile))
.findFirst()
.ifPresent(friendships::remove);
}
final String getFullName() {
return String.format("%s %s", firstName, lastName);
}
public final void addNewFriendship(Profile friend) {
friendships.add(friend);
}
}
I was trying to create separate node to be created for each friendship to have relationship many to one (profile to friendship). The effect of my code is below (and the loop in which I create relationships): Effect.
for (int i = 0; i < profiles.size(); i++) {
for (int j = 0; j < profiles.size(); j++) {
if (i != j) {
friendsService.addUserToFriends(profiles.get(i).profileId(), profiles.get(j).profileId());
}
}
}
RazeEpic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.