Neo4j Database – Part 07 – Northwind Queries

In the last blog I took the Northwind database and converted it to a Neo4j graph database model. In this blog I will run some sample Cypher queries.

Cypher Query Language

It is not my intention to give a tutorial on using Cypher rather than give some simple examples. There are entire books on the subject and a chapter in the Neo4j Developer Manual. Then there are plugins like APOC and GraphQL which dramatically enhance the querying capability.

Order Subtotals

RETURN o.OrderID AS OrderID, 
       SUM(i.UnitPrice * i.Quantity * (1 - i.Discount)) AS Subtotal

Employee Sales by Country

MATCH (e:Employee)-[s:SELLS]-(o:Order)-[i:ORDER_ITEM]-()
RETURN e.Country, e.LastName, e.FirstName, o.ShippedDate, o.OrderID, 
       SUM(i.UnitPrice * i.Quantity * (1 - i.Discount)) AS Sale_Amount
ORDER BY e.Country, e.LastName, e.FirstName, o.ShippedDate

Sales By Category

MATCH (p:Product)-[i:ORDER_ITEM]-()
WITH p, SUM(i.UnitPrice * i.Quantity * (1 - i.Discount)) AS ProductSales
RETURN p.Category, p.Product, ProductSales
ORDER BY p.Category, p.Product, ProductSales

Products above Average Price

MATCH (p:Product),(p2:Product)
WITH p, avg(p2.UnitPrice) AS AVGUnitPrice
WHERE p.UnitPrice > AVGUnitPrice
RETURN p.Product, p.UnitPrice
Order BY p.UnitPrice

Return the Highest Level Manager

MATCH p = (e:Employee {FirstName: "Robert", LastName: "King"}) -[*]-> (m:Employee) 
WITH COLLECT(p) AS paths, MAX(length(p)) AS maxLength 
WITH FILTER(path IN paths WHERE length(path)= maxLength) AS longestPaths
WITH EXTRACT(path IN longestPaths | LAST(NODES(path))) as last
RETURN LAST(last).FirstName AS FirstName, LAST(last).LastName AS LastName

In the next blog I will discuss transactions.