Created
July 7, 2014 03:53
-
-
Save nicolewhite/348e1650d3fdfb3398d3 to your computer and use it in GitHub Desktop.
Add weekdays to a neo4j time tree.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(RNeo4j) | |
graph = startGraph("http://localhost:7474/db/data/") | |
# Create time tree. | |
# Copied from http://www.markhneedham.com/blog/2014/04/19/neo4j-cypher-creating-a-time-tree-down-to-the-day/ | |
timetree = "WITH range(2011, 2014) AS years, range(1,12) as months | |
FOREACH(year IN years | | |
MERGE (y:Year {year: year}) | |
FOREACH(month IN months | | |
CREATE (m:Month {month: month}) | |
MERGE (y)-[:HAS_MONTH]->(m) | |
FOREACH(day IN (CASE | |
WHEN month IN [1,3,5,7,8,10,12] THEN range(1,31) | |
WHEN month = 2 THEN | |
CASE | |
WHEN year % 4 <> 0 THEN range(1,28) | |
WHEN year % 100 <> 0 THEN range(1,29) | |
WHEN year % 400 <> 0 THEN range(1,29) | |
ELSE range(1,28) | |
END | |
ELSE range(1,30) | |
END) | | |
CREATE (d:Day {day: day}) | |
MERGE (m)-[:HAS_DAY]->(d))))" | |
cypher(graph, timetree) | |
# Generate dates from January 1st, 2011 to December 31st, 2014 by day. | |
dates = seq(from = as.Date("2011/1/1"), | |
to = as.Date("2014/12/31"), | |
by = "day") | |
# Extract day, month, year, and weekday from dates and store in data frame. | |
weekdays = data.frame(Day = format(dates, "%d"), | |
Month = format(dates, "%m"), | |
Year = format(dates, "%Y"), | |
Weekday = weekdays(dates)) | |
# Write data frame to csv. | |
filepath = "C:/Users/Nicole/Desktop/weekdays.csv" | |
write.csv(weekdays, filepath, row.names = F) | |
# Use load csv to match the day and then add the weekday relationship. | |
load_csv = paste0("LOAD CSV WITH HEADERS FROM 'file:///", filepath, "' AS csv") | |
add_weekdays = paste(load_csv, | |
"MATCH (d:Day {day:TOINT(csv.Day)})<-[:HAS_DAY]-(:Month {month:TOINT(csv.Month)})<-[:HAS_MONTH]-(:Year {year:TOINT(csv.Year)}) | |
MERGE (w:Weekday {weekday:csv.Weekday}) | |
CREATE (d)-[:ON_WEEKDAY]->(w)") | |
cypher(graph, add_weekdays) | |
# All days on a Wednesday in February of 2012. (2012 was a leap year) | |
cypher(graph, "MATCH (:Year {year:2012})-[:HAS_MONTH]->(:Month {month:2})-[:HAS_DAY]->(d:Day)-[:ON_WEEKDAY]->(:Weekday {weekday:'Wednesday'}) | |
RETURN d.day") | |
# d.day | |
# 1 1 | |
# 2 8 | |
# 3 15 | |
# 4 22 | |
# 5 29 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment