Skip to content

Instantly share code, notes, and snippets.

@mneedham
Created September 9, 2012 12:05
Show Gist options
  • Select an option

  • Save mneedham/3684005 to your computer and use it in GitHub Desktop.

Select an option

Save mneedham/3684005 to your computer and use it in GitHub Desktop.
neo4j: cypher vs core API
cypher:
START researchArea = node:research_areas('research_area_id:1'), month = node:months('month:8'), year = node:years('year:2012')
MATCH researchArea-[:has_child*1..5]->otherResearchArea-[:has_product]->product-[:sold]->sales-[:soldInMonth]->month, sales-[:soldInYear]->year
RETURN DISTINCT(sales.sales), sales.name, product
core API:
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase("/path/to/db");
Node researchArea = db.index().forNodes("research_areas").get("research_area_id", "1").getSingle();
final Node month = db.index().forNodes("months").get("month", "8").getSingle();
final Node year = db.index().forNodes("years").get("year", "2012").getSingle();
final List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
Traversal.description()
.depthFirst()
.relationships(DynamicRelationshipType.withName("has_child"), Direction.OUTGOING)
.evaluator(Evaluators.toDepth(5))
.evaluator(new Evaluator() {
public Evaluation evaluate(Path path) {
Node subResearchArea = path.endNode();
for (Relationship researchAreaToProduct : subResearchArea.getRelationships(DynamicRelationshipType.withName("has_product"))) {
Node productNode = researchAreaToProduct.getEndNode();
for (Relationship productToSales : productNode.getRelationships(DynamicRelationshipType.withName("sold"))) {
Node salesNode = productToSales.getEndNode();
Iterable<Relationship> salesToMonths = salesNode.getRelationships(DynamicRelationshipType.withName("soldInMonth"));
Iterable<Relationship> salesToYears = salesNode.getRelationships(DynamicRelationshipType.withName("soldInYear"));
for (Relationship salesToMonth : salesToMonths) {
for (Relationship salesToYear : salesToYears) {
if (salesToMonth.getEndNode().equals(month) && salesToYear.getEndNode().equals(year)) {
HashMap<String, Object> rowProperties = new HashMap<String, Object>();
rowProperties.put("name", salesNode.getProperty("name"));
rowProperties.put("sales", salesNode.getProperty("sales"));
rowProperties.put("product", productNode.getProperty("product_id"));
rows.add(rowProperties);
}
}
}
}
}
return Evaluation.INCLUDE_AND_CONTINUE;
}
})
.traverse(researchArea);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment