#StackBounty: #python #neo4j #py2neo How can I randomly walk between nodes by weights in Neo4j with Python?

Bounty: 100

I’ve created nodes in Neo4j with the following code,

from py2neo import Graph, Node, Relationship

g = Graph(password='neo4j')
tx = g.begin()

node1 = Node('Node', name='Node-1')
node2 = Node('Node', name='Node-2')
node3 = Node('Node', name='Node-3')
node4 = Node('Node', name='Node-4')
node5 = Node('Node', name='Node-5')
node6 = Node('Node', name='Node-6')
node7 = Node('Node', name='Node-7')

tx.create(node1)
tx.create(node2)
tx.create(node3)
tx.create(node4)
tx.create(node5)
tx.create(node6)
tx.create(node7)

rel12 = Relationship(node1, '0.2', node2, weight=0.2)
rel13 = Relationship(node1, '0.2', node3, weight=0.2)
rel14 = Relationship(node1, '0.6', node4, weight=0.6)
rel45 = Relationship(node4, '0.5', node5, weight=0.5)
rel46 = Relationship(node4, '0.3', node6, weight=0.3)
rel47 = Relationship(node4, '0.2', node7, weight=0.2)

tx.create(rel12)
tx.create(rel13)
tx.create(rel14)
tx.create(rel45)
tx.create(rel46)
tx.create(rel47)

tx.commit()

Here is the graph in Neo4j interface,
neo4j-graph

I want to select a node by name and then, I want to walk to another node randomly. But random selection should be like that,

import random

random.choices(['Node-2', 'Node-3', 'Node-4'], weights=(0.2, 0.2, 0.6))

I can select the node with following code, but I don’t know how to walk to the other node randomly.

from py2neo import Graph
from py2neo.matching import NodeMatcher

g = Graph(password='neo4j')
nodes = NodeMatcher(g)
node1 = nodes.match('Node', name='Node-1').first()

If node-1 is the starting point, ways that can be walked,

Node-1 -> Node-2
Node-1 -> Node-3
Node-1 -> Node-4 -> Node-5
Node-1 -> Node-4 -> Node-6
Node-1 -> Node-4 -> Node-7

Any idea? Thanks in advance.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.