Skip to content

Instantly share code, notes, and snippets.

@swilly22
Created April 15, 2024 18:13
Show Gist options
  • Save swilly22/fb25e7454a45ae021147aa84c5c9cab8 to your computer and use it in GitHub Desktop.
Save swilly22/fb25e7454a45ae021147aa84c5c9cab8 to your computer and use it in GitHub Desktop.
from falkordb import FalkorDB
# Connect to FalkorDB
db = FalkorDB(host='localhost', port=6379)
# Select the social graph
g = db.select_graph('social')
# Create index
try:
g.create_node_range_index('Person', 'Name')
except:
pass
# Create a bunch of Person nodes
people = ["Nir", "Thomas", "Daria"]
q = "MERGE (p:Person {name:$name})"
for person in people:
g.query(q, {'name': person})
# Form connections:
# Connect "Nir" to "Daria" via a FOLLOWS edge
q = "MATCH (n:Person {name:'Nir'}), (d:Person {name:'Daria'}) MERGE (n)-[:FOLLOWS]->(d)"
g.query(q)
# Connect "Daria" to "Thomas" via a FOLLOWS edge
q = "MATCH (d:Person {name:'Daria'}), (t:Person {name:'Thomas'}) MERGE (d)-[:FOLLOWS]->(t)"
g.query(q)
# Check if there's a path between Nir and Thomas
q = "MATCH p = (n:Person {name:'Nir'})-[*]->(t:Person {name:'Thomas'}) RETURN p"
res = g.query(q)
path = res.result_set[0][0]
print(f"Path: {path}")
# Check out-degree for each person
q = "MATCH (a) OPTIONAL MATCH (a)-[]->(z) RETURN a.name, count(z)"
res = g.query(q).result_set
for row in res:
print(f"{row[0]}'s out-degree is {row[1]}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment