Search code examples
jsonneo4jcypherneo4j-apoc

Get last element of array by parsing JSON with Neo4j APOC


Short task description: I need to get the last element of an array/list of one of the fields in nested JSON, here the input JSON file:

{
    "origin": [{
            "label": "Alcohol drinks",
            "tag": [],
            "type": "string",
            "xpath": []
        },
        {
            "label": "Wine",
            "tag": ["red", "white"],
            "type": "string",
            "xpath": ["Alcohol drinks"]
        },
        {
            "label": "Port wine",
            "tag": ["Portugal", "sweet", "strong"],
            "type": "string",
            "xpath": ["Alcohol drinks", "Wine"]
        },
        {
            "label": "Sandeman Cask 33",
            "tag": ["red", "expensive"],
            "type": "string",
            "xpath": ["Alcohol drinks", "Wine", "Port wine"]
        }
    ]
}

I need to get the last element of "xpath" field, in order to create relationship with appropriate "label". Here is the code, which creates connection to all elements mentioned in "xpath", I need just connection to the last one:

WITH "file:///D:/project/neo_proj/input.json" AS url 
CALL apoc.load.json(url) YIELD value 
UNWIND value.origin as or 
MERGE(label:concept{name:or.label}) 
ON CREATE SET label.type = or.type 
FOREACH(tagName IN or.tag | MERGE(tag:concept{name:tagName}) 
MERGE (tag)-[r:link]-(label) 
ON CREATE SET r.Weight=1 
ON MATCH SET r.Weight=r.Weight+1)  
FOREACH(xpathName IN or.xpath | MERGE (xpath:concept{name:xpathName})
                                MERGE (label)-[r:link]-(xpath))

Probably there is something like:

apoc.agg.last(or.xpath)

which returns just an array of arrays or all "xpath" from all 4 records of "origin".

I will appreciate any help, probably there some workarounds (not necessary as I proposed) to solve this issue. Thank you in advance!

N.B. All this should be done from an app, not from within Neo4j browser.


Solution

  • Sounds like you're looking for the last() function? This will return the last element of a list.

    In this case, since you UNWIND the origin to 4 rows, you'll get the last element of the list for each of those rows.

    WITH "file:///D:/project/neo_proj/input.json" AS url 
    CALL apoc.load.json(url) YIELD value 
    UNWIND value.origin as or 
    RETURN last(or.xpath) as last