def test_schema_index(graph, make_unique_id): node_matcher = NodeMatcher(graph) label_1 = make_unique_id() label_2 = make_unique_id() munich = Node(name="München", key="09162000") graph.create(munich) munich.clear_labels() munich.update_labels({label_1, label_2}) graph.schema.create_index(label_1, "name") graph.schema.create_index(label_1, "key") graph.schema.create_index(label_2, "name") graph.schema.create_index(label_2, "key") found_borough_via_name = node_matcher.match(label_1, name="München") found_borough_via_key = node_matcher.match(label_1, key="09162000") found_county_via_name = node_matcher.match(label_2, name="München") found_county_via_key = node_matcher.match(label_2, key="09162000") assert list(found_borough_via_name) == list(found_borough_via_key) assert list(found_county_via_name) == list(found_county_via_key) assert list(found_borough_via_name) == list(found_county_via_name) keys = graph.schema.get_indexes(label_1) assert (u"name", ) in keys assert (u"key", ) in keys graph.schema.drop_index(label_1, "name") graph.schema.drop_index(label_1, "key") graph.schema.drop_index(label_2, "name") graph.schema.drop_index(label_2, "key") with raises(Neo4jError) as e: graph.schema.drop_index(label_2, "key") assert e.value.code == "Neo.DatabaseError.Schema.IndexDropFailed" graph.delete(munich)
def api_search_movie(movie_title): search = tmdb.Search() response = search.movie(query=movie_title) for s in search.results: if (s["poster_path"] == "None" or s["poster_path"] is None): s["poster_path"] = "https://www.theprintworks.com/wp-content/themes/psBella/assets/img/film-poster-placeholder.png" else: s["poster_path"] = "https://image.tmdb.org/t/p/w220_and_h330_face" + s[ "poster_path"] matcher = NodeMatcher(graph) for p in response["results"]: movie = matcher.match("movie").where("_.id=" + str(p["id"])).first() if (movie is None): movie = Node("movie", original_title=p["title"], id=p["id"], release_date=p["release_date"], poster_path=p["poster_path"], vote_count=p["vote_count"], vote_average=p["vote_average"], load=False) graph.create(movie) for g in p["genre_ids"]: genre = matcher.match("genre").where("_.id=" + str(g)).first() belongs_to = Relationship.type("belongs_to") graph.create(belongs_to(movie, genre)) return response
def findOneNode(self, node_type=None, properties=None, where=None): """查找一个结点 :param node_type:结点类型,即 label,类型是str :param properties: 多个"属性名: 属性值"键值对组成的字典,类型是dict :param where: 查询子句,类型是str :return: 一个Node类型的结点 """ matcher = NodeMatcher(self.my_graph) if not (isinstance(node_type, str)): raise TypeError('查询的结点的类型必须要指定,而且node_type必须是字符串类型') if not (properties is None): if not (isinstance(properties, dict)): raise TypeError('properties是多个属性键值对组成的字典,它必须是dict类型') if not (where is None): if not (isinstance(where, str)): raise TypeError('where表示的是查询条件,它必须是字符串类型') if (where is None) and (properties is None): return matcher.match(node_type).first() elif (not (properties is None)) and (where is None): return matcher.match(node_type, **properties).first() elif (properties is None) and (not (where is None)): return matcher.match(node_type).where(where).first()
def batch_relations(self, rela, relations): tx = self.graph.begin() new_relationships = [] old_relationships = [] for data in relations: entityname1 = data["entityname1"] entityname2 = data["entityname2"] matcher = NodeMatcher(self.graph) node1 = matcher.match(name=entityname1).first() node2 = matcher.match(name=entityname2).first() # print("node-----------", node1, node2) matcher = RelationshipMatcher(self.graph) old_relationship = matcher.match([node1, node2], r_type=rela).first() print("-------old_relationship", old_relationship) if old_relationship is None: relationship = Relationship(node1, rela, node2, score=100) print("-------relationship", relationship) new_relationships.append(relationship) if len(new_relationships) > 0: print("new_relationships--------", new_relationships) sub = Subgraph(relationships=new_relationships) tx.create(sub) tx.commit()
def findAllNode(self, node_type=None, properties=None, where=None): """查找多个结点 :param node_type: node_type:结点类型,即 label,类型是str :param properties: 多个"属性名: 属性值"键值对组成的字典,类型是dict :param where: 查询子句,类型是str :return: 多个Node类型的结点组成的list,类型是list """ matcher = NodeMatcher(self.my_graph) if not (isinstance(node_type, str)): raise TypeError('查询的结点的类型必须要指定,而且node_type必须是字符串形式') if not (where is None): if not (isinstance(where, str)): raise TypeError('where表示的是查询条件,它必须是字符串形式') if (properties is None) and (where is None): res = matcher.match(node_type) if len(list(res)) > 0: return list(res) else: return None elif (not (properties is None)) and (where is None): res = matcher.match(node_type, **properties) if len(list(res)) > 0: return list(res) else: return None elif (properties is None) and (not (where is None)): res = matcher.match(node_type).where(where) if len(list(res)) > 0: return list(res) else: return None
def create_db(): sym = pd.read_csv('./data/sym_t.csv') dia = pd.read_csv('./data/dia_t.csv') rel = pd.read_csv('./data/diffsydiw.csv') sym = sym.dropna() dia = dia.dropna() rel = rel.dropna() # create graph database graph = Graph("http://localhost:7474/") # create nodes corresponding to symptoms for row_idx, row in sym.iterrows(): node = Node('Symptom', id = row['syd'], name = row['symptom']) graph.create(node) # create nodes corresponding to diagnoses for row_idx, row in dia.iterrows(): node = Node('Diagnosis', id = row['did'], name = row['diagnose']) graph.create(node) matcher = NodeMatcher(graph) sym_set = set(sym['syd']) dia_set = set(dia['did']) # create relations between symptoms ans diagnoses for row_idx, row in rel.iterrows(): print(row_idx) if (row['syd'] in sym_set) and (row['did'] in dia_set): sym_node = matcher.match('Symptom', id=row['syd']).first() dia_node = matcher.match('Diagnosis', id=row['did']).first() relation = Relationship(sym_node, 'INDICATES', dia_node) graph.create(relation) return graph
def paper_conference(): for paper in coll_paper.find(): paper_id = paper['_id'] con_name = paper['conference'] selector = NodeMatcher(graph) items = selector.match('paper', id=paper_id) # 如果这个论文paper已经存在 if len(items) > 0: paper_node = list(items)[0] # 否则创建新节点 else: paper_node = Node('paper', title=paper['title'], id=paper_id) graph.create(paper_node) entity = coll_conference.find_one({ 'conferenceName': con_name, 'year': paper['year'] }) if entity is None: continue en_id = str(entity['_id']) selector = NodeMatcher(graph) items = selector.match('conference', id=en_id) con_node = Node('conference', conferenceName=con_name, id=en_id, year=entity['year']) if len( items) == 0 else \ list(items)[0] R = Relationship(paper_node, 'published_on', con_node) graph.create(R)
def insertarNoticia(self, noticia, retweets, propietari, plataforma): a = Node("Noticia", title=noticia, retweets=retweets) tx = self.graph.begin() tx.create(a) matcher = NodeMatcher(self.graph) redactorInDB = matcher.match("Redactor", redactor=propietari).first() redactorRel = Node("Redactor", redactor=propietari) plataformaInDB = matcher.match("Plataforma", plataforma=plataforma).first() plataformaRel = Node("Plataforma", plataforma=plataforma) if redactorInDB is None: redactadaPor = Relationship(a, "redactadaPor", redactorRel) tx.create(redactadaPor) else: redactadaPor = Relationship.type("redactadaPor") tx.merge(redactadaPor(a, redactorInDB)) if plataformaInDB is None: disponibleEn = Relationship(a, "disponibleEn", plataformaRel) tx.create(disponibleEn) else: disponibleEn = Relationship.type("disponibleEn") tx.merge(disponibleEn(a, plataformaInDB)) tx.commit()
def paper_field(): for paper in coll_paper.find(): paper_id = paper['_id'] term_dic = json.loads(str(paper['terms']).replace("\'", "\"")) terms = term_dic['IEEE Keywords'] if 'IEEE Keywords' in term_dic else [] selector = NodeMatcher(graph) items = selector.match('paper', xid=paper_id) # 如果这个论文paper已经存在 if len(items) > 0: paper_node = list(items)[0] # 否则创建新节点 else: paper_node = Node('paper', title=paper['title'], xid=paper_id) graph.create(paper_node) for field_name in terms: entity = coll_field.find_one({'fieldName': field_name}) if entity is None: continue en_id = str(entity['_id']) selector = NodeMatcher(graph) items = selector.match('field', xid=en_id) field_node = Node('field', fieldName=field_name, xid=en_id) if len( items) == 0 else \ list(items)[0] R = Relationship(paper_node, 'describe', field_node) graph.create(R)
def insert_relationship(g, people_data): nodes = NodeMatcher(g) tx = g.begin() RELATIONSHIPS = { "actor": Relationship.type("ACT_IN"), "actress": Relationship.type("ACT_IN"), "director": Relationship.type("DIRECT"), "producer": Relationship.type("PRODUCE"), } visited = set() for i in range(len(people_data)): person_id, movie_id = people_data[i]["nconst"], people_data[i][ "tconst"] if (person_id, movie_id) not in visited: print(f"{i} Insert Relation: {person_id},{movie_id}") visited.add((person_id, movie_id)) person = nodes.match("Person", id=person_id).first() movie = nodes.match("Movie", id=movie_id).first() this_relation = people_data[i]["category"] if person and movie: tx.create(RELATIONSHIPS[this_relation](person, movie)) else: print(f"{i} Skip: {person_id},{movie_id}") if i % 1000 == 0: print("Committing ...") tx.commit() tx = g.begin() tx.commit()
def luru(iii, jjj, ForS, rName): i = iii while i < length: j = 1 n1 = len(graph.nodes.match('Char', name=s[i])) if n1 == 0: a = Node("Char", name=s[i]) graph.create(a) matcher = NodeMatcher(graph) a = matcher.match(name=s[i]).first() while j < jjj: n2 = len(graph.nodes.match('Char', name=s[i + j])) if n2 == 0: b = Node("Char", name=s[i + j]) graph.create(b) matcher = NodeMatcher(graph) b = matcher.match(name=s[i + j]).first() r = Relationship(a, rName, b) graph.create(r) a = matcher.match(name=s[i + j]).first() j += 1 i += ForS
def insertarData(self, noticia, data): matcher = NodeMatcher(self.graph) noticiarel = matcher.match("Noticia", title=noticia).first() dataInDB = matcher.match("Fecha", data="{}-{}-{}".format( data.year, data.month, data.day)).first() dataRel = Node("Fecha", data="{}-{}-{}".format(data.year, data.month, data.day)) tx = self.graph.begin() if dataInDB is None: tx.create(dataRel) publicadaEl = Relationship(dataRel, "publicadaEl", noticiarel) tx.create(publicadaEl) mesos = [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre', 'Octubre', 'Noviembre', 'Diciembre' ] mesInDB = matcher.match("Anio", data="{} {}".format( mesos[data.month - 1], data.year)).first() mesRel = Node("MesAnio", data="{} {}".format(mesos[data.month - 1], data.year)) if mesInDB is None: contiene = Relationship(mesRel, "contiene", dataRel) tx.create(contiene) else: contiene = Relationship.type("contiene") tx.merge(contiene(mesInDB, dataRel)) else: publicadaEl = Relationship.type("publicadaEl") tx.merge(publicadaEl(dataInDB, noticiarel)) tx.commit()
def paper_author(): """ 构建 paper - author 关系 :return: """ for paper in coll_paper.find(): paper_id = paper['_id'] selector = NodeMatcher(graph) items = selector.match('paper', id=paper_id) # 如果这个论文paper已经存在 if len(items) > 0: paper_node = list(items)[0] # 否则创建新节点 else: paper_node = Node('paper', title=paper['title'], id=paper_id) graph.create(paper_node) for author_name in paper['authors'].split(';'): # author entity entity = coll_author.find_one({'authorName': author_name}) if entity is None: continue # 查找图中是否有这个author selector = NodeMatcher(graph) items = selector.match('author', id=entity['_id']) author_node = Node('author', authorName=author_name, id=entity['_id']) if len(items) == 0 else \ list(items)[0] R = Relationship(author_node, 'publish', paper_node) graph.create(R)
def getNodes(self, nodeLabel: str, property: str, operator: str, value: str, orderByProperty: str = None, nlimit: int = 10): ''' This method will returns list of Nodes if the node property matches value. Returns [] if nothing matches. operators : = <> > >= < <= 'STARTS WITH' 'ENDS WITH' 'CONTAINS' Refer to: https://py2neo.org/v4/matching.html?highlight=matcher#node-matching ''' matcher = NodeMatcher(self._graph) matchQuery = f"_.{property} {operator} {value}" if orderByProperty: searchNodes = list( matcher.match(nodeLabel).where(matchQuery).order_by( f"_.{orderByProperty}").limit(nlimit)) else: searchNodes = list( matcher.match(nodeLabel).where(matchQuery).limit(nlimit)) self._logger.info(f"{len(searchNodes)} nodes matched search criteria") return searchNodes
class neo4jserver: """ 封装neo4j的orm """ def __init__(self, url, name, pwd): #pymysql.connect('rm-bp171b759ha99x5wfso.mysql.rds.aliyuncs.com',port=3306,user='******',passwd='HPGQEhutFBUCi8ZE8JYgWDwZVhAHXWJx',db='businessdata') self.graph = Graph(url, username=name, password=pwd) self.start = self.graph.begin() def close(self): #self.start.close() pass def insert_entity(self, data): self.start.create(data) self.start.commit() def insert_relation(self, data=[], relation=[]): data = Subgraph(data, relationships=relation) self.start.create(data) self.start.commit() def select_entity_sql(self, sql): self.graph.run(sql).data() # list型 self.graph.run(sql).to_data_frame() # dataframe型 self.graph.run(sql).to_table() # table def select_entity_cond(self, obj, condition): self.matcher = NodeMatcher(self.graph) self.matcher.match("Person", name="Kevin").first() self.matcher.match("Person", name__not="Rick Astley").first() '''
def query_entity(self): nmatcher = NodeMatcher(self.graph) rmatcher = RelationshipMatcher(self.graph) # 大通有哪些车 a_node = nmatcher.match('品牌', name='上汽大通').first() b_node = nmatcher.match('车系').first() relation = rmatcher.match({a_node, b_node}).first() zz = self.graph.match((a_node, ), r_type=type(relation).__name__).all() result = [] for z in zz: result.append(z.end_node.get('name')) print('大通具有:') print(result) # nodes = rmatcher.match({a_node, b_node}).all() # print(nodes[0]) # print(nodes[0].start_node) # print(nodes[0].end_node) # print(nodes[0].nodes) # print(type(nodes[0]).__name__) # # A(实体)车的基本参数(实体) a_node = nmatcher.match('车型', name='2019款 2.0T柴油自动四驱精英型长厢高底盘').first() b_node = nmatcher.match('基本参数').first() relation = rmatcher.match({a_node, b_node}).first() print(relation) print(type(relation).__name__) print(dict(nmatcher.match(name='2019款 2.0T柴油自动四驱精英型长厢高底盘').first())) zz = self.graph.match(nodes=(relation.start_node, ), r_type=type(relation).__name__).all()[0].end_node print(zz)
def main(): # Can I keep the user_node text_generator = open_file( '/Users/Lim/Documents/DAnalyticsWorkspace/ml-10M100K/ratings.dat') graph.begin() matcher = NodeMatcher(graph) # for text in text_generator: useriddd = 0 for data in text_generator: if data: split_data = data.split('::') # split_data[3] = split_data[3].replace("\n", "") for x in range(4): if x == 2: split_data[x] = float(split_data[x]) split_data[x] = int(split_data[x]) user_id, movie_id, ratings = split_data[0:3] movie_node = matcher.match("Movie", id=movie_id).first() user = matcher.match("User", id=user_id).first() if not user: user_node = Node("User", id=user_id) insert_rating(user_node, ratings, movie_node) else: insert_rating(user, ratings, movie_node) if user_id > useriddd: useriddd = user_id sys.stdout.write('{}\r' + str(useriddd)) # insert_rating(user_node, ratings, matcher.match("Movie", id=movie_id).first()) graph.commit()
def write_symptom_info(symptom_info): graph = Graph("bolt://localhost:7687", username="******", password='******') node_matcher = NodeMatcher(graph) try: # 症状 if symptom_info.get('症状') is not None: symptom = node_matcher.match("symptom").where( f"_.name = '{symptom_info['症状']}'").first() # 此节点还未创建 if symptom is None: symptom = Node('symptom', name=symptom_info['症状']) graph.create(symptom) # 概述 if symptom_info.get('概述') is not None: print(symptom_info['概述']) symptom['brief'] = symptom_info['概述'] graph.push(symptom) # 病因 if symptom_info.get('病因') is not None: symptom['cause'] = symptom_info['病因'] graph.push(symptom) # 检查 if symptom_info.get('检查') is not None: symptom['check'] = symptom_info['检查'] graph.push(symptom) # 诊断 if symptom_info.get('诊断') is not None: symptom['diagnose'] = symptom_info['诊断'] graph.push(symptom) # 预防 if symptom_info.get('预防') is not None: symptom['prevent'] = symptom_info['预防'] graph.push(symptom) # 可能患有的疾病 if symptom_info.get('可能患有的疾病') is not None: for jib in symptom_info['可能患有的疾病']: disease = node_matcher.match('disease').where( f"_.name = '{jib}'").first() if disease is None: disease = Node('disease', name=jib) symptom_disease = Relationship(symptom, 'symptom_disease', disease) graph.create(symptom_disease) # 常见症状 if symptom_info.get('常见症状') is not None: for zz in symptom_info['常见症状']: r_symptom = node_matcher.match('symptom').where( f"_.name = '{zz}'").first() if r_symptom is None: r_symptom = Node('symptom', name=zz) symptom_r_symptom = Relationship(symptom, 'r_symptom', r_symptom) graph.create(symptom_r_symptom) return True except Exception as e: with open('error.txt', 'a') as f: f.write(f"write_symptom_info:{symptom_info['症状']}\n{e}\n") return False return True
def parse_smali_file(self, content): """ parses a single smali file and inserts the data to the smali database :param content: content of the smali file :return: null """ # TODO add the regex to parse the called function and change the FOR loop # TODO change code to use all the new methods # parse class class_name = self.get_class_name(content=content) methods = self.get_methods(content=content) # add methods to db for method in methods: method_name = method[0].split(' ')[-1] method_parameters = method[1] method_return_value = method[2] method_data = method[3] method_id = '%s->%s' % (class_name, method_name) called_methods = self.get_called_methods(content=method_data) method_calling_to = '' # Neo4j matcher = NodeMatcher(graph) bma = matcher.match("Method", name=method_id).first() if bma is None: tx = graph.begin() a = Node("Method", name=method_id) tx.create(a) tx.commit() # Neo4j for called_method in called_methods: # Neo4j name = '%s->%s' % (called_method[1], called_method[2]) sma = matcher.match("Method", name=name).first() if sma is None: tx = graph.begin() b = Node("Method", name=name) tx.create(b) tx.commit() sma = matcher.match("Method", name=name).first() bma = matcher.match("Method", name=method_id).first() tx = graph.begin() mab = Relationship(bma, "Call", sma) tx.create(mab) tx.commit() # Neo4j method_calling_to = '%s%s->%s,' % ( method_calling_to, called_method[1], called_method[2]) self.db.add_method(id=method_id, class_name=class_name, method_name=method_name, parameters=method_parameters, calling_to=method_calling_to, return_value=method_return_value, data=method_data) '''
def add_cell(self, code, prev_node, var, cell_id, nb_name): """ Stores the Jupyter cell in base64 encoded form, and adds a link to the previously stored node (for cell provenance tracking). """ self._fetch_code_dict() #print(code) bcode = base64.b64encode(bytes(code, "utf-8")) #print(bcode) nbcode = bcode.decode("utf-8") matcher = NodeMatcher(self.graph_db) if bcode in self.code_dict or nbcode in self.code_dict: current_cell = matcher.match("Cell", source_code=bcode).first() else: if len(list(self.code_dict.values())) != 0: max_id = max(list(self.code_dict.values())) else: max_id = 0 current_cell = Node("Cell", name=f"cell_{max_id + 1}", source_code=nbcode) self.graph_db.create(current_cell) self.graph_db.push(current_cell) if prev_node is not None: successor = Relationship(prev_node, "Successor", current_cell) self.graph_db.create(successor) self.graph_db.push(successor) parent = Relationship(current_cell, "Parent", prev_node) self.graph_db.create(parent) self.graph_db.push(parent) self.code_dict[bcode] = max_id + 1 try: self._store_code_dict() except Exception as e: logging.info(f"Code update for Neo4j failed with error {e}") var_name = f"{cell_id}_{var}_{nb_name}" current_var = matcher.match("Var", name=var_name).first() if current_var is None: current_var = Node("Var", name=var_name) self.graph_db.create(current_var) self.graph_db.push(current_var) contains_edge = Relationship(current_cell, "Contains", current_var) self.graph_db.create(contains_edge) self.graph_db.push(contains_edge) contained_by_edge = Relationship(current_var, "Containedby", current_cell) self.graph_db.create(contained_by_edge) self.graph_db.push(contained_by_edge) return current_cell
def fang_fangfenlei_Relationship(list1,list2): matcher=NodeMatcher(graph) rel_zhengfangs = [] for i in range(0,len(list1)): m=matcher.match("方剂", 方剂名称=list1[i]) n=matcher.match("方剂分类",方剂分类名称=list2[i]) print(m) rel_zhengfangs.append([m,n]) return rel_zhengfangs
def bing_fang_relationship1(bingming,fangji): matcher=NodeMatcher(graph) for j in range(0,279): n=matcher.match("皮肤病",皮肤病名称=bingming[j]) m=matcher.match("方剂",方剂名称=fangji[j]) for node in n: for node1 in m: n_m=Relationship(node,"效验方",node1) graph.create(n_m)
def change(): if request.method == 'POST': graph = Graph('http://localhost:7474', username='******', password='******') user_change1 = request.form.get("change_company") user_change2 = request.form.get("change_position") user_change3 = request.form.get("change_name") user_change4 = request.form.get("new_name") # user_changeposition = Position.match(graph, user_change2).first() # user_changenode1 = Shareholder.match(graph, user_changerel1).first() # user_changenode2 = Company.match(graph, user_changerel2).first() matcher = NodeMatcher(graph) company_node = matcher.match("Company", name=user_change1).first() position_node = matcher.match("Position", name=user_change2, company=user_change1).first() name_node = matcher.match("name", name=user_change3).first() graph.delete(name_node) new_node = Node("name", name=user_change4) new_rel = Relationship(new_node, "属于", position_node) total_change = new_rel | new_node graph.create(total_change) ''' # 单节点对应属性修改 if len(user_change1) > 0: if user_change2 == "height": user_changenode.height = user_change3 if user_change2 == "age": user_changenode.age = user_change3 graph.push(user_changenode) # 节点关系修改 if len(user_changerel1) > 0: if user_changerel3 == "经营": user_changenode1.manager.remove(user_changenode2) graph.push(user_changenode1) relationship = Relationship(x1, user_changerel4, x2) graph.create(relationship) if user_changerel3 == "股东": user_changenode1.shareholder.remove(user_changenode2) graph.push(user_changenode1) relationship = Relationship(x1, user_changerel4, x2) graph.create(relationship) ''' return render_template('change.html')
def returnPodcasts(): # Connect to database graph = Graph("http://*****:*****@localhost:7474") nodematcher = NodeMatcher(graph) relamatcher = RelationshipMatcher(graph) # Find the nodes for the cast members and the podcast. castNodes = nodematcher.match("CAST") podcastNodes = nodematcher.match("PODCAST") nodes = [] # Convert the nodes to GraphJSON format for Alchemy.js for node in castNodes: nodes.append({ "id": node.identity, "name": node["name"], "rta": node["rta"], "tp": node["tp"], "ao": node["ao"] }) for node in podcastNodes: nodes.append({ "id": node.identity, "name": node["name"], "rta": node["rta"], "tp": node["tp"], "ao": node["ao"] }) jsonNodes = dumps(nodes) # Find the Relationships within the database relationships = relamatcher.match(None, "APPEARED_ON") edges = [] # Convert the relationships to GraphJSON for rel in relationships: edges.append({ "source": rel.start_node.identity, "target": rel.end_node.identity, "role": "appeared_on" }) jsonEdges = dumps(edges) # Create a json string with all GraphJSON finalJson = '{"nodes": ' + jsonNodes + ', "edges": ' + jsonEdges + '}' # Save file to server cache with open(webserverstatic + 'main.json', "w+") as jsonFile: jsonFile.write(finalJson) jsonFile.close() # Send file to template to display generated graph return render_template('showdata.html', message="main")
def yao_fenlei(fenlei_name,datalist): matcher=NodeMatcher(graph) m=matcher.match("中药分类",中药分类名称=fenlei_name) for node in m: for count1 in datalist: n1=matcher.match("中药",中药名称=count1) for node1 in n1: #print(node1) n1_m=Relationship(node1,"属于",node) graph.create(n1_m)
def create_rel(self): matcher = NodeMatcher(self.graph) main_node = matcher.match(main_node_label, name=main_node_label) # 建立主节点和电影名的联系 i = 1 for each_movie in movie_name_list: movie_node = matcher.match(movie_name_label, name=each_movie) movie_to_main = Relationship(movie_node, 'no.' + str(i), main_node) i += 1 self.graph.create(movie_to_main)
def yao_fangji_createRelationship(list1,list2): matcher=NodeMatcher(graph) for i in range(0,len(list1)): m=matcher.match("中药", 中药名称=list1[i]) n=matcher.match("方剂",方剂名称=list2[i]) for node in m: print(dict(node)['中药名称']) for node1 in n: print(dict(node1)['方剂名称']) n_m=Relationship(node,"入药方剂",node1) graph.create(n_m)
def changeRelation(request): if request.method == 'GET': return render(request, 'changeRelation.html', { 'entitytypes': entitytypes, 'relationtypes': relationtypes }) else: s_entity_label = request.POST.get('s_entity_type') s_entity_name = request.POST.get('s_entityname') e_entity_label = request.POST.get('e_entity_type') e_entity_name = request.POST.get('e_entityname') origin_relation_label = request.POST.get('origin_relation_type') change_relation_label = request.POST.get('change_relation_type') relation_name = request.POST.get('relationname') for key in entity_map: if key == s_entity_label: start_entity_label = entity_map[key] if key == e_entity_label: end_entity_label = entity_map[key] matcher = NodeMatcher(g) try: s_node = matcher.match(start_entity_label, name=s_entity_name).first() e_node = matcher.match(end_entity_label, name=e_entity_name).first() if not all([s_node, e_node]): messages.error(request, '节点选择有误') return render(request, 'changeRelation.html', { 'entitytypes': entitytypes, 'relationtypes': relationtypes }) # result = g.match(nodes=[s_node, e_node], r_type=origin_relation_label) # if len(list(result)) == 0: # messages.error(request, '关系不存在') # return render(request, 'changeRelation.html', {'entitytypes': entitytypes, 'relationtypes': relationtypes}) r = 'match (n:' + start_entity_label + ' {name:"' + s_entity_name + '"})-[r:' + origin_relation_label + ']->(m:' + end_entity_label + ' {name:"' + e_entity_name + '"}) create (n)-[r2:' + change_relation_label + ']->(m) set r2.name="' + relation_name + '" delete r' g.run(r) except Exception as e: print(e) messages.success(request, '修改失败') return render(request, 'changeRelation.html', { 'entitytypes': entitytypes, 'relationtypes': relationtypes }) else: messages.success(request, '修改成功') return render(request, 'changeRelation.html', { 'entitytypes': entitytypes, 'relationtypes': relationtypes })
def bing_zheng_relationship1(): matcher=NodeMatcher(graph) with open("皮肤病\\病-证.csv",encoding="gbk") as f: for row in f.readlines(): row=row.strip() rowDict=row.split(',') #print(rowDict[0]) n=matcher.match("皮肤病",皮肤病名称=rowDict[0]) m=matcher.match("证候分类",证候分类名称=rowDict[1]) for node in n: for node1 in m: n_m=Relationship(node,"病所属证候",node1) graph.create(n_m)
def query_test(self): nmatcher = NodeMatcher(self.graph) rmatcher = RelationshipMatcher(self.graph) # A车的基本参数 a_node = nmatcher.match('车型', name='2019款 2.0T柴油自动四驱精英型长厢高底盘').first() # relation = rmatcher.match({a_node, b_node}).first() relation = self.graph.match(nodes=(a_node, ), r_type='基本参数').all() print(dict(relation[0].end_node)) # gg = self.graph.match(nodes=(relation.start_node, relation.end_node)).all() # b_node = nmatcher.match('车型基本参数', name='基本参数节点').first()