### Example: Path Expansion with Begin Sequence at Start Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths using a sequence, starting the matching of the sequence one node away from the initial start node. ```cypher MATCH (startNode {name: 'A'}) CALL apoc.path.expandConfig(startNode, {sequence: 'Person>KNOWS>', beginSequenceAtStart: false}) YIELD path RETURN path ``` -------------------------------- ### Example: Path Expansion with Filter Start Node Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, applying the label filter 'Company' to the start node itself. ```cypher MATCH (startNode:Company {name: 'A'}) CALL apoc.path.expandConfig(startNode, {filterStartNode: true, labelFilter: 'Company'}) YIELD path RETURN path ``` -------------------------------- ### Example: Path Expansion with Allowlist Nodes Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, but only allows nodes present in the 'allowedNodes' list to be part of the path. ```cypher MATCH (startNode {name: 'A'}), (n1 {name: 'N1'}), (n2 {name: 'N2'}) CALL apoc.path.expandConfig(startNode, {allowlistNodes: [n1, n2]}) YIELD path RETURN path ``` -------------------------------- ### Setup Sample Graph for Neighbor Search Source: https://neo4j.com/docs/apoc/current/graph-querying/neighborhood This Cypher query sets up a sample graph with Person nodes and FOLLOWS/KNOWS relationships, used for demonstrating neighbor search examples. ```cypher MERGE (mark:Person {name: "Mark"}) MERGE (praveena:Person {name: "Praveena"}) MERGE (joe:Person {name: "Joe"}) MERGE (lju:Person {name: "Lju"}) MERGE (michael:Person {name: "Michael"}) MERGE (emil:Person {name: "Emil"}) MERGE (ryan:Person {name: "Ryan"}) MERGE (ryan)-[:FOLLOWS]->(joe) MERGE (joe)-[:FOLLOWS]->(mark) MERGE (mark)-[:FOLLOWS]->(emil) MERGE (michael)-[:KNOWS]-(emil) MERGE (michael)-[:KNOWS]-(lju) MERGE (michael)-[:KNOWS]-(praveena) MERGE (emil)-[:FOLLOWS]->(joe) MERGE (praveena)-[:FOLLOWS]->(joe) ``` -------------------------------- ### Example: Path Expansion with Optional Path Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, yielding null if no paths are found, rather than filtering out the row. ```cypher MATCH (startNode {name: 'A'}) CALL apoc.path.expandConfig(startNode, {optional: true}) YIELD path RETURN path ``` -------------------------------- ### Example: Path Expansion with Denylist Nodes Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, excluding any paths that contain nodes present in the 'deniedNodes' list. ```cypher MATCH (startNode {name: 'A'}), (d1 {name: 'D1'}), (d2 {name: 'D2'}) CALL apoc.path.expandConfig(startNode, {denylistNodes: [d1, d2]}) YIELD path RETURN path ``` -------------------------------- ### Example: Path Expansion with Termination Nodes Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, but only returns paths that end at nodes with the label 'Target'. ```cypher MATCH (startNode {name: 'A'}), (targetNode {name: 'B'}) CALL apoc.path.expandConfig(startNode, {terminatorNodes: [targetNode]}) YIELD path RETURN path ``` -------------------------------- ### Example XML Structure Source: https://neo4j.com/docs/apoc/current/import/load-xml This is an example of the XML structure for book data, used in subsequent import examples. ```xml Gambardella, Matthew XML Developer's Guide Computer 44.95 2000-10-01 An in-depth look at creating applications with XML. Ralls, Kim Midnight Rain Fantasy 5.95 2000-12-16 A former architect battles corporate zombies, ... ``` -------------------------------- ### Example: Basic Path Expansion with Depth Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, traversing relationships up to a maximum depth of 3. Uses default relationship types and labels. ```cypher MATCH (startNode {name: 'A'}) CALL apoc.path.expandConfig(startNode, {maxLevel: 3}) YIELD path RETURN path ``` -------------------------------- ### Install Trigger Source: https://neo4j.com/docs/apoc/current/deprecations-and-additions Installs a trigger for a given database that is invoked upon successful transaction. ```cypher CALL apoc.trigger.install(databaseName STRING, name STRING, statement STRING, selector MAP, config MAP) ``` -------------------------------- ### Example: Path Expansion with Uniqueness Strategy Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, using the 'NODE_GLOBAL' uniqueness strategy to avoid revisiting nodes across all paths. ```cypher MATCH (startNode {name: 'A'}) CALL apoc.path.expandConfig(startNode, {uniqueness: 'NODE_GLOBAL'}) YIELD path RETURN path ``` -------------------------------- ### Example JSON Path Syntax Source: https://neo4j.com/docs/apoc/current/import/load-json This example demonstrates how to extract an array of tags from the first item in a list of items, using a common JSON path expression. ```jsonpath $.items[0].tags ``` -------------------------------- ### Example: Path Expansion with Label Filters Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, ensuring all traversed nodes have the label 'Person', up to a maximum depth of 4. ```cypher MATCH (startNode {name: 'A'}) CALL apoc.path.expandConfig(startNode, {maxLevel: 4, labelFilter: 'Person'}) YIELD path RETURN path ``` -------------------------------- ### Install Trigger with Time Parameters Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Installs a trigger that sets the 'time' property of newly created nodes to the current timestamp. It demonstrates passing custom parameters to a trigger. ```cypher CALL apoc.trigger.install('neo4j', 'timeParams', "UNWIND $createdNodes AS n SET n.time = $time", {}, {params: {time: timestamp()}}) ; ``` -------------------------------- ### Sample Graph Setup Source: https://neo4j.com/docs/apoc/current/overview/apoc.diff/apoc.diff.nodes This snippet sets up a sample graph with two Person nodes, Joe and Ryan, for use in demonstrating the apoc.diff.nodes procedure. ```cypher MERGE (joe:Person {name: "Joe", dateOfBirth: datetime("1981-09-02")}) MERGE (ryan:Person {name: "Ryan", twitter: "@ryguyrg"}); ``` -------------------------------- ### List All Installed Triggers Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Lists all triggers currently installed for the session's database. ```cypher CALL apoc.trigger.list() ``` -------------------------------- ### Example XML Structure (books.xml) Source: https://neo4j.com/docs/apoc/current/import/load-xml This is a smaller XML file containing two book entries, used for demonstrating the `apoc.load.xml` procedure. ```xml Gambardella, Matthew Arciniegas, Fabio XML Developer's Guide Computer 44.95 2000-10-01 An in-depth look at creating applications with XML. Ralls, Kim Midnight Rain Fantasy 5.95 2000-12-16 A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. ``` -------------------------------- ### Expand Paths with Label Filter and Length Constraints Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Use `apoc.path.expandConfig` to find paths from a starting node with specific label patterns and length constraints. The example filters for paths where nodes alternate between having and not having the 'Field' label, with a minimum of 2 and a maximum of 4 hops. It then filters for even-length paths and returns the nodes (excluding the start node) and their hop count. ```cypher MATCH (p:Person {name: "Praveena"}) CALL apoc.path.expandConfig(p, { labelFilter: "+Field,-Field", beginSequenceAtStart: false, minLevel: 2, maxLevel: 4 }) YIELD path WHERE length(path) % 2 = 0 // Remove the Praveena node from the returned path RETURN nodes(path)[1..] AS nodes, length(path) AS hops ORDER BY hops; ``` -------------------------------- ### Example: Moving a Property to a Label Source: https://neo4j.com/docs/apoc/current/graph-refactoring/property-value-label This example demonstrates how to create a `Movie` node, then use `apoc.create.addLabels` to move the 'genre' property to a label, and finally remove the 'genre' property from the node. ```APIDOC ## Example: Moving a Property to a Label ### Create Initial Node ```cypher CREATE (:Movie {title: 'A Few Good Men', genre: 'Drama'}) ``` ### Move Property to Label and Remove Property ```cypher MATCH (n:Movie) CALL apoc.create.addLabels( id(n), [ n.genre ] ) YIELD node REMOVE node.genre RETURN node ``` ``` -------------------------------- ### Show Triggers Source: https://neo4j.com/docs/apoc/current/deprecations-and-additions Lists all installed triggers for a given database. ```cypher CALL apoc.trigger.show(databaseName STRING) ``` -------------------------------- ### Create Sample Graph Data Source: https://neo4j.com/docs/apoc/current/overview/apoc.any/apoc.any.properties Creates sample student nodes with names and scores for use in subsequent examples. ```cypher CREATE (s:Student {name: 'Alice', score: 71}); CREATE (s:Student {name: 'Mark', score: 95}); CREATE (s:Student {name: 'Andrea', score: 86}); CREATE (s:Student {name: 'Rajesh', score: 89}); CREATE (s:Student {name: 'Jennifer', score: 96}); CREATE (s:Student {name: 'Katarina', score: 80}); ``` -------------------------------- ### Example GraphML Output Source: https://neo4j.com/docs/apoc/current/export/graphml This is an example of the GraphML file structure generated by APOC for a simple movie and person dataset. ```xml :MovieThe MatrixWelcome to the Real World1999 :Person1967Lilly Wachowski :Person1965Lana Wachowski DIRECTED DIRECTED ``` -------------------------------- ### Install Trigger to Log Deleted Nodes Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Installs a trigger named 'createLogNodeOnDelete' that runs after an asynchronous event. It creates a 'Log' node, assigns the labels of the deleted node, and copies its properties using `apoc.any.properties`. ```cypher CALL apoc.trigger.install('neo4j', 'createLogNodeOnDelete', "\n UNWIND $deletedNodes as deletedNode\n CREATE (log:Log) __**(1)**\n SET log:$(labels(deletedNode)) __**(2)**\n SET log += apoc.any.properties(deletedNode) __**(3)**\n ", {phase: 'afterAsync'}); ``` -------------------------------- ### Import Neo4j Movie Dataset Source: https://neo4j.com/docs/apoc/current/overview/apoc.example/apoc.example.movies Call this procedure to populate your database with the example movie dataset. It returns metadata about the import. ```cypher CALL apoc.example.movies(); ``` -------------------------------- ### Install a New Trigger Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Installs a new trigger that executes a Cypher statement when a successful transaction occurs. The trigger is named and can be configured with a selector and specific settings. ```cypher CALL apoc.trigger.install("myDb", "myTrigger", "RETURN true", {phase: "before"}, {config: "value"}) ``` -------------------------------- ### apoc.path.create Source: https://neo4j.com/docs/apoc/current/graph-querying/path-querying Creates a PATH from a given start NODE and a LIST of RELATIONSHIPs. ```APIDOC ## apoc.path.create ### Description Creates a PATH from a given start NODE and a LIST of RELATIONSHIPs. ### Signature apoc.path.create(startNode NODE, rels LIST) ### Returns - PATH: A newly created path. ``` -------------------------------- ### Install Trigger to Create Relationships on New Actor Nodes Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Installs a trigger named 'create-rel-new-node' that creates an ACT_IN relationship to a specific movie for newly created Actor nodes with predefined names. ```cypher CALL apoc.trigger.install('neo4j','create-rel-new-node', "\n UNWIND $createdNodes AS n\n MATCH (m:Movie {title:'Matrix'})\n WHERE n:Actor AND n.name IN ['Keanu Reeves','Laurence Fishburne','Carrie-Anne Moss']\n CREATE (n)-[:ACT_IN]->(m)\n ", {phase:'before'} ) ``` ```cypher CREATE (k:Actor {name:'Keanu Reeves'}) CREATE (l:Actor {name:'Laurence Fishburne'}) CREATE (c:Actor {name:'Carrie-Anne Moss'}) CREATE (a:Actor {name:'Tom Hanks'}) CREATE (m:Movie {title:'Matrix'}) ``` -------------------------------- ### Create a Movie Node Source: https://neo4j.com/docs/apoc/current/graph-refactoring/property-value-label This snippet demonstrates creating a basic node with properties. It serves as a prerequisite for the label transformation example. ```cypher CREATE (:Movie {title: 'A Few Good Men', genre: 'Drama'}) ``` -------------------------------- ### Import GraphML from URL Source: https://neo4j.com/docs/apoc/current/import/import-graphml Example of importing a GraphML file directly from a URL. ```APIDOC ## Import simple GraphML file from URL ### Description Imports a graph based on the `simple.graphml` file located at a given URL. ### Method CALL ### Endpoint apoc.import.graphml ### Parameters - **urlOrBinaryFile** (string) - Required - "http://graphml.graphdrawing.org/primer/simple.graphml" - **config** (MAP) - Optional - `{}` ### Request Example ```cypher CALL apoc.import.graphml("http://graphml.graphdrawing.org/primer/simple.graphml", {}) ``` ### Response #### Success Response Returns a table with import statistics. #### Response Example ``` | source | source | format | nodes | relationships | properties | time | rows | batchSize | batches | done | data | |--------------------------------------------|--------|---------|-------|---------------|------------|-------|------|-----------|---------|-------|------| | "http://graphml.graphdrawing.org/primer/simple.graphml" | "file" | "graphml" | 11 | 12 | 0 | 618 | 0 | -1 | 0 | TRUE | NULL | ``` ``` -------------------------------- ### apoc.trigger.show Source: https://neo4j.com/docs/apoc/current/overview Lists all eventually installed triggers for a database. ```APIDOC ## apoc.trigger.show ### Description Lists all eventually installed triggers for a database. ### Procedure Signature apoc.trigger.show(databaseName STRING) ### Notes Admin Only. ``` -------------------------------- ### Install a Trigger for 'after' Phase Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Installs a trigger named 'name' that executes after a commit. It assigns the transaction ID to newly created nodes. Note: Modifying entities in the 'after' phase is not supported and will result in an exception. ```cypher CALL apoc.trigger.install('neo4j', 'name', "UNWIND $createdNodes AS n SET n.txId = $transactionId'", {phase:'after'} ); CREATE (f:Baz); ``` -------------------------------- ### apoc.rel.startNode Source: https://neo4j.com/docs/apoc/current/overview Returns the start node for a given virtual relationship. ```APIDOC ## apoc.rel.startNode ### Description Returns the start NODE for the given virtual RELATIONSHIP. ### Method RETURN ### Endpoint apoc.rel.startNode(rel RELATIONSHIP) ### Parameters #### Path Parameters - **rel** (RELATIONSHIP) - The virtual relationship. ``` -------------------------------- ### GraphML File Structure Source: https://neo4j.com/docs/apoc/current/import/import-graphml This is an example of a simple GraphML file structure. It defines nodes and edges for a graph. ```xml ``` -------------------------------- ### Fast Node-Counts by Label Example Source: https://neo4j.com/docs/apoc/current/cypher-execution/running-cypher Demonstrates how to efficiently compute the number of nodes for specific labels using `apoc.cypher.run`. ```APIDOC CALL db.labels() yield label CALL apoc.cypher.run("match (:`"+label+"`) return count(*) as count", null) yield value return label, value.count as count ``` -------------------------------- ### Example APOC Initializer Configurations Source: https://neo4j.com/docs/apoc/current/operational Illustrates how to configure APOC initializers for different databases and tasks. Ensure Cypher commands are idempotent using constructs like 'IF NOT EXISTS' and 'MERGE'. ```text apoc.initializer.system=CREATE USER dummy IF NOT EXISTS SET PASSWORD 'abc' ``` ```text apoc.initializer.neo4j.0=CREATE INDEX person_index IF NOT EXISTS FOR (p:Person) ON (p.name) ``` ```text apoc.initializer.neo4j.1=MERGE (:Person{name:'foo'}) ``` ```text apoc.initializer.neo4j.2=MERGE (:Person{name:'bar'}) ``` -------------------------------- ### Show Triggers for a Specific Database Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Lists all installed triggers for a specified database. ```cypher CALL apoc.trigger.show("myDb") ``` -------------------------------- ### Example JSON Output of Exported Relationship Source: https://neo4j.com/docs/apoc/current/export/json This is an example of the JSON structure generated by exporting a 'KNOWS' relationship. It includes the relationship details and the properties of the start and end nodes. ```json {"rel":{"id":"0","type":"relationship","label":"KNOWS","properties":{"bffSince":"P5M1DT12H","since":1993},"start":{"id":"0","labels":["User"],"properties":{"born":"2015-07-04T19:32:24","name":"Adam","place":{"crs":"wgs-84","latitude":13.1,"longitude":33.46789,"height":null},"age":42,"male":true,"kids":["Sam","Anna","Grace"]}},"end":{"id":"1","labels":["User"],"properties":{"name":"Jim","age":42}}}} ``` -------------------------------- ### Create Virtual Node with All Config Options Source: https://neo4j.com/docs/apoc/current/overview/apoc.create/apoc.create.virtual.fromNode Demonstrates combining `wrapNodeIds`, `additionalLabels`, and `additionalProperties` for comprehensive virtual node creation. ```cypher MATCH (a:Account {accountNumber: 101010101}) RETURN apoc.create.virtual.fromNode(a, ['type', 'bank'], { wrapNodeIds: true, additionalLabels: ['Fraud'], additionalProperties: { risk: 'high' } }) AS node; ``` -------------------------------- ### Import GraphML from Local File Source: https://neo4j.com/docs/apoc/current/import/import-graphml Example of importing a GraphML file from the Neo4j import directory after enabling file imports. ```APIDOC ## Import GraphML from local file ### Description Imports a graph based on the `simple.graphml` file located in the Neo4j import directory. Requires `apoc.import.file.enabled=true` in `apoc.conf`. ### Method CALL ### Endpoint apoc.import.graphml ### Parameters - **urlOrBinaryFile** (string) - Required - "file://simple.graphml" - **config** (MAP) - Optional - `{}` ### Request Example ```cypher CALL apoc.import.graphml("file://simple.graphml", {}) ``` ``` -------------------------------- ### Create Sample Data Source: https://neo4j.com/docs/apoc/current/overview/apoc.export/apoc.export.json.graph Creates a small graph dataset for demonstration purposes. ```cypher CREATE (:Person {name: 'Alice', age: 30})-[:KNOWS {since: 2019}]->(:Person {name: 'Bob', age: 25}) ``` -------------------------------- ### Create Sample Graph for Property Updates Source: https://neo4j.com/docs/apoc/current/graph-updates/data-creation Creates a sample graph with nodes and relationships, including properties. This serves as a basis for demonstrating dynamic property setting. ```cypher CREATE (jennifer:Person {name: "Jennifer", community: 1, partition: 4}) CREATE (karin:Person {name: "Karin", community: 4, partition: 2}) CREATE (elaine:Person {name: "Elaine", community: 3, partition: 3}) MERGE (jennifer)-[:FRIENDS {since: datetime("2019-06-01")}]-(karin) MERGE (jennifer)-[:FRIENDS {since: datetime("2019-05-04")}]-(elaine) ``` -------------------------------- ### Create Sample Graph for APOC Convert Examples Source: https://neo4j.com/docs/apoc/current/overview/apoc.convert/apoc.convert.toTree Sets up a sample graph with Persons and Movies, including relationships like ACTED_IN and DIRECTED, used for demonstrating APOC procedures. ```cypher CREATE (Keanu:Person {name:'Keanu Reeves', born:1964}) CREATE (TomH:Person {name:'Tom Hanks', born:1956}) CREATE (TomT:Person {name:'Tom Tykwer', born:1965}) CREATE (JamesThompson:Person {name:'James Thompson'}) CREATE (TheMatrix:Movie {title:'The Matrix', released:1999, tagline:'Welcome to the Real World'}) CREATE (TheMatrixReloaded:Movie {title:'The Matrix Reloaded', released:2003, tagline:'Free your mind'}) CREATE (TheMatrixRevolutions:Movie {title:'The Matrix Revolutions', released:2003, tagline:'Everything that has a beginning has an end'}) CREATE (SomethingsGottaGive:Movie {title:"Something's Gotta Give", released:2003}) CREATE (TheDevilsAdvocate:Movie {title:"The Devil's Advocate", released:1997, tagline:'Evil has its winning ways'}) CREATE (YouveGotMail:Movie {title:"You've Got Mail", released:1998, tagline:'At odds in life... in love on-line.'}) CREATE (SleeplessInSeattle:Movie {title:'Sleepless in Seattle', released:1993, tagline:'What if someone you never met, someone you never saw, someone you never knew was the only someone for you?'}) CREATE (ThatThingYouDo:Movie {title:'That Thing You Do', released:1996, tagline:'In every life there comes a time when that thing you dream becomes that thing you do'}) CREATE (CloudAtlas:Movie {title:'Cloud Atlas', released:2012, tagline:'Everything is connected'}) CREATE (Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrix) CREATE (Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrixReloaded) CREATE (Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrixRevolutions) CREATE (Keanu)-[:ACTED_IN {roles:['Julian Mercer']}]->(SomethingsGottaGive) CREATE (Keanu)-[:ACTED_IN {roles:['Kevin Lomax']}]->(TheDevilsAdvocate) CREATE (TomH)-[:ACTED_IN {roles:['Joe Fox']}]->(YouveGotMail) CREATE (TomH)-[:ACTED_IN {roles:['Sam Baldwin']}]->(SleeplessInSeattle) CREATE (TomH)-[:ACTED_IN {roles:['Mr. White']}]->(ThatThingYouDo) CREATE (TomH)-[:ACTED_IN {roles:['Zachry', 'Dr. Henry Goose', 'Isaac Sachs', 'Dermot Hoggins']}]->(CloudAtlas) CREATE (TomT)-[:DIRECTED]->(CloudAtlas) CREATE (JamesThompson)-[:REVIEWED {summary:'Enjoyed it!', rating:95}]->(TheMatrix) CREATE (JamesThompson)-[:REVIEWED {summary:'It was alright.', rating:65}]->(TheMatrixReloaded) CREATE (JamesThompson)-[:REVIEWED {summary:'The best of the three', rating:100}]->(TheMatrixRevolutions); ``` -------------------------------- ### Example: Path Expansion with Specific Relationship Types Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths from a start node, only traversing 'FRIENDS' or 'COLLEAGUES' relationships in any direction, up to a maximum depth of 2. ```cypher MATCH (startNode {name: 'A'}) CALL apoc.path.expandConfig(startNode, {maxLevel: 2, relationshipFilter: 'FRIENDS|COLLEAGUES'}) YIELD path RETURN path ``` -------------------------------- ### Create Sample Nodes Source: https://neo4j.com/docs/apoc/current/graph-updates/atomic-updates These statements create sample nodes with various properties to demonstrate atomic updates. ```cypher CREATE (p:Person {name:'Tom',age: 40}) CREATE (p:Person {name:'Will',age: 35}) CREATE (p:Person {name:'David', children: ['Anne','Sam','Paul']}) CREATE (p:Person {name:'John', cars: ['Class A','X3','Focus']}) CREATE (p:Person {name:'Ryan', salary1:1800, salary2:1500}) ``` -------------------------------- ### Create Sample Graph for Node Merging Source: https://neo4j.com/docs/apoc/current/graph-refactoring/merge-nodes Creates a sample graph with several nodes and relationships, including some with the same start and end nodes, to demonstrate node merging. ```cypher CREATE (n1:Person {name:'Tom'}), (n2:Person {name:'John'}), (n3:Company {name:'Company1'}), (n5:Car {brand:'Ferrari'}), (n6:Animal:Cat {name:'Derby'}), (n7:City {name:'London'}), (n1)-[:WORKS_FOR {since:2015}]->(n3), (n2)-[:WORKS_FOR {since:2018}]->(n3), (n3)-[:HAS_HQ {since:2004}]->(n7), (n1)-[:DRIVE {since:2017}]->(n5), (n2)-[:HAS {since:2013}]->(n6); return * ``` -------------------------------- ### Slice a collection of movies by release year Source: https://neo4j.com/docs/apoc/current/overview/apoc.agg/apoc.agg.slice This example demonstrates how to use apoc.agg.slice to get the first 3 movies for each person, ordered by release year. It assumes a graph with Person and Movie nodes and ACTED_IN relationships. ```cypher MATCH (p:Person)-[:ACTED_IN]->(movie) WITH p, movie ORDER BY p, movie.released RETURN p.name AS person, apoc.agg.slice(movie, 0, 3) AS movies ``` -------------------------------- ### Download and Mount APOC for Production Source: https://neo4j.com/docs/apoc/current/installation This sequence downloads the APOC JAR file into a local 'plugins' directory and then runs a Neo4j Docker container, mounting this directory to the container's /plugins path. This is recommended for production environments. ```bash mkdir plugins pushd plugins wget https://github.com/neo4j/apoc/releases/download/2026.05.0/apoc-2026.05.0-core.jar popd docker run --rm -e NEO4J_AUTH=none -p 7474:7474 -v $PWD/plugins:/plugins -p 7687:7687 neo4j:2025.05 ``` -------------------------------- ### Setup for Importing Cypher Statements Source: https://neo4j.com/docs/apoc/current/overview/apoc.export/apoc.export.cypher.graph Provides the necessary Cypher statements to set up constraints and import data, typically used before importing exported Cypher statements. ```cypher :begin CREATE CONSTRAINT uniqueConstraint FOR (node:`UNIQUE IMPORT LABEL`) REQUIRE (node.`UNIQUE IMPORT ID`) IS UNIQUE; :commit :begin UNWIND [{_id:31450, properties:{tagline:"Welcome to the Real World", title:"The Matrix", released:1999}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Movie; UNWIND [{_id:31457, properties:{born:1952, name:"Joel Silver"}}] AS row CREATE (n:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row._id}) SET n += row.properties SET n:Person; :commit :begin UNWIND [{start: {_id:31457}, end: {_id:31450}, properties:{}}] AS row MATCH (start:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.start._id}) MATCH (end:`UNIQUE IMPORT LABEL`{`UNIQUE IMPORT ID`: row.end._id}) CREATE (start)-[r:PRODUCED]->(end) SET r += row.properties; :commit :begin MATCH (n:`UNIQUE IMPORT LABEL`) WITH n LIMIT 20000 REMOVE n:`UNIQUE IMPORT LABEL` REMOVE n.`UNIQUE IMPORT ID`; :commit :begin DROP CONSTRAINT uniqueConstraint; :commit ``` -------------------------------- ### Example Data Creation Source: https://neo4j.com/docs/apoc/current/export/cypher This Cypher snippet demonstrates how to create a dataset with multiple relationships of the same type ('WORKS_FOR') between a Person and a Project node, along with other relationship types. ```cypher create (pers:Person {name: 'MyName'})-[:WORKS_FOR {id: 1}]->(proj:Project {a: 1}), (pers)-[:WORKS_FOR {id: 2}]->(proj), (pers)-[:WORKS_FOR {id: 2}]->(proj), (pers)-[:WORKS_FOR {id: 3}]->(proj), (pers)-[:WORKS_FOR {id: 4}]->(proj), (pers)-[:WORKS_FOR {id: 5}]->(proj), (pers)-[:IS_TEAM_MEMBER_OF {name: 'aaa'}]->(:Team {name: 'one'}), (pers)-[:IS_TEAM_MEMBER_OF {name: 'eee'}]->(:Team {name: 'two'}) ``` -------------------------------- ### Create Initial Nodes Source: https://neo4j.com/docs/apoc/current/graph-refactoring/clone-nodes Creates two initial nodes, Foo and Bar, for demonstration purposes. ```cypher CREATE (f:Foo{name:'Foo'}),(b:Bar{name:'Bar'}) ``` -------------------------------- ### Create Sample Data Source: https://neo4j.com/docs/apoc/current/overview/apoc.export/apoc.export.arrow.stream.query This snippet creates a sample dataset including users with various properties and relationships. It's used to demonstrate the export functionality. ```cypher CREATE (f:User {name:'Adam',age:42,male:true,kids:['Sam','Anna','Grace'], born:localdatetime('2015185T19:32:24'), place:point({latitude: 13.1, longitude: 33.46789})})-[:KNOWS {since: 1993, bffSince: duration('P5M1.5D')}]->(b:User {name:'Jim',age:42}),(c:User {name: 'John', age:12}),(d:Another {foo: 'bar'}) ``` -------------------------------- ### Create a Sample Graph Source: https://neo4j.com/docs/apoc/current/graph-refactoring/extract-node-from-relationship This Cypher query creates a simple graph with two nodes, 'Foo' and 'Bar', connected by a 'FOOBAR' relationship. This serves as the initial state for the refactoring example. ```cypher CREATE (f:Foo)-[rel:FOOBAR {a:1}]->(b:Bar) ``` -------------------------------- ### Make a GET request to the Wikipedia Action API Source: https://neo4j.com/docs/apoc/current/import/load-json Fetches data from the Wikipedia Action API using a GET request. Explicitly sets the HTTP method to GET and uses JSON Path to extract specific data. The URL needs to be properly encoded. ```cypher CALL apoc.load.jsonParams("https://en.wikipedia.org/w/api.php?action=query&titles=Neo4j&format=json&formatversion=2", {method: "GET"}, "", ".query.pages[0]") YIELD value RETURN value ``` ```cypher WITH apoc.text.urlencode("Auvergne-Rhône-Alpes") AS title CALL apoc.load.jsonParams("https://en.wikipedia.org/w/api.php?action=query&titles="+title+"&format=json&formatversion=2", {method: "GET"}, "", ".query.pages[0]") YIELD value RETURN value.title AS title, value.pageid AS pageid ``` -------------------------------- ### CSV Output Example Source: https://neo4j.com/docs/apoc/current/overview/apoc.export/apoc.export.csv.all This is an example of the CSV output generated by APOC. It shows the structure for nodes and relationships, including internal Neo4j properties. ```csv "_id","_labels","baz","foo","_start","_end","_type" "0",":Sample:User","",,, "1",":Sample:User","",,, "2",":Sample:User","","bar",,, "3",":Sample:User","baa","true",,, ,,,,"2","3","KNOWS" ``` -------------------------------- ### GraphML Output Example Source: https://neo4j.com/docs/apoc/current/export/graphml An example of the GraphML XML structure generated by APOC export. This format is useful for interoperability with other graph visualization tools. ```xml :Movie The Matrix Welcome to the Real World 1999 :Person 1964 Keanu Reeves :Person 1967 Carrie-Anne Moss :Person 1961 Laurence Fishburne :Person 1960 Hugo Weaving :Person 1967 Lilly Wachowski :Person 1965 Lana Wachowski :Person 1952 Joel Silver ACTED_IN ["Neo"] ACTED_IN ["Trinity"] ACTED_IN ["Morpheus"] ACTED_IN ["Agent Smith"] DIRECTED DIRECTED PRODUCED ``` -------------------------------- ### Create a Sample Graph Dataset Source: https://neo4j.com/docs/apoc/current/graph-refactoring/clone-subgraph This Cypher query sets up a graph with two distinct trees, each rooted by a 'Root' node. It defines multiple 'Node' nodes and establishes relationships between them to serve as a basis for subgraph cloning examples. ```cypher CREATE (rootA:Root{name:'A'}) (rootB:Root{name:'B'}) (n1:Node{name:'node1', id:1}) (n2:Node{name:'node2', id:2}) (n3:Node{name:'node3', id:3}) (n4:Node{name:'node4', id:4}) (n5:Node{name:'node5', id:5}) (n6:Node{name:'node6', id:6}) (n7:Node{name:'node7', id:7}) (n8:Node{name:'node8', id:8}) (n9:Node{name:'node9', id:9}) (n10:Node{name:'node10', id:10}) (n11:Node{name:'node11', id:11}) (n12:Node{name:'node12', id:12}) CREATE (rootA)-[:LINK]->(n1)-[:LINK]->(n2)-[:LINK]->(n3)-[:LINK]->(n4) CREATE (n1)-[:LINK]->(n5)-[:LINK]->(n6)<-[:LINK]-(n7) CREATE (n5)-[:LINK]->(n8) CREATE (n5)-[:LINK]->(n9)-[:DIFFERENT_LINK]->(n10) CREATE (rootB)-[:LINK]->(n11) View all (4 more lines) ``` -------------------------------- ### APOC Installation Output in Docker Logs Source: https://neo4j.com/docs/apoc/current/installation These log lines indicate that the APOC plugin is being fetched and installed within the Neo4j Docker container. ```text Fetching versions.json for Plugin 'apoc' from https://neo4j.github.io/apoc/versions.json Installing Plugin 'apoc' from https://github.com/neo4j/apoc/releases/download/2026.05.0/apoc-2026.05.0-core.jar to /plugins/apoc.jar ``` -------------------------------- ### Example: Path Expansion with BFS Traversal Source: https://neo4j.com/docs/apoc/current/graph-querying/expand-paths-config Expands paths using Breadth-First Search (BFS) to find the shortest paths first, up to a maximum depth of 5. ```cypher MATCH (startNode {name: 'A'}) CALL apoc.path.expandConfig(startNode, {bfs: true, maxLevel: 5}) YIELD path RETURN path ``` -------------------------------- ### Example APOC Dependency Warning Source: https://neo4j.com/docs/apoc/current/installation This is an example of a warning message that may appear in the debug log if additional JARs for specific APOC functionalities (like S3 or HDFS) are not included and the functionality is not needed. ```text Failed to load `apoc.util.s3.S3URLConnection` ``` -------------------------------- ### Create Sample Graph Data Source: https://neo4j.com/docs/apoc/current/overview/apoc.create/apoc.create.vRelationship This code block sets up the initial graph data used in the examples, including students, test scores, and levels. ```cypher CREATE (s1:Student {name: 'Priya'}) CREATE (s2:Student {name: 'Joachim'}) CREATE (s3:Student {name: 'Dominic'}) CREATE (s4:Student {name: 'Amir'}) CREATE (s5:Student {name: 'Natasha'}) CREATE (s6:Student {name: 'Elena'}) CREATE (t1:TestScore {score: 87}) CREATE (t2:TestScore {score: 90}) CREATE (t3:TestScore {score: 78}) CREATE (t4:TestScore {score: 84}) CREATE (t5:TestScore {score: 76}) CREATE (t6:TestScore {score: 92}) CREATE (a:Level {level: 'beginner'}) CREATE (b:Level {level: 'intermediate'}) CREATE (c:Level {level: 'advanced'}) MERGE (s1)-[:HAS]->(t1)-[:ASSIGNED_TO]->(b) MERGE (s2)-[:HAS]->(t2)-[:ASSIGNED_TO]->(c) MERGE (s3)-[:HAS]->(t3)-[:ASSIGNED_TO]->(a) MERGE (s4)-[:HAS]->(t4)-[:ASSIGNED_TO]->(b) MERGE (s5)-[:HAS]->(t5)-[:ASSIGNED_TO]->(a) MERGE (s6)-[:HAS]->(t6)-[:ASSIGNED_TO]->(c); ``` -------------------------------- ### Install Multiple APOC Triggers Source: https://neo4j.com/docs/apoc/current/background-operations/triggers Installs several APOC triggers for different purposes: setting a timestamp, converting a name to lowercase, adding transaction info, and counting removed relationships of type 'X'. ```cypher CALL apoc.trigger.install('neo4j', 'timestamp', "UNWIND $createdNodes AS n SET n.ts = timestamp()", {}); CALL apoc.trigger.install('neo4j', 'lowercase', "UNWIND $createdNodes AS n SET n.id = toLower(n.name)", {}); CALL apoc.trigger.install('neo4j', 'txInfo', "UNWIND $createdNodes AS n SET n.txId = $transactionId, n.txTime = $commitTime", {phase:'after'}); CALL apoc.trigger.install('neo4j', 'count-removed-rels', "MATCH (c:Counter) SET c.count = c.count + size([r IN $deletedRelationships WHERE type(r) = \"X\"])", {}) ``` -------------------------------- ### Create a sample graph with a relationship Source: https://neo4j.com/docs/apoc/current/graph-refactoring/invert-relationship Creates a graph with two nodes, a Car and a Person, connected by a DRIVES relationship. This sets up the initial state for the inversion example. ```cypher CREATE path=(c:Car {make:"Volvo"})-[rel:DRIVES {year:2001}]->(p:Person {name:"Dan"}) RETURN path ```