Skip to content
Feeding a clanker? Grab this page as raw .md →

Neo4jWidget API#

Neo4jWidget showing a Cypher query result as a graph of movie and person nodes joined by ACTED_IN relationships, with label filter chips above

Neo4jWidget takes a neo4j driver (or a uri plus auth), reads the database's labels, relationship types and property keys up front, and puts a Cypher input above a graph view of whatever the query returns. Clicking a node runs a follow-up query to pull in its neighbors, so you can walk outward from a small result instead of writing ever-longer Cypher. What is on screen stays readable from Python via nodes, relationships, selected_nodes and selected_relationships.

It talks to a real database, so this page has no in-browser demo — run it on molab against your own server instead. See also: GraphWidget for graphs you build in Python, EdgeDraw for sketching one by hand, and Treemap for hierarchies rather than graphs.

Who can run queries#

Anyone who can see the widget can type Cypher into the query box, and it runs with the credentials of the driver you passed in. By default (read_only=True) queries from the query box run in a read-access session, so the database refuses writes such as CREATE or DETACH DELETE; pass read_only=False to allow writes. initial_query and run_query(), which you call from Python, are not restricted. When you publish a notebook, also connect with a database account that only has read rights.

Bases: AnyWidget

Interactive Neo4j graph explorer with Cypher query input.

Anyone who can see the widget can run Cypher through its query box with the driver's credentials. By default (read_only=True) those queries run in a read-access session, so writes such as CREATE or DELETE are refused by the server. For published notebooks, also connect with a database account that only has read rights.

Examples:

import marimo as mo
from neo4j import GraphDatabase
from wigglystuff import Neo4jWidget

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
widget = mo.ui.anywidget(Neo4jWidget(driver))
widget

Create a Neo4jWidget.

Parameters:

Name Type Description Default
driver

A neo4j Driver. Provide this or uri.

None
uri Optional[str]

Bolt URI used to create a driver when driver is not given.

None
auth Optional[tuple]

Auth tuple passed to GraphDatabase.driver with uri.

None
database Optional[str]

Database name to query (defaults to the server default).

None
width int

Widget width in pixels.

800
height int

Widget height in pixels.

500
max_nodes int

Maximum number of nodes kept when expanding.

300
initial_query Optional[str]

Cypher query to run from Python on creation.

None
read_only bool

Run queries from the query box in a read-access session so the database refuses writes.

True
Source code in wigglystuff/neo4j_widget.py
def __init__(
    self,
    driver=None,
    *,
    uri: Optional[str] = None,
    auth: Optional[tuple] = None,
    database: Optional[str] = None,
    width: int = 800,
    height: int = 500,
    max_nodes: int = 300,
    initial_query: Optional[str] = None,
    read_only: bool = True,
    **kwargs: Any,
) -> None:
    """Create a Neo4jWidget.

    Args:
        driver: A `neo4j` Driver. Provide this or `uri`.
        uri: Bolt URI used to create a driver when `driver` is not given.
        auth: Auth tuple passed to `GraphDatabase.driver` with `uri`.
        database: Database name to query (defaults to the server default).
        width: Widget width in pixels.
        height: Widget height in pixels.
        max_nodes: Maximum number of nodes kept when expanding.
        initial_query: Cypher query to run from Python on creation.
        read_only: Run queries from the query box in a read-access session
            so the database refuses writes.
    """
    if driver is not None:
        self._driver = driver
    elif uri is not None:
        from neo4j import GraphDatabase

        self._driver = GraphDatabase.driver(uri, auth=auth)
    else:
        raise ValueError("Provide either a neo4j Driver or uri (+ auth).")
    self._database = database
    self._max_nodes = max_nodes
    self._read_only = read_only
    schema = self._extract_schema()
    super().__init__(width=width, height=height, schema=schema, **kwargs)
    if initial_query:
        self._execute_query(initial_query)

clear #

clear() -> None

Clear the graph display and selection.

Source code in wigglystuff/neo4j_widget.py
def clear(self) -> None:
    """Clear the graph display and selection."""
    self.nodes = []
    self.relationships = []
    self.selected_nodes = []
    self.selected_relationships = []
    self.error = ""

get_selected_node_data #

get_selected_node_data() -> List[dict]

Return full node dicts for currently selected nodes.

Source code in wigglystuff/neo4j_widget.py
def get_selected_node_data(self) -> List[dict]:
    """Return full node dicts for currently selected nodes."""
    selected = set(self.selected_nodes)
    return [n for n in self.nodes if n["element_id"] in selected]

get_selected_relationship_data #

get_selected_relationship_data() -> List[dict]

Return full relationship dicts for currently selected relationships.

Source code in wigglystuff/neo4j_widget.py
def get_selected_relationship_data(self) -> List[dict]:
    """Return full relationship dicts for currently selected relationships."""
    selected = set(self.selected_relationships)
    return [r for r in self.relationships if r["element_id"] in selected]

run_query #

run_query(query: str) -> None

Execute a Cypher query and merge results into the graph.

Source code in wigglystuff/neo4j_widget.py
def run_query(self, query: str) -> None:
    """Execute a Cypher query and merge results into the graph."""
    self._execute_query(query)

Synced traitlets#

Traitlet Type Notes
width int Widget width in pixels (default: 800).
height int Widget height in pixels (default: 500).
schema dict Auto-extracted node labels, relationship types, and property keys.
nodes list List of node dicts currently displayed.
relationships list List of relationship dicts currently displayed.
error str Last error message (empty when no error).
query_running bool Whether a query is currently executing.
selected_nodes list Element IDs of currently selected nodes.
selected_relationships list Element IDs of currently selected relationships.