def check_join_Existing_line_existing_point_not_on_line(): print(" inside check_join_Existing_line_existing_point_not_on_line function") print("Pick existing set of point and line not connected to it") query = "START b=node(*),a=node(*) MATCH b-[r?:CONTAIN]->a WHERE b.type = {A} AND a.type = {B} AND r IS NULL RETURN a,b" cypher.execute(graph_db, query, {"A" :"line","B":"point"}, row_handler=print_row_new) if len(count) == 0: return false #Join this point with the end-points of the chosen line randomSet = random.sample(dictLine_Point,1) print(" randomset of line and point chosen is ") print( "selectedPoint is " +randomSet[0][0]) print( "selectedLine is " +randomSet[0][1]) node1 = randomSet[0][0] node2 = randomSet[0][1] #Fill in the details of the calling function TODO lineMane = "hjk" length = 10 ang1 = 10 ang2 = 30 ang3 = 40 ang4 = 50 node_triangle = "fdg" addLineInTriangle(lineName, length, ang1, ang2,ang3,ang4,node_triangle) count = 0 return true
def creating_rels(): print rels print allRels for rel in rels: query ='START a=node(*), b=node(*) WHERE has(a.IDX) and a.IDX? = "'+rel[0]+'" and has(a.DB) and a.DB? = "'+traversalName+'" and has(b.IDX) and b.IDX? ="'+rel[1]+'" and has(b.DB) and b.DB? ="'+traversalName+'" CREATE a-[r:_'+str(allRels.count(rel))+']->b RETURN r' print query cypher.execute(graph_db, query, {}, row_handler=print_row,error_handler=print_error)
def test_query_with_params(self): a, b, ab = alice_and_bob(self.graph_db) def check_metadata(metadata): self.assertEqual(5, len(metadata.columns)) self.assertEqual("a", metadata.columns[0]) self.assertEqual("b", metadata.columns[1]) self.assertEqual("ab", metadata.columns[2]) self.assertEqual("a.name", metadata.columns[3]) self.assertEqual("b.name", metadata.columns[4]) def check_row(row): self.assertTrue(isinstance(row, list)) self.assertEqual(5, len(row)) self.assertTrue(isinstance(row[0], neo4j.Node)) self.assertTrue(isinstance(row[1], neo4j.Node)) self.assertTrue(isinstance(row[2], neo4j.Relationship)) self.assertEqual(row[0], a) self.assertEqual(row[1], b) self.assertEqual(row[2], ab) self.assertEqual(row[3], "Alice") self.assertEqual(row[4], "Bob") query = ( "START a=node({A}),b=node({B}) " "MATCH a-[ab]-b " "RETURN a,b,ab,a.name,b.name" ) cypher.execute(self.graph_db, query, {"A": a._id, "B": b._id}, row_handler=check_row, metadata_handler=check_metadata )
def check_join_Existing_line_existing_point_not_on_line(): print( " inside check_join_Existing_line_existing_point_not_on_line function") print("Pick existing set of point and line not connected to it") query = "START b=node(*),a=node(*) MATCH b-[r?:CONTAIN]->a WHERE b.type = {A} AND a.type = {B} AND r IS NULL RETURN a,b" cypher.execute(graph_db, query, { "A": "line", "B": "point" }, row_handler=print_row_new) if len(count) == 0: return false #Join this point with the end-points of the chosen line randomSet = random.sample(dictLine_Point, 1) print(" randomset of line and point chosen is ") print("selectedPoint is " + randomSet[0][0]) print("selectedLine is " + randomSet[0][1]) node1 = randomSet[0][0] node2 = randomSet[0][1] #Fill in the details of the calling function TODO lineMane = "hjk" length = 10 ang1 = 10 ang2 = 30 ang3 = 40 ang4 = 50 node_triangle = "fdg" addLineInTriangle(lineName, length, ang1, ang2, ang3, ang4, node_triangle) count = 0 return true
def alice_bob_test(self): # Build a Cypher query query = "START a=node({A}) MATCH a-[:KNOWS]->b RETURN a,b" # ...and execute the query cypher.execute(self.graph_db, query, {"A": self.node_a.id}, row_handler=print_row)
def convert_to_json_influence(db): name_dict = {} nodes_list = [] edge_list = [] nodes, metadata = cypher.execute(db, "START n=node(*) MATCH (n:ComedianInfobox) RETURN n") i = 0 for row in nodes: node = row[0] props = node.get_properties() name = props['name'] name_dict[name] = i json_str = '{"name": "'+ name + '"}' nodes_list.append(json_str) i += 1 nodes_list_str = ",".join(nodes_list) influence_results, metadata = cypher.execute(db, "START n=node(*) MATCH (n:ComedianInfobox)-[b:INFLUENCED]->(c:ComedianInfobox) RETURN n,c") for row in influence_results: person1_props = row[0].get_properties() person1_name = person1_props['name'] person1 = name_dict[person1_name] person2_props = row[1].get_properties() person2_name = person2_props['name'] person2 = name_dict[person2_name] json_str = '{"source":' + str(person1) + ', "target": '+ str(person2) + '}' edge_list.append(json_str) edge_list_str = ",".join(edge_list) fout = open('influences_json.json','w') complete_json_str = '{ "nodes":[' + nodes_list_str + '], "links":[' + edge_list_str + ']}' json.dump(complete_json_str, fout, indent=4) fout.close()
def outputD3JSON(output_file): nodes = [] links = [] node_id_to_index = {} to_output = { "nodes":nodes, "links":links } rows, metadata = cypher.execute(GRAPHDB, "MATCH (n) RETURN n") for index,row in enumerate(rows): node = row[0] node_id = node._id node_to_write = { "id":node_id } nodes.append(node_to_write) node_id_to_index[node_id] = index rows, metadata = cypher.execute(GRAPHDB, "MATCH (a)-[r:RELEVANCY]->(b) RETURN a,r,b") for nodeA, rel, nodeB in rows: weight = rel["weight"] edge_to_write = { "source":node_id_to_index[nodeA._id], "target":node_id_to_index[nodeB._id], "weight":weight } links.append(edge_to_write) to_write = json.dumps(to_output) with open(output_file, "w") as f: f.write(to_write)
def test_query_with_params(self): a, b, ab = alice_and_bob(self.graph_db) def check_metadata(metadata): self.assertEqual(5, len(metadata.columns)) self.assertEqual("a", metadata.columns[0]) self.assertEqual("b", metadata.columns[1]) self.assertEqual("ab", metadata.columns[2]) self.assertEqual("a.name", metadata.columns[3]) self.assertEqual("b.name", metadata.columns[4]) def check_row(row): self.assertTrue(isinstance(row, list)) self.assertEqual(5, len(row)) self.assertTrue(isinstance(row[0], neo4j.Node)) self.assertTrue(isinstance(row[1], neo4j.Node)) self.assertTrue(isinstance(row[2], neo4j.Relationship)) self.assertEqual(row[0], a) self.assertEqual(row[1], b) self.assertEqual(row[2], ab) self.assertEqual(row[3], "Alice") self.assertEqual(row[4], "Bob") query = ("START a=node({A}),b=node({B}) " "MATCH a-[ab]-b " "RETURN a,b,ab,a.name,b.name") cypher.execute(self.graph_db, query, { "A": a._id, "B": b._id }, row_handler=check_row, metadata_handler=check_metadata)
def test_query_with_handlers(self): a, b = self.graph_db.create({"name": "Alice"}, {"name": "Bob"}) ab = a.create_relationship_to(b, "KNOWS") def check_metadata(metadata): print(metadata) self.assertTrue(isinstance(metadata.columns, list)) self.assertEqual(5, len(metadata.columns)) self.assertEqual("a", metadata.columns[0]) self.assertEqual("b", metadata.columns[1]) self.assertEqual("ab", metadata.columns[2]) self.assertEqual("a.name", metadata.columns[3]) self.assertEqual("b.name", metadata.columns[4]) def check_row(row): print(row) self.assertTrue(isinstance(row, list)) self.assertEqual(5, len(row)) self.assertTrue(isinstance(row[0], neo4j.Node)) self.assertTrue(isinstance(row[1], neo4j.Node)) self.assertTrue(isinstance(row[2], neo4j.Relationship)) self.assertEqual(row[0], a) self.assertEqual(row[1], b) self.assertEqual(row[2], ab) self.assertEqual(row[3], "Alice") self.assertEqual(row[4], "Bob") query = """\ start a=node({0}),b=node({1})\ match a-[ab]-b\ return a,b,ab,a.name,b.name""".format(a.id, b.id) cypher.execute(self.graph_db, query, row_handler=check_row, metadata_handler=check_metadata)
def print_edge_list(db): print "0" fout = open('topic_edge_list.txt', 'w') print ".5" topic_results, metadata = cypher.execute(db, "START n=node(*) MATCH (n)-[b:SPOKE_ABOUT]->(c) RETURN n,c") print "1" for row in topic_results: person_props = row[0].get_properties() person = person_props['name'] topic_props = row[1].get_properties() topic = topic_props['subject'] str = person + "#" + topic + "#S" print str fout.write(str+"\r\n") fout.close() fout = open('influence_edge_list.txt', 'w') influence_results, metadata = cypher.execute(db, "START n=node(*) MATCH (n)-[b:INFLUENCED]->(c) RETURN n,c") for row in influence_results: person1_props = row[0].get_properties() person1 = person1_props['name'] person2_props = row[1].get_properties() person2 = person2_props['name'] str = person1 + "#" + person2 + "#I" fout.write(str+"\r\n") fout.close()
def updateBond(b): g = neo4j.GraphDatabaseService() b[1] = b[1] + b[3] s = "MATCH (n)-[k:KNOWS]-(b) WHERE n.name= " "'" + b[ 0] + "'" " AND b.name= " "'" + b[2] + "'" " SET k.bond= " + str(b[1]) cypher.execute(g, s) print b
def docsSearch(request): ipAddr = request.META.get("REMOTE_ADDR") filename = "/home/qingyuan/log/" + ipAddr writeObject = request.GET["log"] with open(filename, "a") as f: f.write(str(writeObject) + "\n") if "n" in request.GET: nodeID = int(request.GET["ID"]) query = "start n=node({clicked}) return n.docs" data, metadata = cypher.execute(graph_db, query, params={"clicked": nodeID}) docsList = json.dumps(data[0][0]) elif "r" in request.GET: startID = int(request.GET["startID"]) endID = int(request.GET["endID"]) query = "start n=node({startnode}), m=node({endnode}) match n-[r]-m where has(r.docs) return r.docs" data, metadata = cypher.execute(graph_db, query, params={"startnode": startID, "endnode": endID}) docsList = [] if data: docsList = json.dumps(data[0][0]) elif "sn" in request.GET: rawID = request.GET["ID"] nodeID = [int(x) for x in rawID.split(",")] query = "start n=node({clicked}) return n.docs" data, metadata = cypher.execute(graph_db, query, params={"clicked": nodeID}) docsList = [] for d in data: curDoc = ast.literal_eval(d[0])[0] docsList.append(curDoc) docsList = json.dumps(docsList) return HttpResponse(docsList, content_type="application/json")
def print_edge_list(db): print "0" fout = open('topic_edge_list.txt', 'w') print ".5" topic_results, metadata = cypher.execute( db, "START n=node(*) MATCH (n)-[b:SPOKE_ABOUT]->(c) RETURN n,c") print "1" for row in topic_results: person_props = row[0].get_properties() person = person_props['name'] topic_props = row[1].get_properties() topic = topic_props['subject'] str = person + "#" + topic + "#S" print str fout.write(str + "\r\n") fout.close() fout = open('influence_edge_list.txt', 'w') influence_results, metadata = cypher.execute( db, "START n=node(*) MATCH (n)-[b:INFLUENCED]->(c) RETURN n,c") for row in influence_results: person1_props = row[0].get_properties() person1 = person1_props['name'] person2_props = row[1].get_properties() person2 = person2_props['name'] str = person1 + "#" + person2 + "#I" fout.write(str + "\r\n") fout.close()
def test_query_with_params(self): a, b = self.graph_db.create_nodes( {"name": "Alice"}, {"name": "Bob"} ) ab = a.create_relationship_to(b, "KNOWS") def check_metadata(metadata): self.assertTrue(isinstance(metadata.columns, list)) self.assertEqual(5, len(metadata.columns)) self.assertEqual("a", metadata.columns[0]) self.assertEqual("b", metadata.columns[1]) self.assertEqual("ab", metadata.columns[2]) self.assertEqual("a.name", metadata.columns[3]) self.assertEqual("b.name", metadata.columns[4]) def check_row(row): self.assertTrue(isinstance(row, list)) self.assertEqual(5, len(row)) self.assertTrue(isinstance(row[0], neo4j.Node)) self.assertTrue(isinstance(row[1], neo4j.Node)) self.assertTrue(isinstance(row[2], neo4j.Relationship)) self.assertEqual(row[0], a) self.assertEqual(row[1], b) self.assertEqual(row[2], ab) self.assertEqual(row[3], "Alice") self.assertEqual(row[4], "Bob") query = """\ start a=node({A}),b=node({B})\ match a-[ab]-b\ return a,b,ab,a.name,b.name""" cypher.execute(self.graph_db, query, {"A": a.id, "B": b.id}, row_handler=check_row, metadata_handler=check_metadata )
def get_all_meanings(self, word): ''' Get all meanings as assigned by the disambiguation index (should be very fast! approx O(1) hopefully) If that fails, get all meanings given by the following regex: <word>* If even that fails, get all meanings fuzzily equal to <word> using Levenshtein distance or soundex If even THAT fails, return an error saying no meanings and ask the user what the hell he meant to say word => string keyword to get all possible neo4j objects for ''' print "WORD:", word data, metadata = cypher.execute(self.graphdb, 'start n=node:%s(name="%s") match n-[]-m return m' % (self.DISAMBIGUATION, word)) if data: print data return [d[0] for d in data] res = self.disambiguation_index.query("name:%s~" % word) if res: print res return [d[0] for d in data] res = self.disambiguation_index.query("name:%s*" % word) if res: print res return [d[0] for d in data] data, metadata = cypher.execute(self.graphdb, 'START root=node(*) WHERE root.name=~".*%s.*" RETURN root' % word) if data: print data return [d[0] for d in data] return []
def test_query_with_params(self): a, b, ab = alice_and_bob(self.graph) def check_metadata(metadata): assert len(metadata.columns) == 5 assert metadata.columns[0] == "a" assert metadata.columns[1] == "b" assert metadata.columns[2] == "ab" assert metadata.columns[3] == "a.name" assert metadata.columns[4] == "b.name" def check_row(row): assert isinstance(row, list) assert len(row) == 5 assert isinstance(row[0], neo4j.Node) assert isinstance(row[1], neo4j.Node) assert isinstance(row[2], neo4j.Relationship) assert row[0] == a assert row[1] == b assert row[2] == ab assert row[3] == "Alice" assert row[4] == "Bob" query = ("START a=node({A}),b=node({B}) " "MATCH a-[ab]-b " "RETURN a,b,ab,a.name,b.name") cypher.execute(self.graph, query, { "A": a._id, "B": b._id }, row_handler=check_row, metadata_handler=check_metadata)
def main(ts, START=None, END=None, mode=1): """ Does the graph processing at time_stamp ts and returns stats. mode = 1 for complete graph traversal else for graph traversal within time_window. """ global time_stamp time_stamp = ts global graph_component # It's necessary to flush the graph_component to remove the last map graph_component = {} global START_TIME START_TIME = START global END_TIME END_TIME = END # print time_stamp, START_TIME, END_TIME, graph_component, mode # handle_row_custom([2]) # return graph_db = neo4j.GraphDatabaseService("http://localhost:7475/db/data/") if (mode == 1): cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler=handle_row) else: cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler=handle_row_custom) return get_comp_sizes(graph_component.values())
def test_reload_external_changes(manager, connection, static_types): Thing = static_types['Thing'] manager.save(Thing) manager.reload_types() # cache type registry # update the graph as an external manager would # (change a value and bump the typesystem version) match_clauses = ( get_match_clause(Thing, 'Thing', manager.type_registry), get_match_clause(manager.type_system, 'ts', manager.type_registry), ) query = join_lines( 'MATCH', (match_clauses, ','), 'SET ts.version = {version}', 'SET Thing.cls_attr = {cls_attr}', 'RETURN Thing' ) query_params = { 'cls_attr': 'placeholder', 'version': str(uuid.uuid4()) } cypher.execute(connection, query, query_params) # reloading types should see the difference manager.reload_types() descriptor = manager.type_registry.get_descriptor(Thing) assert "cls_attr" in descriptor.class_attributes
def main(ts, START = None, END = None, mode = 1): """ Does the graph processing at time_stamp ts and returns stats. mode = 1 for complete graph traversal else for graph traversal within time_window. """ global time_stamp time_stamp = ts global graph_component # It's necessary to flush the graph_component to remove the last map graph_component ={} global START_TIME START_TIME = START global END_TIME END_TIME = END # print time_stamp, START_TIME, END_TIME, graph_component, mode # handle_row_custom([2]) # return graph_db = neo4j.GraphDatabaseService("http://localhost:7475/db/data/") if (mode == 1): cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler = handle_row ) else : cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler = handle_row_custom ) return get_comp_sizes(graph_component.values())
def getUsers(): g = neo4j.GraphDatabaseService() s = "MATCH (n)-[k:KNOWS]-(b) SET k.bond=0" cypher.execute(g, s) s = "MATCH (s) RETURN s.tag" a = cypher.execute(g, s)[0] a = [str(i[0]) for i in a] return a
def test_nonsense_query_with_error_handler(self): def print_error(message, exception, stacktrace): print(message) assert len(message) > 0 cypher.execute(self.graph, ("SELECT z=nude(0) " "RETURNS x"), error_handler=print_error)
def tCommonNeighbors(graph_db): ret, meta = cypher.execute(graph_db, "start a=node(*) return max(a.neighbors!)") threshold = ret[0][0] or 0 while (threshold>0): threshold /= 2 ret, meta = cypher.execute(graph_db, bCommonNeighbors % threshold, {}, error_handler=print) if ret[-1][2] > threshold: return
def getUsers(): g=neo4j.GraphDatabaseService() s="MATCH (n)-[k:KNOWS]-(b) SET k.bond=0" cypher.execute(g,s) s="MATCH (s) RETURN s.tag" a=cypher.execute(g,s)[0] a=[str(i[0]) for i in a] return a
def creating_nodesA(row): query='' a=row[0] if not a in newNodes: newNodes.append(a) query += "CREATE n = {IDX:'"+a+"',DB:'"+traversalName+"'} " if query != '': print query cypher.execute(graph_db, query, {}, row_handler=print_row,error_handler=print_error)
def test_nonsense_query_with_error_handler(self): def print_error(message, exception, stacktrace): print(message) self.assertTrue(len(message) > 0) cypher.execute(self.graph_db, "select z=nude(0) returns x", error_handler=print_error) self.assertTrue(True)
def drawPerpendicular(change=0): print("Inside drawPerpendicular function") diff_level[0] = diff_level[0] + addPerpendicularPoints #Pick any one triangle query = "START z=node(*) WHERE z.type={A} RETURN z" data, metadata = cypher.execute(graph_db, query, {"A": "triangle"}) for row in data: print(row[0]["name"]) node_triangle = row[0] #Pick existing set of point and line not connected to it query = "START c = node(*) , b= node(*), a= node(*)MATCH c-[:KD1]->d-[:HAS]->b-[r?:CONTAIN]->a WHERE b.type = {A} AND a.type = {B} AND r IS NULL RETURN a,b" cypher.execute(graph_db, query, { "A": "line", "B": "point" }, row_handler=print_row_new) #Pick any one set randomly randomSet = random.sample(dictLine_Point, 1) if change == 1: while save_perp == randomset: randomSet = random.sample(dictLine_Point, 1) # TODO Remove old perpendicular line removeLine_Fig(old_perp_line) save_perp = randomSet print(" randomset of line and point chosen is ") print("selectedPoint is " + randomSet[0][0]) print("selectedLine is " + randomSet[0][1]) selectedLine = randomSet[0][1] selectedPoint = randomSet[0][0] #Find new point by computation TODO #Add point on line newPoint = getNewPointName() print(newPoint) write_Name_In_File(newPoint) addPointOnLine(newPoint, 10, 20, selectedLine, 40, 40, node_triangle) #Add line in triangle newLine = selectedPoint + newPoint old_perp_line = newLine addLineInTriangle(newLine, 40, 90, 90, 20, 25, node_triangle) #Currently hard coding for perpendicular line, PS perp QR, PS perp QS, PS perp SR perpBase1 = newPoint + selectedLine[0] perpBase2 = newPoint + selectedLine[1] perpBase3 = selectedLine addPerpendicularAngle(newLine, perpBase1) addPerpendicularAngle(newLine, perpBase2) addPerpendicularAngle(newLine, perpBase3) print("Exiting drawPerpendicular function")
def test_nonsense_query_with_error_handler(self): def print_error(message, exception, stacktrace): print message self.assertTrue(len(message) > 0) cypher.execute( self.graph_db, "select z=nude(0) returns x", error_handler=print_error ) self.assertTrue(True)
def test_nonsense_query_with_error_handler(self): def print_error(message, exception, stacktrace): print(message) self.assertTrue(len(message) > 0) cypher.execute(self.graph_db, ( "SELECT z=nude(0) " "RETURNS x" ), error_handler=print_error) self.assertTrue(True)
def update_info(user, path): tag = genId() id1 = genId() id2 = genId() id3 = genId() g = neo4j.GraphDatabaseService() s = "CREATE (p:Photo {path:" "'" + path + "'" ",tag:" "'" + tag + "'" ",id1:" "'" + id1 + "'" ",id2:" "'" + id2 + "'" ",id3:" "'" + id3 + "'" "})" cypher.execute(g, s) t = "MATCH (n),(p) WHERE n.name= " "'" + user + "'" " AND p.path= " "'" + path + "'" " CREATE (n)-[:UPLOADS]->(p)" cypher.execute(g, t)
def createRels(user,person): a="MATCH (n)-[r:KNOWS]-(b)WHERE n.name=""'"+user+"'"" AND b.name=""'" +person+"'""RETURN r" a=cypher.execute(g,a) a=a[0] if len(a)==0: b="MATCH (n),(b) WHERE n.name=""'"+user+"'"" AND b.name=""'"+person+"'"" CREATE (n)-[r:KNOWS {bond:0}]->(b)" cypher.execute(g,b) print "Creation Successfully Done" else: print "Already They know each other"
def update_info(user,path): tag=genId() id1=genId() id2=genId() id3=genId() g=neo4j.GraphDatabaseService() s="CREATE (p:Photo {path:""'"+path+"'"",tag:""'"+tag+"'"",id1:""'"+id1+"'"",id2:""'"+id2+"'"",id3:""'"+id3+"'""})" cypher.execute(g,s) t="MATCH (n),(p) WHERE n.name= ""'"+user+"'"" AND p.path= ""'"+path+"'"" CREATE (n)-[:UPLOADS]->(p)" cypher.execute(g,t)
def check_join_Existing_three_non_collinear_non_connected_Points(): print("Pick existing set of three non collinear points which are not connected") global count_row global dict_three_point count_row = 0 dict_three_point = [] query = "START b=node(*),a=node(*),c=node(*) MATCH a-[r?:CONNECTED]-b, b-[s?:CONNECTED]-c,c-[t?:CONNECTED]-a WHERE NOT(a = b) AND NOT(b = c) AND NOT(a = c) AND b.type = {B} AND a.type = {B} AND c.type = {B} AND t IS NULL AND s IS NULL AND r IS NULL RETURN a,b,c" cypher.execute(graph_db, query, {"B":"point"}, row_handler=print_three_points_row) #global count_row if count_row == 0: print(" Not found 3 points, hence exiting from this function") return False #Join these points and add info to the triangle TODO (Please fill the values of angle and length in the below code) randomSet = check_saveObjFigure("Triangle_three_existing_points") print( "first selectedPoint is " +randomSet[0][0]) print( "second selectedPoint is " +randomSet[0][1]) print( "third selectedPoint is " +randomSet[0][2]) query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][0]}) node1 = data[0][0] query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][1]}) node2 = data[0][0] query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][2]}) node3 = data[0][0] node1.create_relationship(node2, "CONNECTED") node2.create_relationship(node3, "CONNECTED") node3.create_relationship(node1, "CONNECTED") sideName1 = node1["name"] + node2["name"] sideName2 = node2["name"] + node3["name"] sideName3 = node1["name"] + node3["name"] node_a, node_b, node_c = graph_db.create( {"name": sideName1, "value":quesArray[0],"type":"line"}, {"name": sideName2, "value":quesArray[1],"type":"line"}, {"name": sideName3, "value":quesArray[2],"type":"line"}) node_a.create_relationship_to(node_b, "ANGLE") node_b.create_relationship_to(node_c, "ANGLE") node_c.create_relationship_to(node_a, "ANGLE") triangleName = node1["name"] + node2["name"] + node3["name"] addTriangle(triangleName) count_row = 0 print("exiting from check_join_Existing_three_non_collinear_non_connected_Points function") return True
def drawPerpendicular(firstTime, change = 0): print("Inside drawPerpendicular function") #Pick any one triangle query = "START z=node(*) WHERE z.type={A} RETURN z" data, metadata = cypher.execute(graph_db, query, {"A": "triangle"}) for row in data: print(row[0]["name"]) node_triangle = row[0] #Pick existing set of point and line not connected to it query = "START c = node(*) , b= node(*), a= node(*)MATCH c-[:KD1]->d-[:HAS]->b-[r?:CONTAIN]->a WHERE b.type = {A} AND a.type = {B} AND r IS NULL RETURN a,b" cypher.execute(graph_db, query, {"A" :"line","B":"point"}, row_handler=print_row_new) #Pick any one set randomly randomSet = random.sample(dictLine_Point,1) if change == 1 : for save_perp in randomset: randomSet = random.sample(dictLine_Point,1) # TODO Remove old perpendicular line ******************** removeLine_Fig(old_perp_line) save_perp.append(randomset) print(" randomset of line and point chosen is ") print( "selectedPoint is " +randomSet[0][0]) print( "selectedLine is " +randomSet[0][1]) selectedLine = randomSet[0][1] selectedPoint = randomSet[0][0] #Find new point by computation TODO ************* #Add point on line newPoint = getNewPointName() print(newPoint) write_Name_In_File(newPoint) addPointOnLine(newPoint,10,20,selectedLine,40,40,node_triangle) #Add line in triangle newLine = selectedPoint + newPoint old_perp_line = newLine addLineInTriangle(newLine, 40, 90, 90,20,25,node_triangle) perpBase1 = newPoint + selectedLine[0] perpBase2 = newPoint + selectedLine[1] perpBase3 = selectedLine addPerpendicularAngle(newLine,perpBase1) addPerpendicularAngle(newLine,perpBase2) addPerpendicularAngle(newLine,perpBase3) print("Exiting drawPerpendicular function")
def check_join_Existing_three_non_collinear_non_connected_Points(): print("Pick existing set of three non collinear points which are not connected") global count_row global dict_three_point count_row = 0 dict_three_point = [] query = "START b=node(*),a=node(*),c=node(*) MATCH a-[r?:CONNECTED]-b, b-[s?:CONNECTED]-c,c-[t?:CONNECTED]-a WHERE NOT(a = b) AND NOT(b = c) AND NOT(a = c) AND b.type = {B} AND a.type = {B} AND c.type = {B} AND t IS NULL AND s IS NULL AND r IS NULL RETURN a,b,c" cypher.execute(graph_db, query, {"B":"point"}, row_handler=print_three_points_row) global count_row if count_row == 0: print(" Not found 3 points, hence exiting from this function") return False #Join these points and add info to the triangle TODO (Please fill the values of angle and length in the below code) randomSet = check_saveObjFigure("Triangle_three_existing_points") print( "first selectedPoint is " +randomSet[0][0]) print( "second selectedPoint is " +randomSet[0][1]) print( "third selectedPoint is " +randomSet[0][2]) query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][0]}) node1 = data[0][0] query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][1]}) node2 = data[0][0] query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][2]}) node3 = data[0][0] node1.create_relationship(node2, "CONNECTED") node2.create_relationship(node3, "CONNECTED") node3.create_relationship(node1, "CONNECTED") sideName1 = node1["name"] + node2["name"] sideName2 = node2["name"] + node3["name"] sideName3 = node1["name"] + node3["name"] node_a, node_b, node_c = graph_db.create( {"name": sideName1, "value":quesArray[0],"type":"line"}, {"name": sideName2, "value":quesArray[1],"type":"line"}, {"name": sideName3, "value":quesArray[2],"type":"line"}) node_a.create_relationship_to(node_b, "ANGLE") node_b.create_relationship_to(node_c, "ANGLE") node_c.create_relationship_to(node_a, "ANGLE") triangleName = node1["name"] + node2["name"] + node3["name"] addTriangle(triangleName) count_row = 0 print("exiting from check_join_Existing_three_non_collinear_non_connected_Points function") return True
def numberOfEdges(a): g=neo4j.GraphDatabaseService() for i in a: s="MATCH (a)<-[w:WRITES|UPLOADS]-(n)-[k:KNOWS]-(b) WHERE a.tag= ""'"+i+"'"" RETURN n.name,k.bond,b.name" b=cypher.execute(g,s)[0] for j in b: l=len(b) h=j[1]/float(l) t="MATCH (a)-[k:KNOWS]-(b) WHERE a.name= ""'"+j[0]+"'"" AND b.name= ""'"+j[2]+"'"" SET k.heavy=""'"+str(h)+"'" cypher.execute(g,t) print j
def handle_row(row): nodeA = row[0] print unicode(nodeA).encode('utf-8', 'ignore') def handle_row_inner(inner_row): nodeB = inner_row[0] weight = random.random() print "w: " + str(weight) if nodeA != nodeB: GRAPHDB.create((nodeA, "RELEVANCY", nodeB, {"weight": weight}),) # for each node in inner loop cypher.execute(GRAPHDB, "START z=node(*) RETURN z", row_handler=handle_row_inner)
def view(user): #members other than the user itself are visible t = "MATCH (b)-[:KNOWS]-(n) WHERE n.name= " "'" + user + "'" " RETURN b.name" s = "MATCH n RETURN n.name " a = [str(i[0]) for i in cypher.execute(g, t)[0]] b = [str(i[0]) for i in cypher.execute(g, s)[0]] c = (set(b) - set(a)) for i in c: if i == user: continue else: print i
def check_existing_line_point_not_on_line(): print("Pick existing set of point and line not connected to it") query = "START b=node(*),a=node(*) MATCH b-[r?:CONTAIN]->a WHERE b.type = {A} AND a.type = {B} AND r IS NULL RETURN a,b" cypher.execute(graph_db, query, {"A" :"line","B":"point"}, row_handler=print_row_new) if len(count) == 0: return false #Join this point with the mid-point of the chosen line count = 0 return true
def main(ts): global time_stamp time_stamp = ts global graph_component graph_component ={} # print time_stamp # print " Start the BFS..." graph_db = neo4j.GraphDatabaseService("http://localhost:7475/db/data/") # print " connected to DB." cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler=handle_row) return get_comp_sizes(graph_component.values())
def tCommonNeighbors(graph_db): ret, meta = cypher.execute(graph_db, "start a=node(*) return max(a.neighbors!)") threshold = ret[0][0] or 0 while (threshold > 0): threshold /= 2 ret, meta = cypher.execute(graph_db, bCommonNeighbors % threshold, {}, error_handler=print) if ret[-1][2] > threshold: return
def getState(self): # moiraiCypher.getState() query1 = "START n=node(*) RETURN n;" query2 = "START n=node(*) MATCH n-[r]->m RETURN r, ID(n), ID(m);" params = {} print "exporting state" # get all nodes # pass each row to cypher2pubsub to change into DCES events cypher.execute(graph_db, query1, params, row_handler=self.cypher2pub) # get all edges (retrieve by nodes?) cypher.execute(graph_db, query2, params, row_handler=self.cypher2pub) return True
def tag(id): id = int(id) tag_data,metadata=cypher.execute(app.graph_db, "match (m:USER{{id:{0}}}),(n:ARTIST{{id:{1}}}) " "create unique m-[r:TAGS]->n set r.tags = " "case when not (has (r.tags)) then [] when not '{2}' in r.tags " "then r.tags + '{2}' else r.tags end;".format(session['user'], id,request.form['tags'])) tag_data,metadata = cypher.execute(app.graph_db, "MATCH (n:USER {{id: {0} }}), (m: ARTIST {{id: {1}}}) " "CREATE unique (n)-[:`{2}`]->m RETURN n".format(session['user'],id,request.form['tags'])) #TODO Add another query to create a new relationship with the tag return redirect(url_for('neo4j.artists.view',id=id))
def numberOfEdges(a): g = neo4j.GraphDatabaseService() for i in a: s = "MATCH (a)<-[w:WRITES|UPLOADS]-(n)-[k:KNOWS]-(b) WHERE a.tag= " "'" + i + "'" " RETURN n.name,k.bond,b.name" b = cypher.execute(g, s)[0] for j in b: l = len(b) h = j[1] / float(l) t = "MATCH (a)-[k:KNOWS]-(b) WHERE a.name= " "'" + j[ 0] + "'" " AND b.name= " "'" + j[ 2] + "'" " SET k.heavy=" "'" + str(h) + "'" cypher.execute(g, t) print j
def tRootedPageRank(graph_db, params): d = 0.85 # PageRank Damping factor pret, ret, cret = [], [], None N = getNodeCount(graph_db) xnid = cypher.execute(graph_db, pGetNID, params)[0][0][0] cypher.execute(graph_db, xRootedPageRankInit % (1.0/N)) while (pret != cret): pret = cret cypher.execute(graph_db, xRootedPageRankSetSource % (d,d), params) cypher.execute(graph_db, xRootedPageRankSetOther %(xnid,d)) cypher.execute(graph_db, xRootedPageRankSwitch) ret, meta = cypher.execute(graph_db, xRootedPageRankQueryTop % (xnid,10)) cret = [nid for nid,score in ret]
def nInteract(): """ Grab 100 random relations in the form: 'speaker opinion', 'listener', 'listener opinion' and pass them to the nShareOpinion method. I use the py2neo cypher methods to pass the following query to the database. MATCH (a:Agents)-[SpeaksTo]->(b:Agents) WITH a, b, rand() AS c ORDER BY c RETURN a.hasOpinion,b,b.hasOpinion LIMIT 100; :return: list in the order of the RETURN statement """ query = "MATCH (a:Agents)-[SpeaksTo]->(b:Agents) WITH a, b, rand() AS c ORDER BY c RETURN a.hasOpinion,b,b.hasOpinion LIMIT 100;" cypher.execute(nGraph, query, row_handler=nShareOpinion)
def tag(id): id = int(id) database = app.db_client.music database.users.update({'_id' : session['user'], 'artists.artist' : id}, {"$addToSet" : {'artists.$.tag' : request.form['tags']}}) tag_data,metadata=cypher.execute(app.graph_db, "match (m:USER{{id:{0}}}),(n:ARTIST{{id:{1}}}) " "create unique m-[r:TAGS]->n set r.tags = " "case when not (has (r.tags)) then [] when not '{2}' in r.tags " "then r.tags + '{2}' else r.tags end;".format(session['user'], id,request.form['tags'])) tag_data,metadata = cypher.execute(app.graph_db, "MATCH (n:USER {{id: {0} }}), (m: ARTIST {{id: {1}}}) " "CREATE unique (n)-[:`{2}`]->m RETURN n".format(session['user'],id,request.form['tags'])) print request.form['tags'] return redirect(url_for('neomongo.artists.view',id=id))
def generateFigure(geom_object, concept): generateObjFigure(geom_object) generateConceptFigure(concept) //TODO check the functions below generateTriangle(quesArray, cordArray, triangleName,node_root) drawPerpendicular() print("AFTER DRAWING PERPENDICULAR LINE SHOWING ALL RELATIONS") #Checking graph nodes by printing all nodes along with their relationship query = "START a=node(*) MATCH a-[r]->b RETURN a,b,r" cypher.execute(graph_db, query, row_handler=print_row) writeFig_Data_to_File()
def addPointFig(): print("Inside adding point, find an existing line not having existing mid point") global countLine global dictLine_Point countLine = [] dictLine_Point = [] query = "START c=node(*), b=node(*),a=node(*) MATCH c-[:KD1]->d-[:HAS]->b-[r?:MIDPOINT]->a,b-[s?:CONTAIN]-a WHERE b.type = {A} AND a.type = {B} AND r IS NULL AND s IS NULL RETURN a,b" cypher.execute(graph_db, query, {"A" :"line","B":"point"}, row_handler=print_row_new) #If above case fails, then if len(countLine) != 0: #Get the mid-point of the chosen line randomSet = random.sample(dictLine_Point,1) #####TODO This is for generating a new triangle different from previous one ''' if len(save_point) > 0 : for randomSet in save_point: randomSet = random.sample(dict_three_point,1) #End of if save_point.append(randomSet) ''' print(" randomset of line chosen is ") print( "selectedPoint is " +randomSet[0][0]) print( "selectedLine is " +randomSet[0][1]) #Get nodes of the end points of lines, from nodes get the cord values for computing mid-point query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][1][0]}) cord1x = data[0][0]["cordx"] cord1y = data[0][0]["cordy"] query = "START a=node(*) WHERE a.type = {A} AND a.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"point","B":randomSet[0][1][1]}) cord2x = data[0][0]["cordx"] cord2y = data[0][0]["cordy"] cord3x = 0.5 *(cord1x + cord2x) cord3y = 0.5 *(cord1y + cord2y) query = "START a=node(*) MATCH a-[:HAS]->b WHERE a.type = {A} AND b.name = {B} return a" data,metadata = cypher.execute(graph_db, query, {"A" :"triangle","B":randomSet[0][1]}) triangle = data[0][0] #TODO #addPointOnLine(pointName,cordx,cordy,line, line1Length, line2Length,node_triangle): p1 = getNewPointName() addPointOnLine(p1, cord3x, cord3y, randomSet[0][1], 10,20,triangle) countLine = [] else: print("need to think ....this case should not arrive soooooooooon except for first time") return True
def tRootedPageRank(graph_db, params): d = 0.85 # PageRank Damping factor pret, ret, cret = [], [], None N = getNodeCount(graph_db) xnid = cypher.execute(graph_db, pGetNID, params)[0][0][0] cypher.execute(graph_db, xRootedPageRankInit % (1.0 / N)) while (pret != cret): pret = cret cypher.execute(graph_db, xRootedPageRankSetSource % (d, d), params) cypher.execute(graph_db, xRootedPageRankSetOther % (xnid, d)) cypher.execute(graph_db, xRootedPageRankSwitch) ret, meta = cypher.execute(graph_db, xRootedPageRankQueryTop % (xnid, 10)) cret = [nid for nid, score in ret]
def update_status(user): fp = open("status.json", "w+") g = neo4j.GraphDatabaseService() e = "MATCH (n:People)-[:KNOWS]-(b)-[:WRITES]->(s) WHERE n.name= " "'" + user + "'" " RETURN b.name,s.status,s.tag,s.id1,s.id2,s.id3" f = "MATCH (n:People)-[:WRITES]->(s) WHERE n.name= " "'" + user + "'" " RETURN n.name,s.status,s.tag,s.id1,s.id2,s.id3" b = cypher.execute(g, f)[0] a = cypher.execute(g, e)[0] for i in b: a.append(i) del b json.dump(a, fp) fp.close() for i in a: print i
def update_status(user): fp=open("status.json","w+") g=neo4j.GraphDatabaseService() e="MATCH (n:People)-[:KNOWS]-(b)-[:WRITES]->(s) WHERE n.name= ""'"+user+"'"" RETURN b.name,s.status,s.tag,s.id1,s.id2,s.id3" f="MATCH (n:People)-[:WRITES]->(s) WHERE n.name= ""'"+user+"'"" RETURN n.name,s.status,s.tag,s.id1,s.id2,s.id3" b=cypher.execute(g,f)[0] a=cypher.execute(g,e)[0] for i in b: a.append(i) del b json.dump(a,fp) fp.close() for i in a: print i
def check_join_Existing_three_non_collinear_Points(): print("Pick existing set of three points which are not connected") query = "START b=node(*),a=node(*),c=node(*) MATCH b-[r?:CONNECTED]-a, b-[s?:CONNECTED]-c,c-[t?:CONNECTED]-a WHERE NOT(a = b) AND NOT(b = c) AND NOT(a = c) AND b.type = {B} AND a.type = {B} AND c.type = {B} AND t IS NULL AND s IS NULL AND r IS NULL RETURN a,b,c" cypher.execute(graph_db, query, {"B": "point"}, row_handler=print_three_points_row) if count_row == 0: return false #Join these points and add info to the triangle TODO (Please fill the values of angle and length in the below code) randomSet = random.sample(dict_three_Point, 1) print(" randomset of line and point chosen is ") print("first selectedPoint is " + randomSet[0][0]) print("second selectedPoint is " + randomSet[0][1]) node1 = randomSet[0][0] node2 = randomSet[0][1] node3 = randomSet[0][2] node1.create_relationship(node2, "CONNECTED") node2.create_relationship(node3, "CONNECTED") node3.create_relationship(node1, "CONNECTED") sideName1 = node1["name"] + node2["name"] sideName2 = node2["name"] + node3["name"] sideName3 = node1["name"] + node3["name"] node_a, node_b, node_c = graph_db.create( { "name": sideName1, "value": quesArray[0], "type": "line" }, { "name": sideName2, "value": quesArray[1], "type": "line" }, { "name": sideName3, "value": quesArray[2], "type": "line" }) node_a.create_relationship_to(node_b, "ANGLE") node_b.create_relationship_to(node_c, "ANGLE") node_c.create_relationship_to(node_a, "ANGLE") triangleName = node1["name"] + node2["name"] + node3["name"] addTriangle(triangleName) count_row = 0 return true
def generateFigure(geom_object, concept): print("inside generateFigure function ") generateObjFigure(geom_object, 1, 0) print("AFTER DRAWING FIGURE OBJECT SHOWING ALL RELATIONS") #Checking graph nodes by printing all nodes along with their relationship query = "START a=node(*) MATCH a-[r]->b RETURN a,b,r" cypher.execute(graph_db, query, row_handler=print_row) generateConceptFigure(concept) print("AFTER DRAWING FIGURE CONCEPT SHOWING ALL RELATIONS") #Checking graph nodes by printing all nodes along with their relationship query = "START a=node(*) MATCH a-[r]->b RETURN a,b,r" cypher.execute(graph_db, query, row_handler=print_row) writeFig_Data_to_File()
def main(seed): depth = 0 global g # Connect to Neo4j graph_db = neo4j.GraphDatabaseService(NEODB) print "Starting Node Export at {0}.".format( datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')) for s in seed: query = q.format(s) neo_nodes, metadata = cypher.execute(graph_db, query) # add the node g.add_node(neo_nodes[0][0]) attr = graph_db.node(neo_nodes[0][0]).get_properties() attr = addNodeAttributes(attr) g.node[neo_nodes[0][0]] = attr complete.add(neo_nodes[0][0]) # pass them to the recursive DFS dfs_parse_nodes(neo_nodes, depth + 1) print "Saving File" nx.write_gexf(g, GEXF_FILE) print "Done at {0}.".format(datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'))
def liked_posts(user): fp = open('photo.json', 'w') s = "MATCH (b)-[r:RATES]->(s:Photo)<-[p:WRITES|UPLOADS]-(n) WHERE n.name=" "'" + user + "'" " RETURN s.path,sum(r.rate),s.tag" a = cypher.execute(g, s)[0] a.sort(key=itemgetter(1)) json.dump(a, fp) fp.close()
def warp(): """ NoneType -> int Takes nothing. Returns a random node ID matching the query criteria. """ # Magic to get est # of nodes in graph from restful API resp = requests.get( NEODB[:-4] + "manage/server/jmx/domain/org.neo4j/instance%3Dkernel%230%2Cname%3DPrimitive%20count?_=1342719685294" ) rdict = resp.json()[0] for i in range(len(rdict['attributes'])): if rdict['attributes'][i]['name'] == "NumberOfNodeIdsInUse": nodeCount = rdict['attributes'][i]['value'] # try 10 times to get a random node for i in range(10): r = random.randrange(0, nodeCount) query = q.format("*")[:-6] + " SKIP {0} LIMIT 1;\n".format(r) neoNodes, metadata = cypher.execute(G, query) if len(neoNodes) > 0: node = neoNodes[0][0] return node._id # if we can't find a random node, return node 0 return 0
def Neighbor_price_fetch(self, ISBN): query= "START n=node:ni(ISBN={ISBN}) MATCH n-[r]-m WHERE has(m.Type) and has(m.Price) and m.Type='Title' with n, r ORDER BY r.weight DESC LIMIT 15 RETURN avg(m.Price)" data = cypher.execute(graphDB, query) if isinstance(data[0][0], list): return data[0][0][0] else: return data[0][0]
def test_param_used_thrice(self): node, = self.graph.create({}) query = ("START a=node({X}), b=node({X}), c=node({X})" "RETURN a, b, c") params = {"X": node._id} data, metadata = cypher.execute(self.graph, query, params) assert data[0] == [node, node, node]