How to handle dates in neo4j

Andreas Kuczera picture Andreas Kuczera · Mar 30, 2015 · Viewed 17.6k times · Source

I'm an historian of medieval history and I'm trying to code networks between kings, dukes, popes etc. over a period of time of about 50 years (from 1220 to 1270) in medieval Germany. As I'm not a specialist for graph-databases I'm looking for a possibility to handle dates and date-ranges.

Are there any possibilities to handle over a date-range to an edge so that the edges, which represents a relationship, disappears after e.g. 3 years?

Are there any possibility to ask for relationships who have their date-tag in a date-range?

Answer

Stefan Armbruster picture Stefan Armbruster · Mar 30, 2015

The common way to deal with dates in Neo4j is storing them either as a string representation or as millis since epoch (aka msec passed since Jan 01 1970).

The first approach makes the graph more easily readable the latter allows you to do math e.g. calculate deltas.

In your case I'd store two properties called validFrom and validTo on the relationships. You queries need to make sure you're looking for the correct time interval.

E.g. to find the king(s) in charge of France from Jan 01 1220 to Dec 31st 1221 you do:

MATCH (c:Country{name:'France'})-[r:HAS_KING]->(king)
WHERE r.validFrom >= -23667123600000 and r.validTo <=-23604051600000
RETURN king, r.validFrom, r.validTo

addendum

Since Neo4j 3.0 there's the APOC library which provides couple of functions for converting timestamps to/from human readable date strings.