pythonneo4jcypher

Is it possible to dynamically set the label in cypher with UNWIND without using APOC?


Here's my query:

def create_entity_nodes(tx, report_id, entities):

    query = (
        "UNWIND $entities AS entity "
        "MATCH (report:Report {id: $report_id}) "
        "CREATE (entity.name:entity.type entity), "
        "(report)-[:OWNS]->(entity.name) "
        "(entity.name)-[:BELONGS_TO]->(report)"
        "RETURN report"
    )

I previously only did it with one entity in my code below and it worked. So, I wanted to try it with a list but I'm not sure if it's possible.

    entity_type = entity["type"]
    if not entity_type:
        raise ValueError("Entity type is required.")
    entity_type = entity_type[0].upper() + entity_type[1:].lower()
    entity.pop("type")
    query = (
        f"MATCH (report:Report {{id: $report_id}}) "
        f"CREATE ({entity['name']}:{entity_type} $props), "
        f"({entity['name']})-[:BELONGS_TO]->(report), "
        f"(report)-[:OWNS]->({entity['name']})"
        f"RETURN report"
    )
    result = tx.run(query, report_id=report_id, props=entity)

Solution

  • No, your first query won't work. At the moment, the only way to create labels dynamically is to build the query string as you did with your second query, or by using an apoc function like apoc.create.node.