Skip to content
illyfrancis edited this page Jul 26, 2013 · 6 revisions

Intro to Neo4j by Emil Eifram

Core abstractions

  • Nodes
  • Relationships between nodes
  • Properties on both

Example: the matrix

  • First Identify the entities
    • node id (mandatory attrib on a node)
    • node attributes
  • Nodes (Person) knows (relationships) other node
    • Relationships also have properties (e.g. the "knows" has age = 3 days)
    • can add arbitrary relationships "coded_by"

Code 1 : building a node space

GraphDatabaseService graphDb = ... // get factory (via DI or whatever)

Transaction tx = graphDb.beginTx();  // this is important!!! 

// create Thomas "Neo" Anderson
Node mrAnderson = graphDb.createNode();
mrAnderson.setProperty("name", "Thomas Anderson");
mrAnderson.setProperty("age", 29);

// create Morpheus
Node morpheus = graphDb.createNode();
morpheus.setProperty("name", "Morpheus");
morpheus.setProperty("rank", "Captain");
morpheus.setProperty("occupation", "Total bad ass");

// create a relationship representing that they know each other
mrAnderson.createRelationshipTo(morpheus, RelTypes.KNOWS);

// create Trinity, Cypher, Agent Smith, Architect similarly

tx.commit();

Code 1b : Defining RelationshipTypes

// In package org.neo4j.graphdb
public interface RelationshipType {
  String name();
}

// example of how to roll dynamic RelationshipTypes
class MyDynamicRelType implements RelationshipType {
  private final String name;
  MyDynamicRelType(String name) { this.name = name; }
  public String name() { return this.name; }
}

There's standard imp in the API by the way.

Dynamic relationship is useful when you don't know before. But if you do know use static relationship type

// Example on how to static-relationshiptype
enum MyStaticRelTypes implements RelationshipType {
  KNOWS,
  KNOWS_FOR,
}

Clone this wiki locally