How to implement composite keys in Neo4J
Asked Answered
F

1

8

I need to ensure that a combination of more than one property values in all nodes is unique. How to do that in Neo4J.

From Neo4J documentation available at http://docs.neo4j.org/chunked/milestone/transactions-unique-nodes.html, it's possible to ensure uniqueness of one property. But what about combination of 2 or more.

Fibrous answered 6/2, 2013 at 10:7 Comment(0)
H
4

You could try

  public Node getOrCreateUserWithUniqueFactory(final String firstName, final String lastname, GraphDatabaseService graphDb) {
    UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory(graphDb, "users") {
      @Override
      protected void initialize(Node created, Map<String, Object> properties) {
        created.setProperty("id", properties.get("id"));

        created.setProperty("firstName", firstName);
        created.setProperty("lastName", lastname);
      }
    };

    return factory.getOrCreate("id", firstName + "_" + lastname);
  }
Heartland answered 6/2, 2013 at 10:42 Comment(4)
Thanks Werner! I am going to use this in my implementation unless I find some even better way. Many thanks!Fibrous
Just beware that this isn't creating a composite key in the sense that you have 2 separate keys that you can look up, this is creating one key that is the combination of the two keys you wanted previously. The Unique Factory doesn't currently provide a way of creating unique nodes with composite keys.Pucka
Thanks Nicholas! FirstName, lastName (and other fields constituting composite key) are coming from reflection using Class.getDeclaredFields() methods to retrive fields and then using field to fetch field value. Since field order is not guarnteed by Java, this looks a bit tricky to me.Fibrous
Beware also that this implementation requires that both values are strings and that the values are guaranteed to not have underscores in them. You might get around both of these by serializing the composite data structure as JSON.Landonlandor

© 2022 - 2024 — McMap. All rights reserved.