### Full Query Execution Example Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Complete example demonstrating graph creation, GrandCypher initialization, and query execution with filters. ```python import networkx as nx from grandcypher import GrandCypher G = nx.DiGraph() G.add_node("Alice", age=30) G.add_node("Bob", age=25) G.add_edge("Alice", "Bob", relation="knows") gc = GrandCypher(G) result = gc.run(""" MATCH (a)-[r]->(b) WHERE a.age > 28 RETURN a, b, r """) ``` -------------------------------- ### Install GrandCypher from source Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Get-Started.md Clone the repository and install the package in editable mode. ```shell git clone https://github.com/aplbrain/grandcypher cd grandcypher pip3 install -e . ``` -------------------------------- ### Install Grand-Cypher Source: https://github.com/aplbrain/grand-cypher/blob/master/README.md Install the library using pip. ```shell pip install grand-cypher ``` -------------------------------- ### List predicate example Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Demonstrates the syntax for an ALL predicate expression. ```cypher ALL(r IN relationships(e) WHERE r.weight > 0) ``` -------------------------------- ### GrandCypher Integration Example Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Shows how the indexer is integrated into the query execution flow to prune search spaces. ```python # In GrandCypherExecutor._matches_iter() indexer = ArrayAttributeIndexer( entity_ids=list(target_graph.nodes()), entity_attributes=[target_graph.nodes[n] for n in target_graph.nodes()] ) indexer.create_indices(keys) # Index keys from WHERE clause # Convert WHERE condition to IndexerConditionAST ast = to_indexer_ast(where_condition) # Run indexer to get candidate entities entity_domain = IndexerConditionRunner(indexer).find(ast) # Pass candidates as hints to grandiso hints = hinter.index_domain_to_hints(entity_domain) ``` -------------------------------- ### IndexerConditionRunner Usage Example Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Demonstrates creating an indexer, defining a comparison condition, and executing it to find matching entities. ```python indexer = ArrayAttributeIndexer(entity_ids, entity_attributes) indexer.create_indices(["age"]) runner = IndexerConditionRunner(indexer) age_gt_25 = Compare(">", AttributeRef("a", "age"), 25) results = runner.find(age_gt_25) # results: {"a": [entities_with_age > 25]} ``` -------------------------------- ### Example Usage of ArrayAttributeIndexer Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Demonstrates initializing an ArrayAttributeIndexer with a NetworkX graph. ```python import networkx as nx from grandcypher.indexer import ArrayAttributeIndexer graph = nx.DiGraph() graph.add_node("A", weight=2, name="Alice") graph.add_node("B", weight=1, name="Bob") graph.add_node("C", weight=3, name="Charlie") indexer = ArrayAttributeIndexer( entity_ids=list(graph.nodes()), entity_attributes=[graph.nodes[n] for n in graph.nodes()] ) ``` -------------------------------- ### Chain unify zero-hop nodes example Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md Demonstrates collapsing a chain of nodes into a single representative node. ```python hop_specs = [ HopSpec(edge_id=("A", "B"), nodes=("A", "A"), hop_count=0), HopSpec(edge_id=("B", "C"), nodes=("B", "B"), hop_count=0) ] unified, alias = unify_zero_hop_nodes(motif, hop_specs) # alias: {"A": "A", "B": "A", "C": "A"} # unified nodes: {"A"} # All three motif nodes map to host node A ``` -------------------------------- ### Unify zero-hop nodes example Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md Demonstrates collapsing nodes connected by a zero-hop edge while maintaining normal edges. ```python from grandcypher.struct import unify_zero_hop_nodes, HopSpec motif = nx.DiGraph() motif.add_node("A") motif.add_node("B") motif.add_node("C") hop_specs = [ HopSpec(edge_id=("A", "B"), nodes=("A", "A"), hop_count=0), # Zero-hop HopSpec(edge_id=("B", "C"), nodes=("B", "C"), hop_count=1) # Normal ] unified, alias = unify_zero_hop_nodes(motif, hop_specs) # alias: {"A": "A", "B": "A", "C": "C"} # unified nodes: {"A", "C"} # unified edges: [("A", "C")] ``` -------------------------------- ### String Pattern Matching Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Examples of using CONTAINS, STARTS WITH, and ENDS WITH for string filtering. ```cypher WHERE a.email CONTAINS "@company" WHERE a.name STARTS WITH "Dr. " WHERE a.url ENDS WITH ".edu" ``` -------------------------------- ### Paginate Results with LIMIT and SKIP Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Examples of using LIMIT and SKIP clauses for result pagination. ```cypher LIMIT 10 SKIP 5 LIMIT 10 SKIP 5 ``` -------------------------------- ### Sort Results with ORDER BY Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Examples of sorting query results in ascending or descending order. ```cypher ORDER BY A.age DESC ORDER BY A.name ASC, B.age DESC ``` -------------------------------- ### Execute k-Hop Reachability Query Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Finds nodes reachable from a starting node within a path length of 1 to 3 edges. ```python gc.run(""" MATCH (start)-[*1..3]->(end) WHERE start.name = "Alice" RETURN end.name """) ``` -------------------------------- ### Query Language Clauses Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Examples of supported Cypher clauses for graph traversal and filtering. ```cypher MATCH (a)-[r]->(b) ``` ```cypher WHERE a.age > 25 ``` ```cypher RETURN a.name ``` ```cypher ORDER BY a.age DESC ``` ```cypher LIMIT 10 ``` ```cypher SKIP 5 ``` ```cypher RETURN DISTINCT a ``` -------------------------------- ### Define Graph Patterns with MATCH Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Examples of defining various graph patterns including labels, attributes, and variable-length paths. ```cypher MATCH (A)-[r]->(B) MATCH (A:Person)-[r:knows]->(B:Person) MATCH (A {age: 30})-[r {since: 2020}]->(B) ``` -------------------------------- ### Supported Value Types Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Examples of supported data types within attribute maps. ```cypher {id: 123} -- Integer {weight: 2.5} -- Float {name: "Alice"} -- String {active: true} -- Boolean {active: false} {value: NULL} -- Null {tags: ["a", "b", "c"]} -- List (in WHERE only) ``` -------------------------------- ### Complex Pattern Matching Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Example of a multi-hop query with filtering and aggregation. ```cypher MATCH (person:Person {active: true})-[r:knows {trust: "high"}]->(colleague) MATCH (colleague)-[*1..3]->(deep_contact) WHERE person.age >= 25 AND size(colleague.teams) > 1 AND (r.duration > 5 OR r.duration IS NULL) RETURN person.name, colleague.name, COUNT(deep_contact) AS connections, AVG(r.weight) AS avg_trust ORDER BY COUNT(deep_contact) DESC LIMIT 5 ``` -------------------------------- ### Specify Return Values with RETURN Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Examples of returning nodes, aliasing results, and applying distinct or aggregation functions. ```cypher RETURN A, B.name RETURN A AS node, COUNT(B) AS connections RETURN DISTINCT A ``` -------------------------------- ### Supported Value Types in Queries Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Syntax examples for filtering by various data types within Cypher WHERE clauses. ```cypher -- Null WHERE x IS NULL -- Boolean WHERE active = true WHERE deleted = false -- Integer WHERE age = 30 WHERE count > 100 -- Float WHERE weight = 2.5 WHERE price >= 19.99 -- String WHERE name = "Alice" WHERE status = "active" -- List (in WHERE only) WHERE tag IN ["work", "personal"] ``` -------------------------------- ### Nested Expressions in WHERE Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Examples of using arithmetic, size, and string functions within filter expressions. ```cypher WHERE (a.value * 2 + 10) > (b.threshold / 3) WHERE size(r.tags) * 2 <= a.max_tags WHERE trim(a.name) = trim(b.display_name) ``` -------------------------------- ### Filter Results with WHERE Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Examples of filtering query results using comparison, existence, and logical operators. ```cypher WHERE A.age > 25 AND B.name == "Bob" WHERE exists { MATCH (A)-[r]->(C) } WHERE NOT (A)-->(B) ``` -------------------------------- ### Generate edge hop specifications from a motif Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md Example usage of generate_edge_hop_specs with a NetworkX graph containing hop metadata. ```python import networkx as nx from grandcypher.struct import generate_edge_hop_specs motif = nx.DiGraph() motif.add_edge("A", "B", __min_hop__=1, __max_hop__=2) motif.add_edge("B", "C") # Default: 1 hop specs = generate_edge_hop_specs(motif) # specs[0]: [HopSpec(1-hop), HopSpec(2-hop)] # specs[1]: [HopSpec(1-hop)] ``` -------------------------------- ### Find Transitive Closure in Cypher Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Identifies all reachable nodes from a starting point. Use reasonable hop limits to prevent exponential performance degradation. ```cypher MATCH (start)-[*1..100]->(end) WHERE start.id = "node_1" RETURN DISTINCT end ``` -------------------------------- ### Import Main Entry Point Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/README.md Import the primary GrandCypher class to begin using the library. ```python from grandcypher import GrandCypher ``` -------------------------------- ### Full Workflow Execution Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Demonstrates initializing a NetworkX graph and executing a Cypher query using GrandCypher. ```python from grandcypher import GrandCypher import networkx as nx # Create graph G = nx.DiGraph() G.add_node("alice", age=30, role="Manager") G.add_node("bob", age=25, role="Developer") G.add_node("charlie", age=35, role="Lead") G.add_edge("alice", "bob", relation="manages", years=2) G.add_edge("bob", "charlie", relation="reports_to", years=1) # Query gc = GrandCypher(G) result = gc.run(""" MATCH (a:Person)-[r:manages]->(b) WHERE a.age > 25 RETURN a.name, b.name, r.relation ORDER BY a.age DESC LIMIT 10 """) print(result) ``` -------------------------------- ### GrandCypher.__init__ Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Initializes the GrandCypher query engine with a target NetworkX graph. ```APIDOC ## GrandCypher.__init__ ### Description Initializes the GrandCypher instance with a host graph and optional default query limit. ### Parameters - **host_graph** (nx.Graph) - Required - The NetworkX graph to query (DiGraph or MultiDiGraph). - **limit** (int) - Optional - Default result limit for queries. ``` -------------------------------- ### Initialize GrandCypher Class Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Constructor signature for the GrandCypher class. ```python class GrandCypher: def __init__(self, host_graph: nx.Graph, limit: int = None) -> None ``` -------------------------------- ### Initialize UnionFind Class Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md Basic structure and method signatures for the UnionFind class. ```python from grandcypher.struct import UnionFind class UnionFind: def __init__(self) def find(self, x: NodeID) -> NodeID def union(self, a: NodeID, b: NodeID) -> None ``` -------------------------------- ### Import Indexing Utilities Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/README.md Import indexer classes and condition runners for query optimization. ```python from grandcypher.indexer import ( ArrayAttributeIndexer, IncrementIndexQuerier, NoIndexQuerier, Compare, AND, OR, IndexerConditionRunner ) ``` -------------------------------- ### Initialize IndexerConditionRunner Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Import and initialize the runner with an existing indexer instance. ```python from grandcypher.indexer import IndexerConditionRunner class IndexerConditionRunner: def __init__(self, indexer: ArrayAttributeIndexer) ``` -------------------------------- ### Define variable-length edge patterns Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md Examples of Cypher patterns involving variable-length edges and zero-hop constraints. ```cypher MATCH (a)-[*1..3]->(b) ``` ```cypher MATCH (a)-[*1..2]->(b)-[*1..2]->(c) ``` ```cypher MATCH (a)-[*0]->(b)-[*1..2]->(c) ``` -------------------------------- ### Initialize GrandCypherExecutor Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Instantiate the core query execution engine with a target graph and optional result limit. ```python from grandcypher import GrandCypherExecutor class GrandCypherExecutor: def __init__(self, target_graph: nx.Graph, limit: Optional[int] = None) ``` -------------------------------- ### Execute Aggregation Query Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Demonstrates the use of aggregation functions within a RETURN clause. ```python result = gc.run(""" MATCH (a)-[r]->(b) RETURN a.name, COUNT(b) as num_connections """) ``` -------------------------------- ### Test Queries with Minimal Graphs Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Uses NetworkX to construct a small graph for verifying query results and structure. ```python import networkx as nx from grandcypher import GrandCypher # Create minimal test graph G = nx.DiGraph() G.add_node("A", type="X") G.add_node("B", type="X") G.add_edge("A", "B", label="knows") gc = GrandCypher(G) result = gc.run("MATCH (a)-[r]->(b) RETURN a, b") print(result) # Verify structure ``` -------------------------------- ### GrandCypher.set_hints Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Configures optimization hints for the GrandCypher instance. ```APIDOC ## set_hints(hints) ### Description Sets optimization hints for subsequent queries. ### Parameters - **hints** (dict) - Required - The hints configuration. ### Returns - **GrandCypher** - Returns the instance for method chaining. ``` -------------------------------- ### GrandCypher Usage Flow Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Demonstrates the end-user interface and the internal steps taken during query execution. ```python # End-user code gc = GrandCypher(graph) result = gc.run("MATCH (a)-[r]->(b) WHERE a.age > 25 RETURN a, b") # Internal flow: # 1. GrandCypher.run() parses the query # 2. GrandCypherTransformer converts AST to executor state # 3. GrandCypherExecutor processes the query: # a. _get_true_matches() finds all valid matches # b. _lookup() extracts return values # c. returns() applies ORDER BY/DISTINCT/LIMIT # 4. Result dict returned to user ``` -------------------------------- ### Run a Cypher query with hints Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Hints.md Pass a list of dictionaries to the run method where each dictionary maps query variable names to node IDs. ```python gc = GrandCypher(graph) result = gc.run(query, hints=[{"A": 1}, {"B": 2}]) ``` -------------------------------- ### Initialize GrandCypher Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Instantiate the class with a target NetworkX graph and an optional result limit. ```python gc = GrandCypher(host_graph, limit=None) ``` -------------------------------- ### set_hints(hints) Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Set optimization hints for grandiso matching to restrict search space. ```APIDOC ## set_hints(hints) ### Description Set optimization hints for grandiso matching. Speeds up graph isomorphism matching by restricting search space. ### Parameters - **hints** (list[dict]) - Partial node mappings to guide matching ### Returns GrandCypherExecutor (Self for method chaining) ### Example ```python executor.set_hints([{"A": "node1", "B": "node2"}]) ``` ``` -------------------------------- ### Import Data Structures Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/README.md Import structural components for defining hops, matches, and edge mappings. ```python from grandcypher.struct import ( HopSpec, Match, EdgeMapping, EdgePath, EdgeWithKey, UnionFind, MotifToHostView ) ``` -------------------------------- ### GrandCypher.run Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Executes a Cypher query string against the initialized graph. ```APIDOC ## GrandCypher.run ### Description Executes a Cypher query on the host graph and returns the matched results. ### Parameters - **cypher** (str) - Required - The Cypher query to execute. - **hints** (list[dict]) - Optional - Partial-mapping hints passed to grandiso.find_motifs. ### Returns - **Dict[str, List]** - Dictionary mapping return items to list of matched values. ``` -------------------------------- ### Run Cypher Queries on SQL Backend Source: https://github.com/aplbrain/grand-cypher/blob/master/README.md Use the Grand library with a SQL backend to persist graph data and execute Cypher queries. ```python import grand from grandcypher import GrandCypher G = grand.Graph( backend=grand.backends.SQLBackend( db_url="my_persisted_graph.db", directed=True ) ) # use the networkx-style API for the Grand library: G.nx.add_node("A", foo="bar") G.nx.add_edge("A", "B") G.nx.add_edge("B", "C") G.nx.add_edge("C", "A") GrandCypher(G.nx).run(""" MATCH (A)-[]->(B)-[]->(C) MATCH (C)-[]->(A) WHERE A.foo == "bar" RETURN A, B, C """) ``` -------------------------------- ### Initialize AttributeRef Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Represents an attribute reference such as A.name. ```python from grandcypher.types import AttributeRef ref = AttributeRef("A", "name") # Equivalent to: A.name ``` -------------------------------- ### Initialize EntityRef Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Represents a bare node or edge reference in a query. ```python from grandcypher.types import EntityRef ref = EntityRef("A") ``` -------------------------------- ### Execute Query and Return Results Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Returns a dictionary mapping return item names to lists of values after applying aggregation, sorting, and pagination. ```python result = executor.returns() ``` ```python executor = GrandCypherExecutor(graph, limit=10) # ... set up motif, where condition, etc ... result = executor.returns() # result: {'A': [node1, node2, ...], 'B': [node3, node4, ...]} ``` -------------------------------- ### Execute Query with Labels and Properties Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Filters by specific node labels and inline property constraints. ```python result = gc.run(""" MATCH (a:Person)-[r:knows]->(b:Person {age: 30}) RETURN a.name """) ``` -------------------------------- ### ArrayAttributeIndexer.__init__ Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Initializes a new ArrayAttributeIndexer instance with entity IDs and their corresponding attribute dictionaries. ```APIDOC ## ArrayAttributeIndexer.__init__(entity_ids, entity_attributes) ### Description Initializes the master indexer that manages multiple attribute indices. ### Parameters - **entity_ids** (list) - Required - IDs of all entities (e.g., node names). - **entity_attributes** (list) - Required - Full attribute dictionaries for each entity. ``` -------------------------------- ### Constrain search space with query hints Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Use hints to provide partial node mappings for faster graph isomorphism searches in large graphs. ```python from grandcypher import GrandCypher gc = GrandCypher(large_graph) # Without hints: searches full graph result1 = gc.run("MATCH (a)-[r]->(b) RETURN a, b") # With hints: searches only edges from known nodes hints = [{"a": "node_alice", "b": "node_bob"}] result2 = gc.run( "MATCH (a)-[r]->(b) RETURN a, b", hints=hints ) ``` -------------------------------- ### View GrandCypher Module Hierarchy Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Visual representation of the library's internal file structure. ```text grandcypher/ ├── __init__.py # Main entry point ├── types.py # Type definitions ├── struct.py # Graph structures and algorithms ├── indexer.py # Attribute indexing └── hinter.py # Grandiso hint generation ``` -------------------------------- ### Run a Cypher query on a NetworkX graph Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Get-Started.md Initialize GrandCypher with a NetworkX graph object and execute a MATCH query. ```python from grandcypher import GrandCypher import networkx as nx my_graph = nx.read_graphml("my-fun-graph.graphml") # Get a list of all edges in the graph: results = GrandCypher(my_graph).run(""" MATCH (A)-[]->(B) RETURN A, B """) ``` -------------------------------- ### Set optimization hints Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Provides partial node mappings to restrict the search space for graph isomorphism matching. ```python executor.set_hints([{"A": "node1", "B": "node2"}]) return executor # Supports chaining ``` -------------------------------- ### Create Node Indices Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Experimental method to index node attributes for improved lookup performance. ```python gc.create_node_indices(["age", "name"]) ``` -------------------------------- ### Node and Edge Attribute Assignment Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Demonstrates how to add nodes and edges with attributes using Python dictionaries. ```python G.add_node("alice", age=30, name="Alice", tags=["person"]) G.add_edge("a", "b", weight=2.5, label="knows") ``` -------------------------------- ### gc.run(query) Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Executes a graph query string and returns the results as a dictionary where keys are the returned entity names and values are lists of matches. ```APIDOC ## gc.run(query) ### Description Executes a Cypher-like query against the graph database. Results are returned as a dictionary mapping return variables to lists of node or edge data. ### Parameters - **query** (string) - Required - The Cypher query string to execute. ### Response - **result** (dict) - A dictionary where keys are the returned entity names and values are lists of node or edge data dictionaries. ### Example ```python result = gc.run("MATCH (a)-[r]->(b) RETURN a, b") # Result format: # { # 'a': [{'name': 'Alice', 'age': 30}], # 'b': [{'name': 'Bob', 'age': 25}] # } ``` ``` -------------------------------- ### Apply Pagination Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Applies SKIP and LIMIT constraints to the result dictionary by slicing value lists uniformly. ```python paginated = executor._apply_pagination(results, ignore_limit=False) ``` -------------------------------- ### Match Nodes with Labels Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Demonstrates syntax for filtering nodes by single, multiple, or alternative labels. ```cypher MATCH (a:Person) -- Single label MATCH (a:Person:Employee) -- Multiple labels (all must match) MATCH (a:Person|Employee) -- Alternative syntax ``` -------------------------------- ### Create Indices Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Builds indices for the specified attribute keys. ```python indexer.create_indices(["weight", "age"]) ``` -------------------------------- ### Query Result Format Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Demonstrates the structure of the returned dictionary containing entity matches. ```python result = gc.run("MATCH (a)-[r]->(b) RETURN a, b") # Result format: # { # 'a': [node1_data, node2_data, ...], # 'b': [node1_data, node2_data, ...] # } ``` -------------------------------- ### Execute Multi-Hop Query with Constraints Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Traverses two hops while enforcing weight comparisons between the relationship edges. ```python gc.run(""" MATCH (a)-[r1]->(b) MATCH (b)-[r2]->(c) WHERE a.type = "root" AND r1.weight > r2.weight RETURN a, b, c """) ``` -------------------------------- ### Execute Cypher Query Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Basic usage of the run method to execute a Cypher query on a graph. ```python gc = GrandCypher(my_graph) result = gc.run("MATCH (A)-[]->(B) RETURN A, B") ``` -------------------------------- ### Execute Variable-Length Path Query Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Traverses paths of varying lengths between nodes using the [*min..max] syntax. ```python result = gc.run(""" MATCH (a)-[*1..3]->(b) WHERE a.name == "Alice" RETURN b.name """) ``` -------------------------------- ### Match Variable-Length Paths Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Syntax for defining path depth constraints using hop counts. ```cypher MATCH (a)-[*]->(b) -- Any length (0 or more) MATCH (a)-[*1..3]->(b) -- 1 to 3 hops MATCH (a)-[*2..]->(b) -- 2 or more hops MATCH (a)-[*..3]->(b) -- Up to 3 hops MATCH (a)-[*2]->(b) -- Exactly 2 hops ``` -------------------------------- ### Execute Scalar Functions in Python Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Demonstrates using scalar functions like toLower and size within a GrandCypher query executed via Python. ```python result = gc.run(""" MATCH (a)-[r]->(b) WHERE toLower(a.name) == "alice" RETURN size(r.tags) as tag_count """) ``` -------------------------------- ### Apply list predicates Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Expressions.md Uses the ALL predicate to verify conditions across a relationship list. ```cypher MATCH (a)-[r*2]->(b) WHERE ALL(edge IN relationships(r) WHERE edge.weight > 5) RETURN ID(a), ID(b) ``` -------------------------------- ### Apply compound list predicates Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Expressions.md Demonstrates using compound conditions within a list predicate. ```cypher MATCH (a)-[r*2]->(b) WHERE ALL( edge IN relationships(r) WHERE edge.weight > 5 AND edge.kind = "friend" ) RETURN ID(a), ID(b) ``` -------------------------------- ### Querying nodes and edges with __labels__ Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Label-Convention.md Demonstrates defining node and edge labels using the __labels__ attribute and executing a Cypher query. ```python from grandcypher import GrandCypher import networkx as nx G = nx.Graph() G.add_node(1, name="Douglas Adams", __labels__=["Person"]) G.add_node(2, name="The Hitchhiker's Guide to the Galaxy", __labels__=["Book"]) G.add_edge(1, 2, __labels__=["AUTHORED"]) GrandCypher(G).run(""" MATCH (a:Person)-[e]->(b:Book) RETURN a.name, b.name """) ``` -------------------------------- ### Improve query performance with early filtering Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Combine ORDER BY with LIMIT and pre-filtering WHERE clauses to reduce the number of matches processed. ```python # Gets ALL results, then sorts, then limits (inefficient) result = gc.run(""" MATCH (a)-[r]->(b) RETURN a, COUNT(b) AS connections ORDER BY connections DESC LIMIT 10 """) # Faster when combined with WHERE to reduce matches result = gc.run(""" MATCH (a)-[r]->(b) WHERE a.category = "important" RETURN a, COUNT(b) AS connections ORDER BY connections DESC LIMIT 10 """) ``` -------------------------------- ### Visualize Graph Results with NetworkX Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Constructs a directed graph from query results and renders it using Matplotlib. ```python import matplotlib.pyplot as plt from networkx.drawing import draw_networkx result = gc.run("MATCH (a)-[]->(b) RETURN a, b") # Draw matched edges G_match = nx.DiGraph() for i in range(len(result["a"])): a = result["a"][i].get("id", result["a"][i]) b = result["b"][i].get("id", result["b"][i]) G_match.add_edge(a, b) draw_networkx(G_match) plt.show() ``` -------------------------------- ### Execute Simple Match Query Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Filters nodes based on attribute conditions using a WHERE clause. ```python result = gc.run(""" MATCH (a)-[r]->(b) WHERE a.age > 25 RETURN a.name, b.name """) ``` -------------------------------- ### Import Type Definitions Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/README.md Import core type references used for entity, attribute, and expression handling. ```python from grandcypher.types import EntityRef, AttributeRef, IDRef, ExpressionBase ``` -------------------------------- ### Compose scalar functions in Cypher Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Expressions.md Demonstrates nesting scalar functions and using them in comparison operations. ```cypher MATCH (n) WHERE toLower(trim(n.name)) = toLower(n.canonical_name) RETURN ID(n), toUpper(n.name) ``` -------------------------------- ### Handling NULL values in queries Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Shows how to filter for NULL attributes and use the coalesce function to provide default values. ```python # Adding nodes with NULL attributes G.add_node("user1", age=30, email=None) G.add_node("user2", age=None, email="user@example.com") gc = GrandCypher(G) # Match null values result = gc.run(""" MATCH (u) WHERE u.email IS NULL RETURN u.age """) # Coalesce for defaults result = gc.run(""" MATCH (u) RETURN u.name, coalesce(u.email, "no-email") AS contact """) ``` -------------------------------- ### Using Aggregation Functions in Cypher Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/examples.md Shows how to apply the SUM aggregation function to edge attributes during a Cypher query. ```python from grandcypher import GrandCypher import networkx as nx host = nx.MultiDiGraph() host.add_node("a", name="Alice", age=25) host.add_node("b", name="Bob", age=30) host.add_edge("a", "b", __labels__={"paid"}, amount=12, date="12th June") host.add_edge("b", "a", __labels__={"paid"}, amount=6) host.add_edge("b", "a", __labels__={"paid"}, value=14) host.add_edge("a", "b", __labels__={"friends"}, years=9) host.add_edge("a", "b", __labels__={"paid"}, amount=40) qry = """ MATCH (n)-[r:paid]->(m) RETURN n.name, m.name, SUM(r.amount) """ res = GrandCypher(host).run(qry) print(res) ``` ```json { "n.name": ["Alice", "Bob"], "m.name": ["Bob", "Alice"], "SUM(r.amount)": [{"paid": 52}, {"paid": 6}], } ``` -------------------------------- ### Querying a Multigraph with GrandCypher Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/examples.md Demonstrates executing a Cypher query on a NetworkX MultiDiGraph to retrieve node properties and edge attributes. ```python from grandcypher import GrandCypher import networkx as nx host = nx.MultiDiGraph() host.add_node("a", name="Alice", age=25) host.add_node("b", name="Bob", age=30) host.add_edge("a", "b", __labels__={"paid"}, amount=12, date="12th June") host.add_edge("b", "a", __labels__={"paid"}, amount=6) host.add_edge("b", "a", __labels__={"paid"}, value=14) host.add_edge("a", "b", __labels__={"friends"}, years=9) host.add_edge("a", "b", __labels__={"paid"}, amount=40) qry = """ MATCH (n)-[r:paid]->(m) RETURN n.name, m.name, r.amount """ res = GrandCypher(host).run(qry) print(res) ``` ```json { "n.name": ["Alice", "Bob"], "m.name": ["Bob", "Alice"], "r.amount": [ {(0, "paid"): 12, (1, "paid"): 40}, {(0, "paid"): 6, (1, "paid"): None}, ], } ``` -------------------------------- ### Iterate Motif Matches Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Iterates through all possible motif matches in the host graph, yielding dictionaries that map motif node names to host node IDs. ```python for match_dict in executor._matches_iter(motif): print(match_dict) ``` -------------------------------- ### Retrieve graph data with _lookup Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Extracts values from the host graph based on specified paths and pagination limits. ```python result = executor._lookup( data_paths=["A", "B.name", "ID(C)"], offset_limit=slice(0, 10) ) ``` -------------------------------- ### Execute Condition AST Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Use the find method to execute a condition AST and retrieve matching entities. ```python runner = IndexerConditionRunner(indexer) results = runner.find(cond_ast) ``` -------------------------------- ### Define AND condition class Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Initializes a logical AND operation between two conditions. ```python class AND(BoolCondition): def __init__(self, condition_a: CONDITION, condition_b: CONDITION) ``` -------------------------------- ### Implement the expression evaluation protocol Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Architecture.md Runtime expressions must implement this method to support evaluation against matches, host graphs, and optional scopes. ```python evaluate(match, host, return_edges, scope=None) ``` -------------------------------- ### Implement UnionFind for node unification Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/types-reference.md Uses the Union-Find data structure to manage disjoint sets of nodes during unification processes. ```python from grandcypher.struct import UnionFind class UnionFind: def find(self, x: NodeID) -> NodeID def union(self, a: NodeID, b: NodeID) -> None ``` ```python uf = UnionFind() uf.union("A", "B") uf.union("B", "C") assert uf.find("A") == uf.find("B") == uf.find("C") # All three return the same representative ``` -------------------------------- ### Compare Class Definition and Usage Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Defines binary comparison operations for indexer conditions. ```python from grandcypher.indexer import Compare class Compare(IndexerConditionAST): def __init__(self, operator: str, left, right) ``` ```python from grandcypher.types import AttributeRef from grandcypher.indexer import Compare # age > 25 cond = Compare(">", AttributeRef("a", "age"), 25) ``` -------------------------------- ### Initialize ArrayAttributeIndexer Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Constructor for the ArrayAttributeIndexer class which manages multiple attribute indices. ```python from grandcypher.indexer import ArrayAttributeIndexer class ArrayAttributeIndexer: def __init__(self, entity_ids: list, entity_attributes: list) ``` -------------------------------- ### Match graph patterns Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Retrieve nodes and relationships using various path matching techniques. ```cypher MATCH (a)-[r]->(b) RETURN a.name, b.name ``` ```cypher MATCH (a)-[r1]->(x)-[r2]->(b) RETURN a, x, b ``` ```cypher MATCH (a)-[*1..3]->(b) RETURN a.name, b.name ``` -------------------------------- ### Validate Query Syntax Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Wraps query execution in a try-except block to catch and handle syntax errors. ```python try: result = gc.run("MATCH (a)-[r]->(b) WHERE invalid syntax") except Exception as e: print(f"Syntax error: {e}") ``` -------------------------------- ### Integrate struct module in GrandCypherExecutor Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md The _edge_hop_motifs method orchestrates motif generation, assignment, materialization, and unification. ```python def _edge_hop_motifs(self, motif): # Step 1: Generate all hop specification options hop_specs = generate_edge_hop_specs(motif) # Step 2: Generate all possible hop assignments hop_assignments = generate_hop_assignments(hop_specs) for hop_assignment in hop_assignments: # Step 3: Expand motif according to assignment materialized = materialize_motif(hop_assignment, motif) # Step 4: Unify zero-hop nodes unified, alias = unify_zero_hop_nodes(materialized, hop_assignment.values()) # Step 5: Yield unified motif for graph isomorphism matching yield unified, hop_assignment, alias ``` -------------------------------- ### List Predicates in WHERE Clause Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Tests conditions across collections of relationships. ```cypher WHERE ALL(r IN relationships(e) WHERE r.weight > 0) WHERE ANY(r IN relationships(e) WHERE r.weight < 0) WHERE NONE(r IN relationships(e) WHERE r.weight IS NULL) WHERE SINGLE(r IN relationships(e) WHERE r.approved = true) ``` -------------------------------- ### Execute Multiple Match Clauses Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Chains multiple MATCH clauses to traverse deeper paths in the graph. ```python result = gc.run(""" MATCH (a)-[r1]->(b) MATCH (b)-[r2]->(c) WHERE a.name == "Alice" RETURN a.name, b.name, c.name """) ``` -------------------------------- ### UnsupportedOp Class Definition Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md A placeholder class for conditions that cannot be optimized via indexing. ```python from grandcypher.indexer import UnsupportedOp class UnsupportedOp(IndexerConditionAST): pass ``` -------------------------------- ### executor.returns() Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Executes the complete query and returns the results as a dictionary mapping return item names to lists of values. ```APIDOC ## Method: returns() -> Dict[str, List] ### Description Executes the complete query, applying aggregation, aliasing, sorting, distinct filtering, and pagination, then returns the final result set. ### Returns - **Dict[str, List]** - A dictionary mapping return item names to lists of values. ### Example ```python executor = GrandCypherExecutor(graph, limit=10) result = executor.returns() # result: {'A': [node1, node2, ...], 'B': [node3, node4, ...]} ``` ``` -------------------------------- ### GrandCypher Class Methods Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/README.md Methods available on the GrandCypher instance for graph interaction and query execution. ```APIDOC ## GrandCypher Class ### __init__(graph, limit=None) Initializes a new GrandCypher instance. ### run(cypher, hints=None) Executes a Cypher query against the graph. Returns a dictionary of results. ### create_node_indices(keys) Creates indices for the specified keys. Returns the GrandCypher instance. ### set_hints(hints) Configures query hints for optimization. Returns the GrandCypher instance. ``` -------------------------------- ### Initialize IDRef Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Represents an ID reference using the ID() function. ```python from grandcypher.types import IDRef ref = IDRef("A") # Equivalent to: ID(A) ``` -------------------------------- ### Troubleshoot No Matches Found in Grand Cypher Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Verify graph structure and attribute existence by running simplified queries to isolate missing data. ```python # Check if pattern exists in smaller scope result = gc.run("MATCH (n) RETURN n") # Check nodes exist result = gc.run("MATCH (a)-[]->(b) RETURN a, b") # Check edges # Verify attributes result = gc.run("MATCH (n {attr: value}) RETURN n") ``` -------------------------------- ### Inspect Query Motif Structure Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Visualizes the mapping between Cypher query patterns and the resulting internal motif structure. ```python # Query structure → motif structure # MATCH (a:Person {age: 30})-[r:knows {since: 2020}]->(b:Person) # Creates motif: # Nodes: {a: {__labels__: {Person}, age: 30}, b: {__labels__: {Person}}} # Edges: {(a,b): {__labels__: {knows}, since: 2020}} ``` -------------------------------- ### Basic RETURN Clause Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Retrieve specific nodes, properties, or combinations of data. ```cypher RETURN a RETURN a, b RETURN a.name, b.age ``` -------------------------------- ### Existence Checks in WHERE Clause Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Verifies the existence of patterns using subqueries. ```cypher WHERE EXISTS { MATCH (a)-[r]->(c) RETURN r } WHERE EXISTS { MATCH (a)-[r]->(c) WHERE c.active = true RETURN c } ``` -------------------------------- ### Aliasing in RETURN Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Rename output columns using the AS keyword. ```cypher RETURN a AS person RETURN a.name AS person_name RETURN COUNT(b) AS friend_count ``` -------------------------------- ### Perform aggregation and sorting Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/module-overview.md Aggregates query results using functions like COUNT and sorts the output using ORDER BY. ```python result = gc.run(""" MATCH (person)-[]->(contact) RETURN person.name, COUNT(contact) AS num_contacts ORDER BY num_contacts DESC LIMIT 10 """) ``` -------------------------------- ### Match Edge Labels Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Demonstrates syntax for filtering relationships by specific or alternative labels. ```cypher MATCH ()-[r:knows]->() MATCH ()-[r:knows|friends]->() -- Any of these labels ``` -------------------------------- ### _lookup(data_paths, offset_limit) Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Retrieve values from the host graph for specified data paths, supporting node references, attributes, and expressions. ```APIDOC ## _lookup(data_paths, offset_limit) ### Description Retrieve values from host graph for specified data paths. Supports node references, node attributes, edge references, edge attributes, ID references, and expression objects. ### Parameters - **data_paths** (list) - Entities/attributes to extract - **offset_limit** (slice) - Result pagination ### Returns Dictionary mapping paths to lists of values. ### Example ```python result = executor._lookup( data_paths=["A", "B.name", "ID(C)"], offset_limit=slice(0, 10) ) ``` ``` -------------------------------- ### Node and Edge Data Structure Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Shows the dictionary format for individual node and edge attributes. ```python # Example node: {'name': 'Alice', 'age': 30} # Example edge: {'weight': 2.5, 'since': 2020} ``` -------------------------------- ### IndexerConditionRunner.find(condition_ast) Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Executes a condition AST against the initialized indexer to return a mapping of entities that satisfy the provided condition. ```APIDOC ## IndexerConditionRunner.find(condition_ast) ### Description Executes a condition AST against the indexer and returns a dictionary mapping entities to matching results. ### Signature `find(condition_ast: IndexerConditionAST) -> IndexDomainType` ### Parameters - **condition_ast** (IndexerConditionAST) - Required - The condition tree to evaluate against the indexer. ### Returns - **IndexDomainType** - A dictionary mapping entities to matching results. ### Example ```python runner = IndexerConditionRunner(indexer) age_gt_25 = Compare(">", AttributeRef("a", "age"), 25) results = runner.find(age_gt_25) # results: {"a": [entities_with_age > 25]} ``` ``` -------------------------------- ### Define unify_zero_hop_nodes function signature Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md The function signature for unifying nodes based on zero-hop specifications. ```python from grandcypher.struct import unify_zero_hop_nodes def unify_zero_hop_nodes( motif: nx.DiGraph, hop_specs: list[HopSpec] ) -> tuple[nx.DiGraph, dict[str, str]] ``` -------------------------------- ### Define OR condition class Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/executor-reference.md Initializes a logical OR operation between two conditions. ```python class OR(BoolCondition): def __init__(self, condition_a: CONDITION, condition_b: CONDITION) ``` -------------------------------- ### Retrieve and Use Index Querier Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Retrieves a querier for a specific attribute and performs a comparison query. ```python querier = indexer.get_index_querier("weight") results = querier.gt(2) # weight > 2 ``` -------------------------------- ### Initialize IncrementIndexQuerier Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Define the IncrementIndexQuerier class structure for indexing sorted attributes. ```python from grandcypher.indexer import IncrementIndexQuerier class IncrementIndexQuerier: def __init__(self, key: Any, indexed_entity_ids: list, indexed_entity_attributes: list) ``` -------------------------------- ### AND Class Definition and Usage Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Represents a logical AND operation, returning the intersection of two conditions. ```python from grandcypher.indexer import AND class AND(IndexerConditionAST): def __init__(self, left: IndexerConditionAST, right: IndexerConditionAST) ``` ```python # age > 25 AND name == "Alice" cond_age = Compare(">", AttributeRef("a", "age"), 25) cond_name = Compare("==", AttributeRef("a", "name"), "Alice") combined = AND(cond_age, cond_name) ``` -------------------------------- ### Accessing Raw Results in Python Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Iterates through the dictionary-based result structure returned by gc.run. ```python result = gc.run("MATCH (a)-[r]->(b) RETURN a, r.weight, b") # result is a dict: {"a": [...], "r.weight": [...], "b": [...]} # All lists have the same length for i in range(len(result["a"])): node_a = result["a"][i] weight = result["r.weight"][i] node_b = result["b"][i] print(f"{node_a} --[{weight}]--> {node_b}") ``` -------------------------------- ### Aggregation in RETURN Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/query-syntax-reference.md Combine grouping keys with aggregate functions. ```cypher RETURN a.department, COUNT(a) AS emp_count, AVG(a.salary) RETURN a.name, COUNT(b) AS connections ``` -------------------------------- ### Perform attribute comparisons Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/indexer-reference.md Execute various comparison operations on indexed attributes to retrieve entity IDs. ```python result = querier.lt(100) ``` ```python result = querier.gt(50) ``` ```python result = querier.ge(50) ``` ```python result = querier.le(100) ``` ```python result = querier.eq(42) ``` ```python result = querier.ne(0) ``` -------------------------------- ### Perform Batch Processing Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/advanced-usage.md Processes large datasets in chunks to manage memory usage effectively. ```python # Process in chunks to reduce memory node_ids = ["node1", "node2", "node3", ...] for batch in chunks(node_ids, size=100): hints = [{"n": nid} for nid in batch] for hint in hints: result = gc.run("MATCH (n)-[]->(m) RETURN m", hints=[hint]) # Process result ``` -------------------------------- ### Execute Aggregation Query Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/api-reference-grandcypher.md Performs calculations on graph data using aggregation functions like COUNT and AVG. ```python result = gc.run(""" MATCH (a)-[r]->(b) RETURN a.name, COUNT(b) as friends, AVG(r.weight) as avg_weight """) ``` -------------------------------- ### Access relationship lists Source: https://github.com/aplbrain/grand-cypher/blob/master/docs/Expressions.md Uses relationships() to retrieve sequences for variable-length paths. ```cypher MATCH (a)-[r*1..3]->(b) WHERE size(relationships(r)) = 2 RETURN ID(a), ID(b) ``` -------------------------------- ### Generate hop assignments Source: https://github.com/aplbrain/grand-cypher/blob/master/_autodocs/struct-reference.md Computes the Cartesian product of all edge hop options to create multiple materialized motifs. ```python from grandcypher.struct import generate_hop_assignments def generate_hop_assignments(all_edge_hops: list[list[HopSpec]]) -> Generator[HopAssignment, None, None] ``` ```python from grandcypher.struct import generate_hop_assignments, generate_edge_hop_specs # Query: (A)-[*1..2]->(B)-[*1]->(C) specs = generate_edge_hop_specs(motif) # [[HopSpec(1), HopSpec(2)], [HopSpec(1)]] assignments = list(generate_hop_assignments(specs)) # Assignment 1: {("A","B"): HopSpec(1-hop), ("B","C"): HopSpec(1-hop)} # Assignment 2: {("A","B"): HopSpec(2-hop), ("B","C"): HopSpec(1-hop)} assert len(assignments) == 2 ```