Skip to main content

SQLite extension for graph queries using Cypher

Project description

GraphQLite Python

Python bindings for GraphQLite, a SQLite extension that adds graph database capabilities using Cypher.

Installation

pip install graphqlite

Quick Start

High-Level Graph API (Recommended)

The Graph class provides an ergonomic interface for common graph operations:

from graphqlite import Graph

# Create a graph (in-memory or file-based)
g = Graph(":memory:")

# Add nodes
g.upsert_node("alice", {"name": "Alice", "age": 30}, label="Person")
g.upsert_node("bob", {"name": "Bob", "age": 25}, label="Person")

# Add edges
g.upsert_edge("alice", "bob", {"since": 2020}, rel_type="KNOWS")

# Query
print(g.stats())              # {'nodes': 2, 'edges': 1}
print(g.get_neighbors("alice"))  # [{'id': 'bob', ...}]
print(g.node_degree("alice"))    # 1

# Graph algorithms
ranks = g.pagerank()
communities = g.community_detection()

# Raw Cypher when needed
results = g.query("MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name")

Low-Level Cypher API

For complex queries or when you need full control:

from graphqlite import connect

db = connect("graph.db")

db.cypher("CREATE (a:Person {name: 'Alice', age: 30})")
db.cypher("CREATE (b:Person {name: 'Bob', age: 25})")
db.cypher("""
    MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
    CREATE (a)-[:KNOWS]->(b)
""")

results = db.cypher("MATCH (a:Person)-[:KNOWS]->(b) RETURN a.name, b.name")
for row in results:
    print(f"{row['a.name']} knows {row['b.name']}")

API Reference

Graph Class

from graphqlite import Graph, graph

# Constructor
g = Graph(db_path=":memory:", namespace="default", extension_path=None)

# Or use the factory function
g = graph(":memory:")

Node Operations

Method Description
upsert_node(node_id, props, label="Entity") Create or update a node
get_node(node_id) Get node by ID
has_node(node_id) Check if node exists
delete_node(node_id) Delete node and its edges
get_all_nodes(label=None) Get all nodes, optionally by label

Edge Operations

Method Description
upsert_edge(source, target, props, rel_type="RELATED") Create edge between nodes
get_edge(source, target) Get edge properties
has_edge(source, target) Check if edge exists
delete_edge(source, target) Delete edge
get_all_edges() Get all edges

Graph Queries

Method Description
node_degree(node_id) Count edges connected to node
get_neighbors(node_id) Get adjacent nodes
get_node_edges(node_id) Get all edges for a node
stats() Get node/edge counts
query(cypher) Execute raw Cypher query

Graph Algorithms

Centrality

Method Description
pagerank(damping=0.85, iterations=20) PageRank importance scores
degree_centrality() In/out/total degree for each node
betweenness_centrality() Betweenness centrality scores
closeness_centrality() Closeness centrality scores
eigenvector_centrality(iterations=100) Eigenvector centrality scores

Community Detection

Method Description
community_detection(iterations=10) Label propagation communities
louvain(resolution=1.0) Louvain modularity optimization
leiden_communities(resolution, seed) Leiden algorithm (requires graspologic)

Connected Components

Method Description
weakly_connected_components() Weakly connected components
strongly_connected_components() Strongly connected components

Path Finding

Method Description
shortest_path(source, target, weight) Dijkstra's shortest path
astar(source, target, lat, lon) A* with optional heuristic
all_pairs_shortest_path() All-pairs shortest paths (Floyd-Warshall)

Traversal

Method Description
bfs(start, max_depth=-1) Breadth-first search
dfs(start, max_depth=-1) Depth-first search

Similarity

Method Description
node_similarity(n1, n2, threshold, top_k) Jaccard similarity
knn(node, k=10) K-nearest neighbors
triangle_count() Triangle counts and clustering coefficients

Export

Method Description
to_rustworkx() Export to rustworkx PyDiGraph (requires rustworkx)

Batch Operations

# Batch insert nodes
g.upsert_nodes_batch([
    ("n1", {"name": "Alice"}, "Person"),
    ("n2", {"name": "Bob"}, "Person"),
])

# Batch insert edges
g.upsert_edges_batch([
    ("n1", "n2", {"weight": 1.0}, "KNOWS"),
])

Connection Class

from graphqlite import connect, wrap

# Open new connection
db = connect("graph.db")
db = connect(":memory:")

# Wrap existing sqlite3 connection
import sqlite3
conn = sqlite3.connect("graph.db")
db = wrap(conn)

Methods

Method Description
cypher(query) Execute Cypher query, return results
execute(sql) Execute raw SQL
close() Close connection

CypherResult

Results from cypher() calls:

results = db.cypher("MATCH (n) RETURN n.name")

len(results)           # Number of rows
results[0]             # First row as dict
results.columns        # Column names
results.to_list()      # All rows as list

for row in results:
    print(row["n.name"])

Utility Functions

from graphqlite import escape_string, sanitize_rel_type, CYPHER_RESERVED

# Escape strings for Cypher queries
safe = escape_string("It's a test")  # "It\\'s a test"

# Sanitize relationship types
rel = sanitize_rel_type("has-items")  # "has_items"
rel = sanitize_rel_type("CREATE")     # "REL_CREATE" (reserved word)

# Set of Cypher reserved keywords
if "MATCH" in CYPHER_RESERVED:
    print("MATCH is reserved")

Extension Path

The extension is located automatically. To specify a custom path:

db = connect("graph.db", extension_path="/path/to/graphqlite.dylib")

Or set the GRAPHQLITE_EXTENSION_PATH environment variable.

Troubleshooting

See FAQ.md for common issues and solutions.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

graphqlite-0.2.1.tar.gz (247.1 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

graphqlite-0.2.1-py3-none-win_amd64.whl (1.2 MB view details)

Uploaded Python 3Windows x86-64

graphqlite-0.2.1-py3-none-manylinux_2_28_aarch64.whl (198.2 kB view details)

Uploaded Python 3manylinux: glibc 2.28+ ARM64

graphqlite-0.2.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (199.7 kB view details)

Uploaded Python 3manylinux: glibc 2.17+ x86-64

graphqlite-0.2.1-py3-none-macosx_11_0_arm64.whl (154.0 kB view details)

Uploaded Python 3macOS 11.0+ ARM64

File details

Details for the file graphqlite-0.2.1.tar.gz.

File metadata

  • Download URL: graphqlite-0.2.1.tar.gz
  • Upload date:
  • Size: 247.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for graphqlite-0.2.1.tar.gz
Algorithm Hash digest
SHA256 29d6e46f20c0bbe63d31aeab668eee0c217d011b10ef9c885e193cffe2cc45ce
MD5 7163796e661c28127c58963455877f80
BLAKE2b-256 2b21832d7f45270cdf62964859bdc623f66c39c9b84f3d3aad152a40dafeac76

See more details on using hashes here.

File details

Details for the file graphqlite-0.2.1-py3-none-win_amd64.whl.

File metadata

  • Download URL: graphqlite-0.2.1-py3-none-win_amd64.whl
  • Upload date:
  • Size: 1.2 MB
  • Tags: Python 3, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for graphqlite-0.2.1-py3-none-win_amd64.whl
Algorithm Hash digest
SHA256 e27ddea29ee34707bb932c851c7fcdac59bd833eec2dc381ff697f1ba853760a
MD5 77f5d733e1909ec6e6e0c553c4e35004
BLAKE2b-256 a1d8082ab433bc54758938a533ead84ab4c8c05f063ed8c22921a86a51cde008

See more details on using hashes here.

File details

Details for the file graphqlite-0.2.1-py3-none-manylinux_2_28_aarch64.whl.

File metadata

File hashes

Hashes for graphqlite-0.2.1-py3-none-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 6619b5a389ae86941d0f981938d9ef4930398d969da11dc4592703016756642e
MD5 8611f5b065191b19ef67e712465bc0f7
BLAKE2b-256 eb1a2d2529174b3a0510c251874730c47d990148dfc6c005dcf85f25a1fcb7c8

See more details on using hashes here.

File details

Details for the file graphqlite-0.2.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for graphqlite-0.2.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 a1c1bce2d057e49ba130a68720422b59b69389d104b5081ef674bc90d28daaf3
MD5 02f8155874c4240e5f4e9f26e2411d18
BLAKE2b-256 d36b097c76cbe63c7a4b2e0804f1c10f535ce511b8b2c79c28d5dc0624a76dd9

See more details on using hashes here.

File details

Details for the file graphqlite-0.2.1-py3-none-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for graphqlite-0.2.1-py3-none-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 01390babc473263551e68a5b922a661da286e136af9c425a7cf6be9c6ea2fed0
MD5 065ec3fe50c299addf964d4e3d32012e
BLAKE2b-256 f80d9a8f9e937c271115c01ee575478bda23ace1ab0b4f466d639d0cd52f4bf3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page