Search code examples
neo4jcypher

How to get data from a property with a JSON document embedded using Cypher


I have the following case: I have some information stored in Neo4j. One property store a JSON document, and I would like to get the information inside this JSON document. I have retrieved the data, even the JSON field using MATCH:

MATCH (n:Node) RETURN n.id, n.nodeInfo as JSONInfo

JSONInfo (which is a property of Node), has the JSON Information:

{ 
   "TIMESTAMP":"2018-03-11T04:58:24Z",
   "field1":"358716053191804",
   "field2":"732111149743974",
   "version_field", "3.9.1"
   "field3":"0",
   "field4":"0"
}

But, I just want to get field1, that has inside JSON property.

What is the best way to retrieve this field in the MATCH command?

Thanks in advance


Solution

  • First of all your example isn't valid JSON. Your version_field key and value should be separated by a colon, not a comma, and you need a comma after "3.9.1".

    {
       "TIMESTAMP":"2018-03-11T04:58:24Z",
       "field1":"358716053191804",
       "field2":"732111149743974",
       "version_field":"3.9.1",
       "field3":"0",
       "field4":"0"
    }
    

    Once that's fixed, and the field is valid JSON, you can use JSON conversion functions from APOC Procedures to do the conversion from a JSON object to a map, then just use dot notation to access map properties:

    MATCH (n:Node)
    RETURN apoc.convert.fromJsonMap(n.nodeInfo).field1 as field1
    

    Keep in mind that map properties in JSON map strings cannot be indexed, so the data within your JSON string property should be used for storage and retrieval, not for lookup.