### Example: Using Neo4j Bookmarks for Transaction Consistency Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This example demonstrates how to use Neo4j bookmarks with `client.use_bookmarks()` to ensure transaction consistency, particularly in an Enterprise Edition setup. It shows how to capture bookmarks from a previous transaction and then execute subsequent queries within that bookmark's context, effectively seeing only data committed up to that point. ```python ## Create a new node and get the bookmarks from the last session await client.cypher("CREATE (d:Developer {name: 'John Doe', age: 25})") bookmarks = client.last_bookmarks ## Create another node, but this time don't get the bookmark ## When we use the bookmarks from the last session, this node will not be visible await client.cypher("CREATE (c:Coffee {flavour: 'Espresso', milk: False, sugar: False})") with client.use_bookmarks(bookmarks=bookmarks): ## All queries executed inside the context manager will use the bookmarks ## passed to the `use_bookmarks()` method. ## Here we will only see the node created in the first query results, meta = await client.cypher("MATCH (n) RETURN n") ## Model queries also can be batched together without any extra work! ## This will return no results, since the coffee node was created after ## the bookmarks were taken. coffee = await Coffee.find_many() print(coffee) ## [] ``` -------------------------------- ### Install Specific Pydantic Version with Poetry Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md Command to install a specific version of Pydantic using `poetry` for testing against different Pydantic versions. Replace `` with the desired Pydantic version string. ```bash poetry add pydantic@ ``` -------------------------------- ### Full pyneo4j-ogm Client Initialization and Operations Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md Provides a complete example of initializing `Pyneo4jClient`, connecting to a database, registering models, and performing node and relationship creation operations. Emphasizes the importance of closing the client connection. ```python async def main(): # We initialize a new `Pyneo4jClient` instance and connect to the database. client = Pyneo4jClient() await client.connect(uri="", auth=("", "")) # To use our models for running queries later on, we have to register # them with the client. # **Note**: You only have to register the models that you want to use # for queries and you can even skip this step if you want to use the # `Pyneo4jClient` instance for running raw queries. await client.register_models([Developer, Coffee, Consumed]) # We create a new `Developer` node and the `Coffee` he is going to drink. john = Developer(name="John", age=25) await john.create() cappuccino = Coffee(flavor="Cappuccino", milk=True, sugar=False) await cappuccino.create() # Here we create a new relationship between `john` and his `cappuccino`. # Additionally, we set the `liked` property of the relationship to `True`. await john.coffee.connect(cappuccino, {"liked": True}) # Will print `John chugged another one!` # Be a good boy and close your connections after you are done. await client.close() asyncio.run(main()) ``` -------------------------------- ### Get Start Node of Relationship Instance (Python) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Demonstrates how to retrieve the start node of a `RelationshipModel` instance. This method is available only for `RelationshipModel` classes, takes no arguments, and returns the associated start node. ```python start_node = await coffee_relationship.start_node() print(start_node) ## ``` -------------------------------- ### Example pyneo4j-ogm Migration File (up/down functions) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Migrations.md Illustrates the structure of an auto-generated pyneo4j-ogm migration file. It shows how to implement 'up' (forward) and 'down' (rollback) operations using the 'Pyneo4jClient' to execute Cypher queries. ```python """ Auto-generated migration file {name}. Do not rename this file or the `up` and `down` functions. """ from pyneo4j_ogm import Pyneo4jClient async def up(client: Pyneo4jClient) -> None: """ Write your `UP migration` here. """ await client.cypher("CREATE (n:Node {name: 'John'})") async def down(client: Pyneo4jClient) -> None: """ Write your `DOWN migration` here. """ await client.cypher("MATCH (n:Node {name: 'John'}) DELETE n") ``` -------------------------------- ### Install pyneo4j-ogm using pip Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md This command installs the pyneo4j-ogm library into your Python environment using the pip package manager. It's the standard way to install Python packages. ```bash pip install pyneo4j-ogm ``` -------------------------------- ### Example: Batching Multiple Cypher Queries with `client.batch()` Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This example illustrates how to use the `client.batch()` asynchronous context manager to group multiple database operations into a single transaction. All queries executed within this block, including both `client.cypher()` calls and model methods like `create()`, will be committed or rolled back atomically. ```python async with client.batch(): ## All queries executed inside the context manager will be batched into a single transaction ## and executed once the context manager exits. If any of the queries fail, the whole transaction ## will be rolled back. await client.cypher( query="CREATE (d:Developer {uid: $uid, name: $name, age: $age})", parameters={"uid": "553ac2c9-7b2d-404e-8271-40426ae80de0", "name": "John Doe", "age": 25}, ) await client.cypher( query="CREATE (c:Coffee {flavour: $flavour, milk: $milk, sugar: $sugar})", parameters={"flavour": "Espresso", "milk": False, "sugar": False}, ) ## Model queries also can be batched together without any extra work! coffee = await Coffee(flavour="Americano", milk=False, sugar=False).create() ``` -------------------------------- ### Example: Executing a Custom Cypher Query with `client.cypher()` Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This example demonstrates how to use the `client.cypher()` method to execute a custom Cypher query. It shows creating a `Developer` node with specific properties and explicitly disabling model resolution, then printing the raw results and metadata. ```python results, meta = await client.cypher( query="CREATE (d:Developer {uid: '553ac2c9-7b2d-404e-8271-40426ae80de0', name: 'John', age: 25}) RETURN d.name as developer_name, d.age", parameters={"name": "John Doe"}, resolve_models=False ## Explicitly disable model resolution ) print(results) ## [["John", 25]] print(meta) ## ["developer_name", "d.age"] ``` -------------------------------- ### Connect to Neo4j Database using Pyneo4jClient Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This snippet demonstrates how to establish a connection to a Neo4j database using the `Pyneo4jClient.connect()` method. It illustrates passing connection parameters such as URI, authentication details, and connection pool size. The example shows both direct instantiation and chained connection approaches. ```python from pyneo4j_ogm import Pyneo4jClient client = Pyneo4jClient() await client.connect(uri="", auth=("", ""), max_connection_pool_size=10, ...) ## Or chained right after the instantiation of the class client = await Pyneo4jClient().connect(uri="", auth=("", ""), max_connection_pool_size=10, ...) ``` -------------------------------- ### Initialize and Register Models with Pyneo4jClient Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md This code example illustrates the process of initializing a `Pyneo4jClient` instance, connecting to a Neo4j database using a URI and authentication credentials, and subsequently registering the previously defined `Developer`, `Coffee`, and `Consumed` models with the client. Model registration is crucial for enabling ORM-like query operations. ```python from pyneo4j_ogm import Pyneo4jClient async def main(): # We initialize a new `Pyneo4jClient` instance and connect to the database. client = Pyneo4jClient() # Replace ``, `` and `` with the # actual values. await client.connect(uri="", auth=("", "")) # To use our models for running queries later on, we have to register # them with the client. # **Note**: You only have to register the models that you want to use # for queries and you can even skip this step if you want to use the # `Pyneo4jClient` instance for running raw queries. await client.register_models([Developer, Coffee, Consumed]) ``` -------------------------------- ### Apply Projections to Query Results (pyneo4j-ogm) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Demonstrates how to use projections with `find_many()` to return specific model properties as dictionaries instead of full model instances. This example projects the 'name' property to 'dev_name'. ```python developers = await Developer.find_many({"name": "John"}, {"dev_name": "name"}) print(developers) ## [{"dev_name": "John"}, {"dev_name": "John"}, ...] ``` -------------------------------- ### pyneo4j-ogm Client Utility Methods API Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md API documentation for convenience methods provided by the pyneo4j-ogm client, primarily for testing and environment setup. These methods include checking connection status and dropping various database elements. ```APIDOC is_connected() -> bool Returns whether the client is currently connected to a database. drop_nodes() Drops all nodes from the database. drop_constraints() Drops all constraints from the database. drop_indexes() Drops all indexes from the database. ``` -------------------------------- ### Example: Create Neo4j Range Index and Uniqueness Constraint in Python Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This Python example demonstrates how to use the pyneo4j-ogm client to create a range index on 'sugar' and 'flavour' properties for 'Beverage' and 'Hot' nodes, and a uniqueness constraint on the 'uid' property for 'Developer' nodes. ```python ## Creates a `RANGE` index for a `Coffee's` `sugar` and `flavour` properties await client.create_range_index("hot_beverage_index", EntityType.NODE, ["sugar", "flavour"], ["Beverage", "Hot"]) ## Creates a UNIQUENESS constraint for a `Developer's` `uid` property await client.create_uniqueness_constraint("developer_constraint", EntityType.NODE, ["uid"], ["Developer"]) ``` -------------------------------- ### pyneo4j-ogm Core API Reference Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md Structured reference for key `pyneo4j-ogm` classes: `Pyneo4jClient`, `NodeModel`, `RelationshipModel`, `RelationshipProperty`, `WithOptions`, and `Field`. Details their essential properties, methods, and configuration options as demonstrated in the code examples. ```APIDOC Pyneo4jClient: - connect(uri: str, auth: tuple) Description: Connects to the Neo4j database. Parameters: uri: Connection URI. auth: Tuple containing username and password. - register_models(models: list) Description: Registers NodeModel and RelationshipModel classes with the client for query operations. Parameters: models: A list of model classes to register. - close() Description: Closes the connection to the database. NodeModel: Description: Base class for defining Neo4j nodes. Properties: - uid: UUID (WithOptions, unique=True) Description: Unique identifier for the node. - name: str Description: Name of the entity. - age: int Description: Age of the entity. - coffee: RelationshipProperty["Coffee", "Consumed"] Description: Defines an outgoing relationship to Coffee nodes via Consumed relationship. Direction: OUTGOING Cardinality: ZERO_OR_MORE - developers: RelationshipProperty["Developer", "Consumed"] Description: Defines an incoming relationship from Developer nodes via Consumed relationship. Direction: INCOMING Cardinality: ZERO_OR_MORE Methods: - create() Description: Creates the node in the database. Settings: - post_hooks: dict Description: Dictionary of post-operation hooks. Example: {"coffee.connect": lambda self, *args, **kwargs: print(f"{self.name} chugged another one!")} - labels: set Description: Explicitly defined labels for the node. Example: {"Beverage", "Hot"} RelationshipModel: Description: Base class for defining Neo4j relationships. Properties: - liked: bool Description: Property indicating if the relationship is "liked". Settings: - type: str Description: The type of the relationship in the graph. Example: "CHUGGED" RelationshipProperty: Description: Used within NodeModels to define relationships to other nodes. Parameters: - target_model: str | NodeModel Description: The target NodeModel class or its string name. - relationship_model: str | RelationshipModel Description: The RelationshipModel class or its string name. - direction: RelationshipPropertyDirection Description: Direction of the relationship (OUTGOING, INCOMING). - cardinality: RelationshipPropertyCardinality Description: Number of allowed relationships (ZERO_OR_MORE, ONE_OR_MORE, ZERO_OR_ONE, ONE). - allow_multiple: bool Description: Whether multiple relationships of the same type are allowed. WithOptions: Description: Utility for defining options on model fields (e.g., unique constraints). Usage: WithOptions(type, options_dict) Field: Description: Pydantic field for model property definitions. Usage: Field(default_factory=callable) ``` -------------------------------- ### Find One with Projections (Model.find_one()) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md This example demonstrates using `projections` with `Model.find_one()` to return only specific properties of a model as a dictionary. This can optimize bandwidth usage and pre-filter query results into a more suitable format. ```python ## Return a dictionary with the developers name at the `dev_name` key instead ## of a model instance. developer = await Developer.find_one({"name": "John"}, {"dev_name": "name"}) print(developer) ## {"dev_name": "John"} ``` -------------------------------- ### Apply Query Options for Limiting and Skipping Results (pyneo4j-ogm) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Illustrates how to use the `options` argument with `find_many()` to control the number of results returned and to skip a certain number of initial results. This example skips the first 10 and returns the next 20. ```python developers = await Developer.find_many({"name": "John"}, options={"limit": 20, "skip": 10}) print(developers) ## [, , ...] up to 20 results ``` -------------------------------- ### Define pyneo4j-ogm Node and Relationship Models Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md Illustrates how to define `NodeModel` classes (`Developer`, `Coffee`) and a `RelationshipModel` class (`Consumed`) in `pyneo4j-ogm`. Includes examples of defining properties, relationship properties, and using `Settings` for hooks, labels, and relationship types. ```python import asyncio from pyneo4j_ogm import ( NodeModel, Pyneo4jClient, RelationshipModel, RelationshipProperty, RelationshipPropertyCardinality, RelationshipPropertyDirection, WithOptions, ) from pydantic import Field from uuid import UUID, uuid4 class Developer(NodeModel): """ This class represents a `Developer` node inside the graph. All interaction with nodes of this type will be handled by this class. """ uid: WithOptions(UUID, unique=True) = Field(default_factory=uuid4) name: str age: int coffee: RelationshipProperty["Coffee", "Consumed"] = RelationshipProperty( target_model="Coffee", relationship_model="Consumed", direction=RelationshipPropertyDirection.OUTGOING, cardinality=RelationshipPropertyCardinality.ZERO_OR_MORE, allow_multiple=True, ) class Settings: # Hooks are available for all methods that interact with the database. post_hooks = { "coffee.connect": lambda self, *args, **kwargs: print(f"{self.name} chugged another one!") } class Coffee(NodeModel): """ This class represents a node with the labels `Beverage` and `Hot`. Notice that the labels of this model are explicitly defined in the `Settings` class. """ flavor: str sugar: bool milk: bool developers: RelationshipProperty["Developer", "Consumed"] = RelationshipProperty( target_model=Developer, relationship_model="Consumed", direction=RelationshipPropertyDirection.INCOMING, cardinality=RelationshipPropertyCardinality.ZERO_OR_MORE, allow_multiple=True, ) class Settings: labels = {"Beverage", "Hot"} class Consumed(RelationshipModel): """ Unlike the models above, this class represents a relationship between two nodes. In this case, it represents the relationship between the `Developer` and `Coffee` models. Like with node-models, the `Settings` class allows us to define some settings for this relationship. Note that the relationship itself does not define it's start- and end-nodes, making it reusable for other models as well. """ liked: bool class Settings: type = "CHUGGED" ``` -------------------------------- ### Get relationships between nodes using pyneo4j-ogm Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/RelationshipProperty.md Shows how to use the `relationships()` method of a `RelationshipProperty` to retrieve relationship instances between a source node and a target node. It illustrates the basic call and the expected output. ```python ## The `developer` and `coffee` variables have been defined somewhere above ## Returns the relationships between the two nodes coffee_relationships = await developer.coffee.relationships(coffee) print(coffee_relationships) ## [, , ...] ## Or if no relationships were found print(coffee_relationships) ## [] ``` -------------------------------- ### Define pyneo4j-ogm NodeModel with Indexes and Constraints Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md This Python snippet demonstrates how to define a `NodeModel` in `pyneo4j-ogm` and apply Neo4j-specific indexes and constraints to its properties using the `WithOptions` method. It shows examples of a unique constraint on `uid` and a text index on `name`, while also illustrating a property where `WithOptions` has no effect. ```python from pyneo4j_ogm import NodeModel, WithOptions from pydantic import Field from uuid import UUID, uuid4 class Developer(NodeModel): """ A model representing a developer node in the graph. """ ## Using the `WithOptions` method on the type, we can still use all of the features provided by ## `Pydantic` while also defining indexes and constraints on the property. uid: WithOptions(UUID, unique=True) = Field(default_factory=uuid4) name: WithOptions(str, text_index=True) ## Has no effect, since no index or constraint options are passed age: WithOptions(int) ``` -------------------------------- ### Filter Developers by Multiple Relationship Patterns Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Query.md Illustrates advanced pattern matching in pyneo4j-ogm by combining multiple relationship patterns. This example finds `Developer` nodes who `liked` their `Coffee` AND are `FRIENDS_WITH` a `Developer` named `Jenny`, showcasing both outgoing and incoming relationship directions. ```Python developers = await Developer.find_many({ "$patterns": [ { "$exists": True, "$direction": RelationshipMatchDirection.OUTGOING, "$node": { "$labels": ["Beverage", "Hot"] }, "$relationship": { "$type": "CHUGGED", "liked": True } }, { "$exists": True, "$direction": RelationshipMatchDirection.INCOMING, "$node": { "$labels": ["Developer"], "name": "Jenny" }, "$relationship": { "$type": "FRIENDS_WITH" } } ] }) ``` -------------------------------- ### Count All Developer Nodes Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md This snippet demonstrates how to get the total number of `Developer` nodes in the database using the `count()` method without any filters. It returns the total count. ```python ## Returns the total number of `Developer` nodes inside the database count = await Developer.count() print(count) ## However many nodes matched the filter ## Or if no match was found print(count) ## 0 ``` -------------------------------- ### Fetch All Relationship Properties Automatically (Python) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Query.md This Python example demonstrates how to automatically fetch all defined relationship-properties for a matched node using `auto_fetch_nodes=True`. It shows how to retrieve a `Developer` node and then access its related `Coffee`, `Developer`, and `OtherModel` nodes through their respective relationship properties, which are populated into the `.nodes` attribute. ```python ## Fetches everything defined in the relationship-properties of the current matched node developer = await Developer.find_one({"name": "John"}, auto_fetch_nodes=True) ## All nodes for all defined relationship-properties are now fetched print(developer.coffee.nodes) ## [, , ...] print(developer.developer.nodes) ## [, , ...] print(developer.other_property.nodes) ## [, , ...] ``` -------------------------------- ### Filter Developers by Coffee Preference (No Sugar) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Query.md Demonstrates how to use pattern matching in pyneo4j-ogm to find `Developer` nodes based on a single relationship pattern. This example retrieves developers who `don't drink` their `Coffee` `with sugar` by using the `$exists: False` operator on the `CHUGGED` relationship. ```Python developers = await Developer.find_many({ "$patterns": [ { "$exists": False, "$direction": RelationshipMatchDirection.OUTGOING, "$node": { "$labels": ["Beverage", "Hot"], "sugar": False }, "$relationship": { "$type": "CHUGGED" } } ] }) ``` -------------------------------- ### Find Many with Filters (Model.find_many()) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md This example demonstrates applying filters to the `Model.find_many()` method to retrieve a specific subset of nodes. Filters allow for complex queries based on property values, similar to those used with `find_one()`. ```python ## Returns all `Developer` nodes where the age property is greater than or ## equal to 21 and less than 45. developers = await Developer.find_many({"age": {"$and": [{"$gte": 21}, {"$lt": 45}]}}) print(developers) ## [, , , ...] ``` -------------------------------- ### Utilize Query Options for Pagination and Sorting in pyneo4j-ogm Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Query.md Query options provide basic functionality for controlling the results returned from queries, such as pagination and sorting. They are defined as a dictionary with keys like `limit` (number of results), `skip` (offset), `sort` (property to sort by), and `order` (sort direction, `ASC` or `DESC`). This example demonstrates retrieving 50 developers, skipping the first 10, and sorting them by `name` in descending order. ```python ## Returns 50 results, skips the first 10 and sorts them by the `name` property in descending order developers = await Developer.find_many({}, options={"limit": 50, "skip": 10, "sort": "name", "order": QueryOptionsOrder.DESCENDING}) print(len(developers)) ## 50 print(developers) ## [, , ...] ``` -------------------------------- ### Fetch Specific Relationship Properties Automatically (Python) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Query.md This Python example illustrates how to selectively fetch specific relationship-properties using the `auto_fetch_models` parameter. It demonstrates fetching only `Coffee` and `Developer` related nodes for a `Developer` instance, leaving other properties unfetched. Models can be passed as class references or string names to `auto_fetch_models`. ```python ## Only fetch nodes for `Coffee` and `Developer` models defined in relationship-properties ## The models can also be passed as strings, where the string is the model's name developer = await Developer.find_one({"name": "John"}, auto_fetch_nodes=True, auto_fetch_models=[Coffee, "Developer"]) ## Only the defined models have been fetched print(developer.coffee.nodes) ## [, , ...] print(developer.developer.nodes) ## [, , ...] print(developer.other_property.nodes) ## [] ``` -------------------------------- ### Update Multiple Developer Nodes (Return Updated Instances) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md This example shows `update_many` to modify `Developer` nodes. Although the code is identical to the default case, this snippet illustrates the behavior when the `new=True` parameter is used (as described in the surrounding text), causing the method to return the model instances *after* the update. ```python ## Updates all `Developer` nodes where the age property is between `22` and `30` ## to `40` and return the updated nodes developers = await Developer.update_many({"age": 40}, {"age": {"$gte": 22, "$lte": 30}}) print(developers) ## [, , ...] ``` -------------------------------- ### Initialize pyneo4j-ogm Migrations Directory Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Migrations.md Command to set up the migration directory for a pyneo4j-ogm project. Defaults to './migrations' but can be customized using the '--migration-dir' argument. ```bash poetry run pyneo4j_ogm init --migration-dir ./my/custom/migration/path ``` -------------------------------- ### Pyneo4jClient API Reference Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This section provides a detailed API reference for the `Pyneo4jClient` class, outlining its constructor and key methods. It includes parameters, their types, and descriptions for `connect()`, `close()`, `register_models()`, and `register_models_from_directory()`. This reference is essential for understanding the client's interface and usage. ```APIDOC Pyneo4jClient: __init__() connect(uri: str, skip_constraints: bool = False, skip_indexes: bool = False, *args, **kwargs) uri: The connection URI to the database. skip_constraints: Whether the client should skip creating any constraints defined on models when registering them. Defaults to `False`. skip_indexes: Whether the client should skip creating any indexes defined on models when registering them. Defaults to `False`. *args: Additional arguments that are passed directly to Neo4j's `AsyncDriver.driver()` method. **kwargs: Additional keyword arguments that are passed directly to Neo4j's `AsyncDriver.driver()` method. close() register_models(models: list) models: A list of model classes to register. register_models_from_directory(path: str) path: The path to a directory holding all your models. ``` -------------------------------- ### Basic Node and Relationship Creation with pyneo4j-ogm Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md Demonstrates the fundamental steps of creating a `Developer` node and a `Coffee` node, then establishing a `Consumed` relationship between them using `pyneo4j-ogm`'s `create()` and `connect()` methods. Shows how to add properties to the relationship. ```python # Imagine your models have been defined above... async def main(): # And your client has been initialized and connected to the database... # We create a new `Developer` node and the `Coffee` he is going to drink. john = Developer(name="John", age=25) await john.create() cappuccino = Coffee(flavor="Cappuccino", milk=True, sugar=False) await cappuccino.create() # Here we create a new relationship between `john` and his `cappuccino`. # Additionally, we set the `liked` property of the relationship to `True`. await john.coffee.connect(cappuccino, {"liked": True}) # Will print `John chugged another one!` ``` -------------------------------- ### Get End Node of Relationship Instance (Python) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Demonstrates how to retrieve the end node of a `RelationshipModel` instance. This method is available only for `RelationshipModel` classes, takes no arguments, and returns the associated end node. ```python end_node = await coffee_relationship.end_node() print(end_node) ## ``` -------------------------------- ### Programmatic pyneo4j-ogm Migration Management Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Migrations.md Demonstrates how to integrate pyneo4j-ogm's migration tools directly into Python applications or custom CLIs. This allows for programmatic initialization, creation, and execution of migrations. ```python import asyncio from pyneo4j_ogm.migrations import create, down, init, status, up ## Call with same arguments as you would with cli init(migration_dir="./my/custom/migration/path") create("my_first_migration") asyncio.run(up()) ``` -------------------------------- ### Run Pytest Suite for pyneo4j-ogm Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/README.md Command to execute the test suite for the pyneo4j-ogm project using `pytest` via `poetry`. It includes flags for asyncio mode and to ignore deprecation warnings. Some tests require a Neo4j instance running on `localhost:7687` with default credentials. ```bash poetry run pytest tests --asyncio-mode=auto -W ignore::DeprecationWarning ``` -------------------------------- ### Register Models from Directory with Pyneo4jClient Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This snippet demonstrates how to automatically discover and register all models within a specified directory and its subdirectories. The `register_models_from_directory()` method simplifies model registration for larger projects. This ensures all defined models are available for ORM operations. ```python ## Create a new client instance and connect ... await client.register_models_from_directory("path/to/models") ``` -------------------------------- ### Register Pre-Hooks for pyneo4j-ogm Models (Python) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Illustrates how to define and register pre-hooks for `pyneo4j-ogm` models. Hooks can be set in the `Settings` class under `pre_hooks` or dynamically using the `register_pre_hooks()` method, allowing custom code execution before a method call. Hook functions receive the class context and method arguments. ```python class Developer(NodeModel): ... class Settings: post_hooks = { "coffee.connect": lambda self, *args, **kwargs: print(f"{self.name} chugged another one!") } ## Or by calling the `register_pre_hooks()` method ## Here `hook_func` can be a synchronous or asynchronous function reference Developer.register_pre_hooks("create", hook_func) ## By using the `register_pre_hooks()` method, you can also overwrite all previously registered hooks ## This will overwrite all previously registered hooks for the defined hook name Developer.register_pre_hooks("create", hook_func, overwrite=True) ``` -------------------------------- ### Close Pyneo4jClient Database Connection Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md This example shows how to explicitly close an active database connection using the `Pyneo4jClient.close()` method. Closing the connection frees up resources and marks the client as disconnected. Attempting further queries after closing will result in a `NotConnectedToDatabase` exception. ```python ## Do some heavy-duty work... ## Finally done, so we close the connection to the database. await client.close() ``` -------------------------------- ### Create a New Node Model Instance Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md This snippet demonstrates how to create a new `Developer` node in the graph from a `NodeModel` instance. It initializes a `Developer` object with `name` and `age` and then persists it to the database using the `create()` method. After successful creation, the instance becomes 'hydrated' with database-assigned properties like `uid`. ```python ## Creates a node inside the graph with the properties and labels ## from the model below developer = Developer(name="John", age=24) await developer.create() print(developer) ## ``` -------------------------------- ### NodeModel Settings Class Properties Reference Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Reference documentation for the properties of the `Settings` class within a `NodeModel`. These properties allow customization of model behavior, including the registration of pre and post execution hooks, defining node labels, and configuring automatic fetching of related nodes. ```APIDOC NodeModel.Settings: pre_hooks: type: Dict[str, List[Callable]] description: A dictionary where the key is the name of the method for which to register the hook and the value is a list of hook functions. The hook function can be synchronous or asynchronous. All hook functions receive the exact same arguments as the method they are registered for and the current model instance as the first argument. Defaults to {}. post_hooks: type: Dict[str, List[Callable]] description: Same as pre_hooks, but the hook functions are executed after the method they are registered for. Additionally, the result of the method is passed to the hook as the second argument. Defaults to {}. labels: type: Set[str] description: A set of labels to use for the node. If no labels are defined, the name of the model will be used as the label. Defaults to the model name split by it's words. auto_fetch_nodes: type: bool description: Whether to automatically fetch nodes of defined relationship-properties when getting a model instance from the database. Auto-fetched nodes are available at the instance..nodes property. If no specific models are passed to a method when this setting is set to True, nodes from all defined relationship-properties are fetched. Defaults to False. ``` -------------------------------- ### Create New pyneo4j-ogm Migration File Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Migrations.md Command to generate a new migration file inside the configured migrations directory. The generated file will include 'up' and 'down' functions for defining migration logic. ```bash poetry run pyneo4j_ogm create my_first_migration ``` -------------------------------- ### Access pyneo4j-ogm Model Settings (Python) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Shows how to access the configuration settings of a `pyneo4j-ogm` model using the `model_settings()` method. This provides access to properties like labels and auto-fetch settings, returning a settings object. ```python model_settings = Developer.model_settings() print(model_settings) ## ``` -------------------------------- ### Apply Query Options for Pagination (Python) Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md Shows how to use the `options` argument with `find_connected_nodes()` to control the query results, such as skipping a number of results and limiting the total number of returned items, useful for pagination. ```python ## Skips the first 10 results and returns the next 20 developers = await producer.find_connected_nodes( { "$node": { "$labels": ["Developer", "Python"] }, "$relationships": [ { "$type": "PRODUCES", "with_love": True } ] }, options={ "limit": 20, "skip": 10 } ) print(developers) ## [, , ...] ``` -------------------------------- ### Configure pyneo4j-ogm Model Settings Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Models.md This Python snippet illustrates the basic structure for configuring `pyneo4j-ogm` models. It shows how an inner `Settings` class is defined within a `NodeModel` to control its behavior and interaction with the database. ```python class Coffee(NodeModel): flavour: str sugar: bool milk: bool class Settings: ## This is the place where the magic happens! ``` -------------------------------- ### Define Projections for Selective Data Retrieval in pyneo4j-ogm Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/Query.md Projections in pyneo4j-ogm allow users to return only specific properties of a model as a dictionary, reducing bandwidth and speeding up queries. They are defined as a dictionary mapping desired output keys to model property names. Only top-level mapping is supported. This example demonstrates mapping `name` to `dev_name` and `age` to `dev_age`, showing how non-existent properties result in `None`. ```python developer = await Developer.find_one({"name": "John"}, {"dev_name": "name", "dev_age": "age", "i_do_not_exist": "some_non_existing_property"}) print(developer) ## {"dev_name": "John", "dev_age": 24, "i_do_not_exist": None} ``` -------------------------------- ### pyneo4j-ogm Client.cypher() Method API Reference Source: https://github.com/groc-prog/pyneo4j-ogm/blob/main/docs/DatabaseClient.md Documentation for the `client.cypher()` method, which allows executing custom Cypher queries directly. It details the parameters required for the query, parameter binding, and options for model resolution. The method returns a tuple containing query results and returned variables. ```APIDOC client.cypher(query: str, parameters: dict, resolve_models: bool = True) -> tuple[list, list] query: The Cypher query string to execute. parameters: A dictionary of parameters to pass to the query. resolve_models: A boolean indicating whether the client should attempt to resolve models from the query results. Defaults to True. Returns: A tuple containing: - A list of results from the query. - A list of variables returned by the query. ```