Last active
December 30, 2015 09:19
-
-
Save etandel/7808160 to your computer and use it in GitHub Desktop.
Neo4J shennanigans
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import partial | |
from bulbs.neo4jserver import Graph | |
from bulbs.model import Node, Relationship | |
from bulbs.property import String, Integer | |
from sitemap import sitemap | |
class Page(Node): | |
element_type = 'page' | |
name = String(nullable=False) | |
visibility = Integer() | |
class Links(Relationship): | |
label = 'links' | |
def create_proxies(g): | |
g.add_proxy('pages', Page) | |
g.add_proxy('links', Links) | |
def iter_tree(tree, lvl=0, cb=None): | |
print '\t' * lvl, tree[0] | |
if cb: | |
cb(*tree) | |
for t in tree[1]: | |
iter_tree(t, lvl+1, cb) | |
def get_or_create_by_name(g, name): | |
return g.pages.get_or_create('name', name, {'name': name}) | |
def create_link(g, name, children): | |
root = get_or_create_by_name(g, name) | |
for c in children: | |
n = get_or_create_by_name(g, c[0]) | |
g.links.create(root, n) | |
UPDATE_VISIBILITY_QUERY = """ | |
START home=node:page(name={home_name}), | |
page=node(*) | |
MATCH path = shortestPath(home-[*]->page) | |
SET page.visibility = length(path); | |
""" | |
def update_visibility(g, home_name): | |
g.client.cypher(UPDATE_VISIBILITY_QUERY, {'home_name': home_name}) | |
def print_visibilities(g): | |
for page in g.pages.get_all(): | |
print page.name, page.visibility | |
def main(): | |
print sitemap, '\n' | |
print '-' * 10, '\n' | |
g = Graph() | |
create_proxies(g) | |
# create home so get_or_create on create_link() is not necessary and only 1 | |
# query is needed for update_visibility. | |
home_name = sitemap[0] | |
g.pages.create(name=home_name, visibility=0) | |
build_graph = partial(create_link, g) | |
iter_tree(sitemap, cb=build_graph) | |
update_visibility(g, home_name) | |
print '-' * 10, '\n' | |
print_visibilities(g) | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sitemap = \ | |
['home', [ | |
['categorias', [ | |
['eletronicos', [ | |
['tv', []], | |
['pc', []], | |
] ], | |
['casa', [ | |
['cadeira', [] ], | |
['mesa', [] ], | |
['cama', [] ], | |
] ], | |
] ], | |
['descontos', [ | |
['tv', []], # visibility = 2 | |
] ], | |
] ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment