Skip to content

Instantly share code, notes, and snippets.

@massimomusante
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save massimomusante/d389cc6a4546d25c6ea2 to your computer and use it in GitHub Desktop.
Save massimomusante/d389cc6a4546d25c6ea2 to your computer and use it in GitHub Desktop.
Fragments from Neo4j demo
protected final static String DBPATH = "./localdb";
protected GraphDatabaseService db = null;
protected void startup()
{
// instantiate the database
db = new GraphDatabaseFactory().newEmbeddedDatabase(DBPATH);
// register shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
db.shutdown();
}
});
try (final Transaction t = db.beginTx())
{
….
t.success();
}
Node n1 = db.createNode();
n1.setProperty("text", "Hello");
Node n2 = db.createNode();
n2.setProperty("text", "World");
Relationship r = n1.createRelationshipTo(n2, DemoRelationship.linked_to);
r.setProperty("text", "to all the");
public enum DemoRelationship implements RelationshipType
{
linked_to
}
private Node randomPerson(String family, int generation)
{
Node person = db.createNode(personLabel);
String sex = Math.random()>.5?"M":"F";
String name;
if("F".equals(sex))
{
name = fNames[(int)(Math.random()*fNames.length)];
}
else
{
name = mNames[(int)(Math.random()*mNames.length)];
}
person.setProperty("sex", sex);
person.setProperty("name", name);
person.setProperty("family", family);
person.setProperty("generation", generation);
return person;
}
ResourceIterable<Node> gotRoot = db.findNodesByLabelAndProperty(rootLabel, "type", "root");
if(gotRoot==null || !gotRoot.iterator().hasNext())
{
Node root = db.createNode(rootLabel);
root.setProperty("type", "root");
// initial database fill
for(int j=0;j<INITIAL_FILL;j++)
{
Node person = randomPerson();
person.createRelationshipTo(root, PersonRelationships.initial_setup);
}
t.success();
result = root;
}
else
{
result = gotRoot.iterator().next();
}
private static final String GENERATION_QUERY = "match (n:person) "
+ "where not (n-[:married_with]->(:person)) "
+ "and n.sex={sex} "
+ "and rand()>{pick} "
+ "and n.generation={generation} "
+ "return n;";
// mate some of same level nodes
Node male = (Node) males.columnAs("n").next();
Node female = (Node) females.columnAs("n").next();
male.createRelationshipTo(female, PersonRelationships.married_with);
// add random children to some random mated nodes
if(Math.random()>BIRTH_RATIO)
{
final double children = Math.random()*MAX_CHLDREN;
for(int j=1;j<children;j++)
{
Node c = randomPerson((String) male.getProperty("family"), generation + 1);
c.createRelationshipTo(male, PersonRelationships.child_of);
c.createRelationshipTo(female, PersonRelationships.child_of);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment