### Setup commands for a new Rails project Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Setup.md A sequence of commands to initialize the project, install Neo4j, and generate a scaffold. ```bash rails new myapp -O -m https://raw.githubusercontent.com/neo4jrb/activegraph/master/docs/activegraph.rb cd myapp rake neo4j:install[community-4.0.6] db/neo4j/development/bin/neo4j-admin set-initial-password password rake neo4j:start rails generate scaffold User name:string email:string rake neo4j:migrate rails s open http://localhost:3000/users ``` -------------------------------- ### #start Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md The start method defines the starting points for a Cypher query. ```APIDOC ## START ### Description Specifies the starting points for the query using node lookups. ### Request Example ```ruby .start('r=node:nodes(name = "Brian")') # Cypher: START r=node:nodes(name = "Brian") ``` ``` -------------------------------- ### neo4j:start Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Starts the Neo4j server instance. ```APIDOC ## RAKE neo4j:start ### Description Starts the Neo4j server for the specified environment. ### Arguments - **environment** (string) - Required - The target environment. ### Example rake neo4j:start[development] ``` -------------------------------- ### Start query execution Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Use the start method to define the starting points for a Cypher query. ```ruby .start('r=node:nodes(name = "Brian")') ``` ```cypher START r=node:nodes(name = "Brian") ``` ```ruby .start(r: 'node:nodes(name = "Brian")') ``` ```cypher START r = node:nodes(name = "Brian") ``` -------------------------------- ### Start Neo4j Server (No Wait) Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Starts the Neo4j server using the 'start-no-wait' command for a specified environment. ```ruby rake neo4j:start_no_wait[development] ``` -------------------------------- ### Start Neo4j Server Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Starts the Neo4j server for a specified environment. Once started, the Neo4j web console can be accessed at http://localhost:7474. ```ruby rake neo4j:start[development] ``` -------------------------------- ### Initialize Vagrant Environment Source: https://github.com/neo4jrb/activegraph/blob/12/CONTRIBUTING.md Commands to start and access the development virtual machine. ```bash vagrant up ``` ```bash vagrant ssh ``` -------------------------------- ### Initialize a Query Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Start a new query from an existing session. ```ruby a_session.query ``` -------------------------------- ### neo4j:install Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Downloads and installs a specific version of Neo4j. ```APIDOC ## RAKE neo4j:install ### Description Downloads and installs Neo4j into the project directory. Supports community and enterprise editions. ### Arguments - **version** (string) - Required - Version string (e.g., community-latest, community-x.x.x). - **environment** (string) - Optional - The environment (default: development). ### Example rake neo4j:install[community-latest,development] ``` -------------------------------- ### Install Neo4j Test Database Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Testing.md Installs a Neo4j community edition for testing. Specify the version and database name. ```bash rake neo4j:install[community-latest,test] ``` ```bash rake neo4j:install[community-3.1.0,test] ``` -------------------------------- ### Install Sphinx Dependencies Source: https://github.com/neo4jrb/activegraph/blob/12/docs/README.md Required Python packages for building the documentation. ```bash pip3 install -U Sphinx ``` ```bash pip3 install sphinx_rtd_theme ``` -------------------------------- ### Install Neo4j Server Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Downloads and installs a specified version of Neo4j into the project directory. Supports community and enterprise editions, latest versions, or specific version numbers. A custom download URL can be set via the NEO4J_DIST environment variable. ```ruby rake neo4j:install[community-latest,development] ``` -------------------------------- ### Start Neo4j and Run Tests in Vagrant Source: https://github.com/neo4jrb/activegraph/blob/12/CONTRIBUTING.md Commands to be executed inside the Vagrant VM to prepare the database and run the test suite. ```bash rake neo4j:start ``` ```bash rspec ``` -------------------------------- ### Configure Neo4j connection Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Setup.md Examples for configuring the database connection via environment variables, YAML, or Rails config. ```bash NEO4J_URL=bolt://localhost:7687 ``` ```yaml development: url: neo4j://localhost:7687 test: url: neo4j://localhost:7688 production: url: - neo4j://core1:7687 - neo4j://core2:7687 - neo4j://core3:7687 username: neo4j password: password ``` ```ruby config.neo4j.driver.url = 'bolt://localhost:7687' ``` ```ruby config.neo4j.driver.url = 'neo4j://localhost:7687' config.neo4j.driver.username = 'neo4j' config.neo4j.driver.password = 'password' ``` ```ruby config.neo4j.driver.encryption = false ``` -------------------------------- ### Migration Class Example Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Define the `up` and `down` methods within a migration class to specify schema changes and their corresponding rollback steps. This example renames a property. ```ruby class RenameUserNameToFirstName < ActiveGraph::Migrations::Base def up rename_property :User, :name, :first_name end def down rename_property :User, :first_name, :name end end ``` -------------------------------- ### Generate a new Rails app with ActiveGraph Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Setup.md Use the -m flag to run the setup script and -O to exclude ActiveRecord. ```bash rails new myapp -O -m https://raw.githubusercontent.com/neo4jrb/activegraph/master/docs/activegraph.rb ``` -------------------------------- ### Setup ActiveGraph in non-Rails Ruby projects Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Setup.md Include the necessary gems and optional rake tasks in your Gemfile. ```ruby gem 'activegraph', '>= 10.0.0' # For example, see https://rubygems.org/gems/activegraph/versions for the latest versions gem 'neo4j-ruby-driver' # For example, see https://rubygems.org/gems/neo4j-ruby-driver/versions for the latest versions ``` ```ruby # Both are optional # To provide tasks to install/start/stop/configure Neo4j require 'active_graph/rake_tasks' # Comes from the `neo4j-rake_tasks` gem ``` -------------------------------- ### Chaining Scopes Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md Example of chaining multiple scopes for expressive queries. ```ruby # Getting all hybrid convertables owned by recently active eligible people Person.eligible.where(recently_active: true).cars.hybrids.convertables ``` -------------------------------- ### Match Clauses Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Examples of using the match method with various arguments to generate Cypher MATCH clauses. ```ruby .match('n') ``` ```ruby .match(:n) ``` ```ruby .match(n: Person) ``` ```ruby .match(n: 'Person') ``` ```ruby .match(n: ':Person') ``` ```ruby .match(n: :Person) ``` ```ruby .match(n: [:Person, "Animal"]) ``` ```ruby .match(n: ' :Person') ``` ```ruby .match(n: nil) ``` ```ruby .match(n: 'Person {name: "Brian"}') ``` ```ruby .match(n: {name: 'Brian', age: 33}) ``` ```ruby .match(n: {Person: {name: 'Brian', age: 33}}) ``` ```ruby .match('(n)--(o)') ``` ```ruby .match('(n)--(o)', '(o)--(p)') ``` ```ruby .match('(n)--(o)').match('(o)--(p)') ``` -------------------------------- ### ActiveGraph Migration Class Example Source: https://context7.com/neo4jrb/activegraph/llms.txt Defines a migration class with `up` and `down` methods for schema changes like adding constraints and indexes. ```ruby # db/neo4j/migrate/20240101000000_add_constraint_to_user.rb class AddConstraintToUser < ActiveGraph::Migrations::Base def up add_constraint :User, :email add_index :User, :name end def down drop_constraint :User, :email drop_index :User, :name end end ``` -------------------------------- ### Using Clauses Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Examples of using the using method to generate Cypher USING clauses for indexes and scans. ```ruby .using('INDEX m:German(surname)') ``` ```ruby .using('SCAN m:German') ``` ```ruby .using('INDEX m:German(surname)').using('SCAN m:German') ``` -------------------------------- ### Open Neo4j Shell Console Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Opens an interactive Neo4j shell console (REPL). If the server is not running, it will be started first and then shut down upon exiting the shell. ```ruby rake neo4j:shell[development] ``` -------------------------------- ### Querying with Enums Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md Examples of using the where method to query enum properties. ```ruby Media.where(type: :image) # => CYPHER: "MATCH (result_media:`Media`) WHERE (result_media.type = 0)" Media.where(type: [Media.types[:image], Media.types[:video]]) # => CYPHER: "MATCH (result_media:`StoredFile`) WHERE (result_media.type IN [0, 1])" Media.as(:m).where('m.type <> ?', Media.types[:image]) # => CYPHER: "MATCH (result_media:`StoredFile`) WHERE (result_media.type <> 0)" ``` -------------------------------- ### Install Overcommit Git Hooks Source: https://github.com/neo4jrb/activegraph/blob/12/CONTRIBUTING.md Configures pre-commit hooks to ensure code quality standards are met before committing. ```bash overcommit --install ``` -------------------------------- ### Install ActiveGraph in Rails Source: https://context7.com/neo4jrb/activegraph/llms.txt Use the Rails generator or add the gem to your Gemfile to integrate ActiveGraph into a Rails application. ```bash # Create a new Rails app with ActiveGraph rails new myapp -O -m https://raw.githubusercontent.com/neo4jrb/activegraph/master/docs/activegraph.rb # Or add to an existing project in Gemfile gem 'activegraph', '~> 10.0.0' gem 'neo4j-ruby-driver', '~> 1.7.0' ``` -------------------------------- ### Cypher Match Query Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Querying.md Example of a Cypher query matching students, lessons, teachers, and exams. ```cypher # MATCH (s:Student)-[:HAS_LESSON]->(lesson:Lesson)<-[:TEACHES]-(:Teacher), (lesson)<-[:FOR_LESSON]-(exam:Exam) # RETURN exam ``` -------------------------------- ### Optional Match Clauses Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Examples of using the optional_match method to generate Cypher OPTIONAL MATCH clauses. ```ruby .optional_match(n: Person) ``` ```ruby .match('(m)--(n)').optional_match('(n)--(o)').match('(o)--(p)') ``` -------------------------------- ### Create Relationship Instances Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Relationship.md Demonstrates manual instantiation and creation of relationship objects using from_node and to_node. ```ruby rel = EnrolledIn.new rel.from_node = student rel.to_node = lesson ``` ```ruby rel = EnrolledIn.new(from_node: student, to_node: lesson) #or rel = EnrolledIn.create(from_node: student, to_node: lesson) ``` -------------------------------- ### Node Creation API Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Demonstrates various ways to create nodes using the `.create` method, including specifying labels and properties. ```APIDOC ## POST /api/nodes ### Description Creates a new node in the graph database. ### Method POST ### Endpoint /api/nodes ### Parameters #### Request Body - **label** (string) - Required - The label for the node. - **properties** (object) - Optional - Key-value pairs for node properties. ### Request Example ```json { "label": "Person", "properties": { "age": 41, "height": 70 } } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the created node. - **labels** (array of strings) - The labels associated with the node. - **properties** (object) - The properties of the node. #### Response Example ```json { "id": 1, "labels": ["Person"], "properties": { "age": 41, "height": 70 } } ``` ``` -------------------------------- ### Access Nodes from Relationship Source: https://context7.com/neo4jrb/activegraph/llms.txt Retrieve the start or end nodes of a relationship object. ```ruby enrollment.from_node # => Student enrollment.to_node # => Course ``` -------------------------------- ### Perform Node Operations and Queries Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Introduction.md Demonstrates creating nodes, finding by attributes, traversing associations, and chaining query methods. ```ruby # Models to create nodes person = Person.create(name: 'James', age: 15) # Get object by attributes person = Person.find_by(name: 'James', age: 15) # Associations to traverse relationships person.houses.map(&:address) # Method-chaining to build and execute queries Person.where(name: 'James').order(age: :desc).first # Query building methods can be chained with associations # Here we get other owners for pre-2005 vehicles owned by the person in question person.vehicles(:v).where('v.year < 2005').owners(:other).to_a ``` -------------------------------- ### ActiveGraph Migration Helpers for Schema and Data Source: https://context7.com/neo4jrb/activegraph/llms.txt Demonstrates using migration helpers for schema operations (constraints, indexes, properties, labels, relationships) and data operations, including executing raw Cypher and using the query builder. ```ruby class DataMigration < ActiveGraph::Migrations::Base disable_transactions! # Required when mixing schema and data changes def up # Schema operations add_constraint :User, :uuid add_index :Post, :slug # Data operations rename_property :User, :name, :full_name remove_property :Post, :deprecated_field # Label operations add_label :User, :Person rename_label :OldLabel, :NewLabel remove_label :User, :TempLabel # Relationship operations relabel_relation :friends, :FRIENDS_WITH, from: :User, to: :User # Execute raw Cypher execute('MATCH (u:User) SET u.migrated = true') # Use query builder say_with_time 'Updating scores' do query.match(p: :Post) .set('p.score = coalesce(p.score, 0)') .exec end end def down drop_constraint :User, :uuid drop_index :Post, :slug rename_property :User, :full_name, :name end end ``` -------------------------------- ### Build Documentation Rake Tasks Source: https://github.com/neo4jrb/activegraph/blob/12/docs/README.md Commands to generate and manage the documentation build process. ```bash rake docs:yard ``` ```bash rake docs:sphinx ``` ```bash rake docs ``` ```bash rake docs:open ``` -------------------------------- ### Clause combinations and chaining Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Demonstrates how to chain various clauses like match, where, with, and order in the ActiveGraph DSL. ```ruby .match(q: Person).where('q.age > 30') ``` ```cypher MATCH (q:`Person`) WHERE (q.age > 30) ``` ```ruby .where('q.age > 30').match(q: Person) ``` ```cypher MATCH (q:`Person`) WHERE (q.age > 30) ``` ```ruby .where('q.age > 30').start('n').match(q: Person) ``` ```cypher START n MATCH (q:`Person`) WHERE (q.age > 30) ``` ```ruby .match(q: {age: 30}).set_props(q: {age: 31}) ``` ```cypher MATCH (q {age: {q_age}}) SET q = $q_set_props ``` ```ruby .match(q: Person).with('count(q) AS count') ``` ```cypher MATCH (q:`Person`) WITH count(q) AS count ``` ```ruby .match(q: Person).with('count(q) AS count').where('count > 2') ``` ```cypher MATCH (q:`Person`) WITH count(q) AS count WHERE (count > 2) ``` ```ruby .match(q: Person).with(count: 'count(q)').where('count > 2').with(new_count: 'count + 5') ``` ```cypher MATCH (q:`Person`) WITH count(q) AS count WHERE (count > 2) WITH count + 5 AS new_count ``` ```ruby .match(q: Person).match('r:Car').break.match('(p: Person)-->q') ``` ```cypher MATCH (q:`Person`), r:Car MATCH (p: Person)-->q ``` ```ruby .match(q: Person).break.match('r:Car').break.match('(p: Person)-->q') ``` ```cypher MATCH (q:`Person`) MATCH r:Car MATCH (p: Person)-->q ``` ```ruby .match(q: Person).match('r:Car').break.break.match('(p: Person)-->q') ``` ```cypher MATCH (q:`Person`), r:Car MATCH (p: Person)-->q ``` ```ruby .with(:a).order(a: {name: :desc}).where(a: {name: 'Foo'}) ``` ```cypher WITH a ORDER BY a.name DESC WHERE (a.name = $a_name) ``` ```ruby .with(:a).limit(2).where(a: {name: 'Foo'}) ``` ```cypher WITH a LIMIT $limit_2 WHERE (a.name = $a_name) ``` ```ruby .with(:a).order(a: {name: :desc}).limit(2).where(a: {name: 'Foo'}) ``` ```cypher WITH a ORDER BY a.name DESC LIMIT $limit_2 WHERE (a.name = $a_name) ``` ```ruby .order(a: {name: :desc}).with(:a).where(a: {name: 'Foo'}) ``` ```cypher WITH a ORDER BY a.name DESC WHERE (a.name = $a_name) ``` ```ruby .limit(2).with(:a).where(a: {name: 'Foo'}) ``` ```cypher WITH a LIMIT $limit_2 WHERE (a.name = $a_name) ``` ```ruby .order(a: {name: :desc}).limit(2).with(:a).where(a: {name: 'Foo'}) ``` ```cypher WITH a ORDER BY a.name DESC LIMIT $limit_2 WHERE (a.name = $a_name) ``` ```ruby .with('1 AS a').where(a: 1).limit(2) ``` ```cypher WITH 1 AS a WHERE (a = $a) LIMIT $limit_2 ``` ```ruby .match(q: Person).where('q.age = $age').params(age: 15) ``` ```cypher MATCH (q:`Person`) WHERE (q.age = $age) ``` -------------------------------- ### Create node with properties Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node with specified properties. ```ruby .create(age: 41, height: 70) ``` ```cypher CREATE ( {age: $age, height: $height}) ``` -------------------------------- ### Run Database Migrations Source: https://github.com/neo4jrb/activegraph/blob/12/docs/UniqueIDs.md Command to execute pending database migrations, including schema changes for ID properties. ```bash rake neo4j:migrate ``` -------------------------------- ### Ruby .where() Method Usage Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Examples of how to use the .where() method to generate various Cypher filtering conditions. ```APIDOC ## .where() Method ### Description The .where() method is used to add filtering conditions to a query. It supports raw Cypher strings, hash-based conditions, and range objects, automatically handling parameterization to prevent injection. ### Parameters - **condition** (String/Hash/Range) - Required - The filtering criteria to apply. - **params** (Hash) - Optional - Additional parameters for parameterized queries. ### Examples - **String condition:** `.where('q.age > 30')` -> `WHERE (q.age > 30)` - **Hash condition:** `.where(q: {age: 30, name: 'Brian'})` -> `WHERE (q.age = $q_age AND q.name = $q_name)` - **Range condition:** `.where(q: {age: (30..40)})` -> `WHERE (q.age IN RANGE($q_age_range_min, $q_age_range_max))` - **Regex condition:** `.where(name: /Brian.*/i)` -> `WHERE (name =~ $name)` ``` -------------------------------- ### Generate and Run Neo4j Migrations Source: https://context7.com/neo4jrb/activegraph/llms.txt Commands for generating, running, rolling back, and checking the status of Neo4j database migrations. ```bash # Generate a migration rails generate neo4j:migration AddConstraintToUser ``` ```bash # Run migrations rake neo4j:migrate ``` ```bash # Rollback rake neo4j:rollback ``` ```bash rake neo4j:rollback STEPS=3 ``` ```bash # Check status rake neo4j:migrate:status ``` ```bash # Schema management rake neo4j:schema:dump ``` ```bash rake neo4j:schema:load ``` -------------------------------- ### Migration Utilities Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Helper methods for logging migration progress and managing data transformations. ```APIDOC ## #say ### Description Writes text to the console during migration execution. ## #say_with_time ### Description Wraps a block of statements, printing the execution time and affected row count. ## #populate_id_property ### Description Populates the id_property (e.g., uuid) of nodes given their model name. ## #relabel_relation ### Description Relabels a relationship, optionally specifying source/destination nodes and direction. ## #change_relations_style ### Description Converts relationship labels between different naming styles (e.g., :lower, :upper, :lower_hash). ``` -------------------------------- ### Initialize ActiveGraph for Non-Rails Apps Source: https://context7.com/neo4jrb/activegraph/llms.txt Manually establish a database connection and define models for standalone Ruby applications. ```ruby require 'active_graph' require 'neo4j/driver' # Establish database connection ActiveGraph::Base.driver = Neo4j::Driver::GraphDatabase.driver( 'neo4j://localhost:7687', Neo4j::Driver::AuthTokens.basic('neo4j', 'password'), encryption: false ) # Now you can use Node and Relationship models class Person include ActiveGraph::Node property :name end person = Person.create(name: 'Alice') ``` -------------------------------- ### Invalid `find_or_create_by` Usage Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Querying.md Avoid using `find_or_create_by` across multiple associations, as it can lead to errors. This example shows an invalid cross-association call. ```ruby student.friends.lessons.find_or_create_by(subject: 'Math') ``` -------------------------------- ### Query Associations in ActiveGraph Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md Query associations to retrieve related objects. Examples show fetching all comments for a post, the author of a comment, and nested associations. ```ruby post.comments.to_a # Array of comments comment.post # Post object comment.post.comments # Original comment and all of it's siblings. Makes just one query post.comments.author.posts # All posts of people who have commented on the post. Still makes just one query ``` -------------------------------- ### Check Indexes and Constraints Source: https://github.com/neo4jrb/activegraph/blob/12/docs/UniqueIDs.md A Neo4j shell command to list all existing indexes and constraints in the database. ```cypher schema ``` -------------------------------- ### Build a Neo4j Query with Active Graph Source: https://github.com/neo4jrb/activegraph/blob/12/README.md Use this query builder to access Neo4j's capabilities, such as breaking down data and ordering results. Ensure the 'neo4j' gem is installed. ```ruby person.friends.favorite_beers.country_of_origin(:country). order('count(country) DESC'). pluck(:country, count: 'count(country)') ``` -------------------------------- ### neo4j:shell Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Opens a Neo4j REPL shell. ```APIDOC ## RAKE neo4j:shell ### Description Open a Neo4j shell console. Starts the server if it is not already running. ### Arguments - **environment** (string) - Required - The target environment. ### Example rake neo4j:shell[development] ``` -------------------------------- ### RSpec Transaction Rollback for Neo4j Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Testing.md Configures RSpec to run tests within a transaction that is rolled back after each example, similar to ActiveRecord's behavior. Note that Neo4j does not support nested transactions. ```ruby # For the `neo4j` gem config.around do |example| ActiveGraph::Base.transaction do |tx| example.run tx.rollback end end ``` -------------------------------- ### SET, SET PROPS, ON CREATE SET, ON MATCH SET Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Methods to generate SET, ON CREATE SET, and ON MATCH SET Cypher clauses. ```APIDOC ## SET Operations ### Description Methods to update properties, labels, or set values conditionally during creation or matching. ### Methods - `.set_props(args)` - `.set(args)` - `.on_create_set(args)` - `.on_match_set(args)` ### Parameters - **args** (String or Hash) - The property assignments or label definitions. ### Request Example ```ruby .set(n: {name: 'Brian', age: 30}) # Cypher: SET n.`name` = $setter_n_name, n.`age` = $setter_n_age .on_create_set(n: {name: 'Brian', age: 30}) # Cypher: ON CREATE SET n.`name` = $setter_n_name, n.`age` = $setter_n_age ``` ``` -------------------------------- ### Chainable has_one Associations in ActiveGraph Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md By default, querying a has_one association returns the object directly, which can be nil and non-chainable. Use `chainable: true` to get an association proxy object that is always chainable. ```ruby comment.post # Post object comment.post(chainable: true) # Association proxy object wrapping post ``` -------------------------------- ### Configure Neo4j Connection Source: https://context7.com/neo4jrb/activegraph/llms.txt Define database connection settings using YAML or Rails configuration objects. ```yaml # config/neo4j.yml development: url: neo4j://localhost:7687 test: url: neo4j://localhost:7688 production: url: - neo4j://core1:7687 - neo4j://core2:7687 - neo4j://core3:7687 username: neo4j password: password ``` ```ruby # Alternative: config/application.rb config.neo4j.driver.url = 'neo4j://localhost:7687' config.neo4j.driver.username = 'neo4j' config.neo4j.driver.password = 'password' config.neo4j.driver.encryption = false # Disable encryption for local dev ``` -------------------------------- ### Chaining Query Clauses in ActiveGraph Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Querying.md Use `query_as` to get a Query object and chain methods like `match`, `where`, and `pluck` to build Cypher queries. This allows for custom MATCH clauses and flexible data retrieval. ```ruby student.lessons.query_as(:l) \ .match("l-[:has_category*]->(root_category:Category)").where("NOT(root_category-[:has_category]->())) \ .pluck(:root_category) ``` -------------------------------- ### Query Builder Interface Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Provides an entry point for the ActiveGraph query builder. ```ruby query.match(:n).where(name: 'John').delete(:n).exec ``` -------------------------------- ### Load Database Schema Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Load constraints, indexes, and migration nodes into the database from the `db/neo4j/schema.yml` file. An optional argument can be passed to remove database elements not present in the schema file. ```bash rake neo4j:schema:load ``` ```bash rake neo4j:schema:load[true] # Remove any constraints or indexes which aren't in the ``schema.yml`` file ``` -------------------------------- ### Configure property options and serialization Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Properties.md Define property types, default values, and JSON serialization for complex data structures. ```ruby class Post include ActiveGraph::Node property :title, type: String, default: 'This ia new post' property :links serialize :links end ``` -------------------------------- ### Manage Sessions and Transactions Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Setup.md Explicitly create sessions and transactions for atomic operations and read-your-own-writes consistency. ```ruby ActiveGraph::Base.session ActiveGraph::Base.write_transaction ActiveGraph::Base.read_transaction ``` -------------------------------- ### Basic Query Methods Source: https://context7.com/neo4jrb/activegraph/llms.txt Perform standard lookups and filtering using ActiveRecord-style syntax. ```ruby # Find by id_property (uuid by default) post = Post.find('abc-123-uuid') posts = Post.find(['uuid1', 'uuid2']) # Find by attributes post = Post.find_by(title: 'Hello') post = Post.find_by!(title: 'Hello') # Raises if not found # Query with where Post.where(published: true) Post.where(score: 10..100) Post.where('n.created_at > $date', date: 1.week.ago) # Chaining Post.where(published: true) .where_not(archived: true) .order(created_at: :desc) .limit(10) .to_a # Count and existence Post.count Post.where(published: true).exists? Post.where(published: true).empty? ``` -------------------------------- ### Configure Neo4j Test Port Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Testing.md Configures the Neo4j test database to run on a specific port. ```bash rake neo4j:config[test,7475] ``` -------------------------------- ### Execute Specific Migration Version Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Run a migration by its version ID. Use `neo4j:migrate:up` to apply a migration or `neo4j:migrate:down` to revert it. ```bash rake neo4j:migrate:up VERSION=some_version ``` ```bash rake neo4j:migrate:down VERSION=some_version ``` -------------------------------- ### MATCH Nodes Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Illustrates how to use `match_nodes` and `optional_match_nodes` to match nodes in the graph based on various inputs. ```APIDOC ## MATCH Nodes ### Description Methods for matching nodes in the graph. `match_nodes` creates a `MATCH` clause, while `optional_match_nodes` creates an `OPTIONAL MATCH` clause. They support matching by node object, integer ID, or multiple nodes. ### Method `match_nodes`, `optional_match_nodes` ### Endpoint N/A (This is a Ruby method for query building) ### Parameters - **var** (Object/Integer/Hash) - Required - The node variable name and the value to match (node object, integer ID, or a hash of node variables to their values). ### Request Example ```ruby .match_nodes(var: node_object) .optional_match_nodes(var: node_object) .match_nodes(var: 924) .match_nodes(user: user, post: post) .match_nodes(user: user, post: 652) ``` ### Response #### Success Response (200) N/A (This method builds a query string) #### Response Example ```cypher MATCH (var) WHERE (ID(var) = $ID_var) OPTIONAL MATCH (var) WHERE (ID(var) = $ID_var) MATCH (var) WHERE (ID(var) = $ID_var) MATCH (user), (post) WHERE (ID(user) = $ID_user) AND (ID(post) = $ID_post) MATCH (user), (post) WHERE (ID(user) = $ID_user) AND (ID(post) = $ID_post) ``` ``` -------------------------------- ### Configure Enum prefixes Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md Use the _prefix option to customize the generated helper method names. ```ruby Media.enum type: [:image, :video, :unknown], _prefix: :something media.something_image? media.something_image! ``` -------------------------------- ### Migration Logging Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Writes text to the migration output, with optional indentation. ```ruby say 'Hello' ``` ```ruby -- Hello ``` ```ruby say 'Hello', true ``` ```ruby -> Hello ``` -------------------------------- ### Transparent Eager Loading Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md Demonstrates the default behavior where associations are loaded efficiently across multiple queries. ```ruby person.blog_posts.each do |post| puts post.title puts "Tags: #{post.tags.map(&:name).join(', ')}" post.comments.each do |comment| puts ' ' + comment.title end end ``` -------------------------------- ### Define Basic Node Model Source: https://context7.com/neo4jrb/activegraph/llms.txt Create a model with properties, validations, and callbacks using ActiveGraph::Node and ActiveGraph::Timestamps. ```ruby class Post include ActiveGraph::Node include ActiveGraph::Timestamps # Adds created_at and updated_at # Define properties with types and defaults property :title, type: String property :content, type: String property :score, type: Integer, default: 0 property :published, type: Boolean, default: false # Validations (ActiveModel compatible) validates :title, presence: true validates :score, numericality: { only_integer: true } # Callbacks before_save :normalize_title private def normalize_title self.title = title.strip.titleize if title end end # Usage post = Post.create(title: 'Hello World', content: 'My first post') # => # post.update(score: 10, published: true) post.valid? # => true post.destroy ``` -------------------------------- ### return method usage Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Specifies the return values for the query. ```ruby .return('q') ``` ```cypher RETURN q ``` ```ruby .return(:q) ``` ```cypher RETURN q ``` ```ruby .return('q.name, q.age') ``` ```cypher RETURN q.name, q.age ``` ```ruby .return(q: [:name, :age], r: :grade) ``` ```cypher RETURN q.name, q.age, r.grade ``` ```ruby .return(q: :neo_id) ``` ```cypher RETURN ID(q) ``` ```ruby .return(q: [:neo_id, :prop]) ``` ```cypher RETURN ID(q), q.prop ``` -------------------------------- ### Migration Status Report Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Display a report detailing the status of all migrations, indicating which have been applied and which are pending. ```bash rake neo4j:migrate:status ``` -------------------------------- ### Database Execution and Querying Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Methods for executing raw Cypher queries and using the query builder. ```APIDOC ## #execute ### Description Executes a pure neo4j cypher query, interpolating parameters. ### Request Example execute('MATCH (n) WHERE n.name = {node_name} RETURN n', node_name: 'John') ## #query ### Description An alias for ActiveGraph::Session.query. You can use it as root for the query builder. ### Request Example query.match(:n).where(name: 'John').delete(:n).exec ``` -------------------------------- ### Run All Pending Migrations Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Execute all migrations that have not yet been run. This task automatically creates or updates the `db/neo4j/schema.yml` file. ```bash rake neo4j:migrate:all ``` ```bash rake neo4j:migrate ``` -------------------------------- ### Create labeled node with identifier and properties Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node with an identifier, label, and properties. ```ruby .create(q: {Person: {age: 41, height: 70}}) ``` ```cypher CREATE (q:`Person` {age: $q_Person_age, height: {q_Person_height}}) ``` -------------------------------- ### neo4j:config Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Configures the port settings for the Neo4j server. ```APIDOC ## RAKE neo4j:config ### Description Configure the port which Neo4j runs on, affecting the HTTP REST interface and web console. ### Arguments - **environment** (string) - Required - The target environment. - **port** (integer) - Required - The port number to assign. ### Example rake neo4j:config[development,7100] ``` -------------------------------- ### Measure Migration Execution Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Wraps statements in a block to measure execution time and report affected rows. ```ruby say_with_time 'Trims all names' do query.match(n: :User).set('n.name = TRIM(n.name)').pluck('count(*)').first end ``` ```bash -- Trims all names. -> 0.3451s -> 2233 rows ``` -------------------------------- ### Set properties on create with on_create_set Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Sets properties only when a node is created. ```ruby .on_create_set('n = {name: "Brian"}') ``` ```cypher ON CREATE SET n = {name: "Brian"} ``` ```ruby .on_create_set(n: {}) ``` ```cypher ``` ```ruby .on_create_set(n: {name: 'Brian', age: 30}) ``` ```cypher ON CREATE SET n.`name` = $setter_n_name, n.`age` = $setter_n_age ``` ```ruby .on_create_set(n: {name: 'Brian', age: 30}, o: {age: 29}) ``` ```cypher ON CREATE SET n.`name` = $setter_n_name, n.`age` = $setter_n_age, o.`age` = $setter_o_age ``` ```ruby .on_create_set(n: {name: 'Brian', age: 30}).on_create_set('o.age = 29') ``` ```cypher ON CREATE SET n.`name` = $setter_n_name, n.`age` = $setter_n_age, o.age = 29 ``` -------------------------------- ### Unique Node Creation API Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Illustrates how to create unique nodes using the `.create_unique` method, ensuring no duplicate nodes are created based on specified criteria. ```APIDOC ## POST /api/nodes/unique ### Description Creates a new node in the graph database only if a node with the same properties and labels does not already exist. ### Method POST ### Endpoint /api/nodes/unique ### Parameters #### Request Body - **label** (string) - Required - The label for the node. - **properties** (object) - Required - Key-value pairs for node properties. Uniqueness is determined by these properties. ### Request Example ```json { "label": "Person", "properties": { "name": "Alice", "age": 30 } } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the created or existing node. - **labels** (array of strings) - The labels associated with the node. - **properties** (object) - The properties of the node. #### Response Example ```json { "id": 2, "labels": ["Person"], "properties": { "name": "Alice", "age": 30 } } ``` ``` -------------------------------- ### Simple regex in hash Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Using regex in a simple hash. ```ruby .where(name: /Brian.*/i) ``` ```cypher WHERE (name =~ $name) ``` -------------------------------- ### Create node with multiple labels as array Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node with multiple labels provided as an array. ```ruby .create(q: {[:Child, :Person] => {age: 41, height: 70}}) ``` ```cypher CREATE (q:`Child`:`Person` {age: $q_Child_Person_age, height: {q_Child_Person_height}}) ``` -------------------------------- ### Create node with multiple labels as array key Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node with multiple labels using an array as the key. ```ruby .create([:Child, :Person] => {age: 41, height: 70}) ``` ```cypher CREATE (:`Child`:`Person` {age: $Child_Person_age, height: {Child_Person_height}}) ``` -------------------------------- ### Restart Neo4j Server Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Restarts the Neo4j server for a specified environment. ```ruby rake neo4j:restart[development] ``` -------------------------------- ### neo4j:restart Source: https://github.com/neo4jrb/activegraph/blob/12/docs/RakeTasks.md Restarts the Neo4j server instance. ```APIDOC ## RAKE neo4j:restart ### Description Restarts the Neo4j server. ### Arguments - **environment** (string) - Required - The target environment. ### Example rake neo4j:restart[development] ``` -------------------------------- ### Create node with multiple labels as key Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node with multiple labels using a symbol key. ```ruby .create(:'Child:Person' => {age: 41, height: 70}) ``` ```cypher CREATE (:`Child:Person` {age: $Child_Person_age, height: {Child_Person_height}}) ``` -------------------------------- ### Simple Query Logging in ActiveGraph Source: https://context7.com/neo4jrb/activegraph/llms.txt Subscribe to query events to log all Cypher queries executed by ActiveGraph. ```ruby # Simple query logging ActiveGraph::Base.subscribe_to_query do |message| Rails.logger.debug(message) end ``` -------------------------------- ### Use Query Parameters Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Querying.md Methods for using automatic and manual parameters to prevent injection and enable caching. ```ruby Student.all.where(age: 20) ``` ```ruby Student.all.where("s.age < $age AND s.name = $name AND s.home_town = $home_town") .params(age: 24, name: 'James', home_town: 'Dublin') .pluck(:s) ``` -------------------------------- ### Create labeled node with properties Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node with a label and associated properties. ```ruby .create(Person: {age: 41, height: 70}) ``` ```cypher CREATE (:`Person` {age: $Person_age, height: $Person_height}) ``` -------------------------------- ### Create node with string label Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node using a string representation of the label. ```ruby .create('(:Person)') ``` ```cypher CREATE (:Person) ``` -------------------------------- ### Define a basic ActiveGraph::Node model Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md Include ActiveGraph::Node in a class to enable Neo4j node functionality. ```ruby class Post include ActiveGraph::Node end ``` -------------------------------- ### Provision Neo4j Add-ons on Heroku Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Setup.md Commands to add GrapheneDB or Graph Story to a Heroku application. ```bash # To use GrapheneDB: heroku addons:create graphenedb # To use Graph Story: heroku addons:create graphstory ``` -------------------------------- ### Chaining Queries on Polymorphic Associations Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md After using `.query_as` and `.match`, you can continue to build complex queries. Use `.match` to specify further relationships and node patterns. ```ruby post.comments.author.written_things.query_as(:written_thing).match("(written_thing)-[:post]->(post:Post)").match("(post)<-[:post]-(comment:Comment)").pluck(:comment) ``` -------------------------------- ### Configure ActiveGraph in standalone Ruby apps Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Configuration.md Set configuration variables directly using the ActiveGraph configuration class. ```ruby ActiveGraph::Config[:variable_name] = value ``` -------------------------------- ### Create node with multiple labels in string Source: https://github.com/neo4jrb/activegraph/blob/12/docs/QueryClauseMethods.md Creates a node with multiple labels defined in a single string. ```ruby .create(q: {:'Child:Person' => {age: 41, height: 70}}) ``` ```cypher CREATE (q:`Child:Person` {age: $q_Child_Person_age, height: {q_Child_Person_height}}) ``` -------------------------------- ### Dump Database Schema Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Generate the `db/neo4j/schema.yml` file by reading the current database state. This file tracks constraints, indexes, and run migrations. This task runs automatically after `neo4j:migrate`. ```bash rake neo4j:schema:dump ``` -------------------------------- ### Defining Enums with Options Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Node.md Configuration options for enum properties including index management, default values, and case sensitivity. ```ruby class Media include ActiveGraph::Node enum type: [:image, :video, :unknown], _index: false end ``` ```ruby class Media include ActiveGraph::Node enum type: [:image, :video, :unknown], _default: :video end ``` ```ruby class Media include ActiveGraph::Node enum type: [:image, :video, :unknown], _case_sensitive: false end ``` -------------------------------- ### Schema and Property Management Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Migrations.md Methods for managing node properties, labels, constraints, and indexes. ```APIDOC ## #remove_property ### Description Removes a property given a label. ## #rename_property ### Description Renames a property given a label. ## #drop_nodes ### Description Removes all nodes with a certain label. ## #add_label / #add_labels ### Description Adds a label or multiple labels to nodes, given their current label. ## #remove_label / #remove_labels ### Description Removes a label or multiple labels from nodes, given a label. ## #add_constraint / #drop_constraint ### Description Adds or drops a unique constraint on a given label attribute. Note: Requires disable_transactions! in migration if data changes are involved. ## #add_index / #drop_index ### Description Adds or drops an exact index on a given label attribute. ``` -------------------------------- ### E2E Test Environment Variables Source: https://github.com/neo4jrb/activegraph/blob/12/docs/Testing.md Environment variables for configuring end-to-end tests, including ActiveGraph path, ActiveModel version, Neo4j port, and authentication settings. ```bash ACTIVEGRAPH_PATH=local path of activegraph code (root directory) ``` ```bash ACTIVE_MODEL_VERSION=version of activemodel ``` ```bash E2E_PORT=neo4j server port ``` ```bash E2E_NO_CRED=set this to true when neo4j server has auth disabled ```