本文整理汇总了Python中py2neo.Graph.node方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.node方法的具体用法?Python Graph.node怎么用?Python Graph.node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类py2neo.Graph
的用法示例。
在下文中一共展示了Graph.node方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_info_and_links
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
def update_info_and_links():
print 'updating show info'
authenticate("localhost:7474", "neo4j", "1234")
graph = Graph(GRAPH_CONNECTION_STRNIG)
results = graph.cypher.stream("match (s:Show) return id(s) as eid,s.id")
start_id = 0
for record in results:
if int(record['s.id']) < start_id:
continue
node_show = graph.node(record['eid'])
result_dict = {}
success = True
while success:
try:
show_info_e_list = requests.get(
'http://services.tvrage.com/feeds/full_show_info.php?sid={0}'.format(node_show['id']))
result_dict = xmltodict.parse(show_info_e_list.text)
omdb_show_info = requests.get(
'http://www.omdbapi.com/?t={0}&y=&plot=full&r=json'.format(node_show['name']))
dict_omdb_show_info = json.loads(omdb_show_info.text)
if dict_omdb_show_info['Response'] == 'True':
for key, value in dict_omdb_show_info.iteritems():
node_show[key] = value
success = False
except ValueError as e:
logger.exception("Value error")
continue
except Exception as e:
logger.exception("Some network issue: will try again")
success = True
print str(node_show['name'])
# info
node_show['started'] = result_dict['Show'].get('started', None)
node_show['ended'] = result_dict['Show'].get('ended', None)
node_show['image'] = result_dict['Show'].get('image', None)
node_show['status'] = result_dict['Show'].get('status', None)
node_show.push()
#Country
from_country = result_dict['Show'].get('origin_country', 'unknown')
node_country = graph.merge_one("Country", 'country', from_country)
node_country.push()
show_from_country = Relationship(node_show, "from", node_country)
graph.create(show_from_country)
#Genres
if result_dict['Show'].get('genres', None) is not None:
genre_list = []
if type(result_dict['Show']['genres']['genre']) is list:
genre_list = result_dict['Show']['genres']['genre']
else:
genre_list.append(result_dict['Show']['genres']['genre'])
for genre in genre_list:
node_genre = graph.merge_one("Genre", 'name', genre)
node_genre.push()
show_of_genre = Relationship(node_show, "of genre", node_genre)
graph.create(show_of_genre)
"""
try:
print node_show['started']
a = node_show['started'].split("/")
if int(a[len(a)-1]) < 2000:
continue
except Exception:
continue
"""
#Seasons
season_list = []
if result_dict['Show'].get('Episodelist', None) is None:
continue
if type(result_dict['Show']['Episodelist']['Season']) is list:
season_list = result_dict['Show']['Episodelist']['Season']
else:
season_list.append(result_dict['Show']['Episodelist']['Season'])
for season in season_list:
node_season = Node.cast('Season', {'no': season['@no']})
graph.create(node_season)
show_season = Relationship(node_show, "has", node_season)
graph.create(show_season)
#Episodes
episode_list = []
if type(season['episode']) is list:
episode_list = season['episode']
#.........这里部分代码省略.........
示例2: int
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
if a and b:
ENDPOINT = "http://neo4j:[email protected]:7474/db/data/"
request = {
"to":ENDPOINT+"node/"+str(b._id),
"max_depth": int(sys.argv[3]),
"relationships": {
"type":"LINKS",
"direction":"out"
},
"algorithm":"allSimplePaths"
}
r = requests.post(ENDPOINT+"node/"+str(a._id)+"/paths", data=json.dumps(request))
# print r.json()
if r.status_code == 200:
for path in r.json():
print "Path:"
for node in path['nodes']:
# print node
retrieved_node = graph.node(node.split('/node/')[1])
print retrieved_node.properties['title'], "->"
print "--------------------"
else:
print "Something went wrong."
print sys.exc_info()[0]
else:
if not a:
print sys.argv[1], "not found!"
else:
print sys.argv[2], "not found!"
示例3: update_show_info_old
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
def update_show_info_old():
print 'updating show info'
authenticate("localhost:7474", "neo4j", "1234")
graph = Graph(GRAPH_CONNECTION_STRNIG)
results = graph.cypher.stream("match (s:Show) return id(s) as eid,s.id")
start_id = 764
for record in results:
if int(record['s.id']) < start_id:
continue
node_show = graph.node(record['eid'])
result_dict = {}
success = True
while success:
try:
show_info_e_list = requests.get(
'http://services.tvrage.com/feeds/full_show_info.php?sid={0}'.format(node_show['id']))
result_dict = xmltodict.parse(show_info_e_list.text)
omdb_show_info = requests.get(
'http://www.omdbapi.com/?t={0}&y=&plot=full&r=json'.format(node_show['name']))
dict_omdb_show_info = json.loads(omdb_show_info.text)
if dict_omdb_show_info['Response'] == 'True':
for key, value in dict_omdb_show_info.iteritems():
node_show[key] = value
success = False
except ValueError as e:
logger.exception("Value Error")
continue
except Exception as e:
logger.exception("Some network issue, will try again")
success = True
print str(node_show['name'])
# info
node_show['started'] = result_dict['Show'].get('started', None)
node_show['ended'] = result_dict['Show'].get('ended', None)
node_show['image'] = result_dict['Show'].get('image', None)
node_show['status'] = result_dict['Show'].get('status', None)
node_show.push()
#Country
from_country = result_dict['Show'].get('origin_country', 'unknown')
node_country = graph.merge_one("Country", 'country', from_country)
node_country.push()
show_from_country = Relationship(node_show, "from", node_country)
graph.create(show_from_country)
#Genres
if result_dict['Show'].get('genres', None) is not None:
genre_list = []
if type(result_dict['Show']['genres']['genre']) is list:
genre_list = result_dict['Show']['genres']['genre']
else:
genre_list.append(result_dict['Show']['genres']['genre'])
for genre in genre_list:
node_genre = graph.merge_one("Genre", 'name', genre)
node_genre.push()
show_of_genre = Relationship(node_show, "of genre", node_genre)
graph.create(show_of_genre)
"""try:
print node_show['started']
a = node_show['started'].split("/")
if int(a[len(a)-1]) < 2000:
continue
except Exception:
continue
"""
#Seasons
season_list = []
if result_dict['Show'].get('Episodelist', None) is None:
continue
if type(result_dict['Show']['Episodelist']['Season']) is list:
season_list = result_dict['Show']['Episodelist']['Season']
else:
season_list.append(result_dict['Show']['Episodelist']['Season'])
for season in season_list:
node_season = Node.cast('Season', {'no': season['@no']})
graph.create(node_season)
show_season = Relationship(node_show, "has", node_season)
graph.create(show_season)
#Episodes
episode_list = []
if type(season['episode']) is list:
episode_list = season['episode']
else:
#.........这里部分代码省略.........
示例4: floor
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
r1 = floor(tot_len * (i + 1) * 0.01)
if l1-1 == r1:
l1 = r1
cursor1 = db.get_cursor()
cursor1.execute(query1,(str(tmony),str(l1),str(r1)))
if(i == 50):
while True:
row = cursor1.fetchone()
if not row:
break
# Process each of these UNIQUE parent id's here
if row:
term_node = graph.find_one("TERM", "term_id", row["parent_id"])
segment_node_id = graph.cypher.execute(query2neo4id, {"tmony": tmony, "segment": str(i+1)})
segment_node = graph.node(segment_node_id[0][0])
has_term_relationship = Relationship(segment_node, "HAS_TERM", term_node)
is_in_relationship = Relationship(term_node, "IS_IN", segment_node)
graph.create(has_term_relationship)
graph.create(is_in_relationship)
cursor1.close()
count += 1
示例5: __init__
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
class GraphDB:
def __init__(self,username, password, server, port):
'''
username = 'neo4j'
password = '*'
server = 'localhost'
port = '7474'
'''
self.username = username
self.password = password
self.server = server
self.port = port
self.con_url = 'http://'+username+':'+password+'@'+server+':'+port+'/db/data/'
self.graph = Graph(self.con_url)
##TODO: move these to constants.py when IPYTHON not required
self.metaprops = {
'RESOLVEDUUID':'_resolvedWithUUID_',
'RESOLVEDRELID':'_resolvedWithRELID_',
'RESOLVEDHENID':'_resolvedWithHENID_', ##for hyper edge node
'RESOLVEDHERID':'_resolvedWithHERID_', ##for hyper edge relation
}
#Done: Multiple each time want to ask something
#Else: works on old data only
##Wont use this
def getGraph(self):
return self.graph
##NOT TO BE USED
#this is how we use the intenal ids of the graph
##should we use it?? most people say no
## anyways, made the method for future use
## Use : getNodeByInternalId(graph, 152)
def getNodeByInternalId(self,id):
a = self.graph.node(id) #getting by id given internally by neo4j
a.pull()
return a
##NOT TO BE USED
## similar to above
## Use : getRelByInternalId(graph, 4)
def getRelByInternalId(self,id):
a = self.graph.relationship(id)
a.pull()
return a
def getNodeByUniqueID(self, uniquelabel, idName, idVal, isIDString=False):
##TODO: move uuid to props
query = "match (n:"+uniquelabel+" {"
if isIDString:
query = query+ idName+":'"+str(idVal)+"'}) return n"
else:
query = query+ idName+":"+str(idVal)+"}) return n"
rc = self.graph.cypher.execute(query)
return rc[0][0]
def getRelationByUniqueID(self, idName, idVal, isIDString=False):
##TODO: move uuid to props
query = "match ()-[r {"
if isIDString:
query = query+ idName+":'"+str(idVal)+"'}]->() return r"
else:
query = query+ idName+":"+str(idVal)+"}]->() return r"
rc = self.graph.cypher.execute(query)
return rc[0][0]
def isPropList(self, node, prop):
return type(node[prop]) is list
##has a counter brother in nexusapis flask app
def isValidNonMetaProp(self, propname):
if propname[0]=='_' or propname[-1]=='_':
return False
return True
##copy meta = True
def copyNode(self, node, copymeta = True, exceptions = []):
#exceptions are the props that should be included no matter what, if they have underscore or not!
naya = Node()
for label in node.labels:
naya.labels.add(label)
for prop in exceptions:
if prop in node.properties:
naya[prop] = node[prop]
for prop in node.properties:
if not copymeta:
if self.isValidNonMetaProp(prop):
naya[prop] = node[prop]
else:
naya[prop] = node[prop]
return naya
def copyNodeAsItIs(self, node):
return self.copyNode(node)
# naya = Node()
#.........这里部分代码省略.........
示例6: DatabaseConnection
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
class DatabaseConnection(object):
def __init__(self):
authenticate("localhost:7474", "neo4j", "admin")
self.connection = Graph()
def add_person(self, person_name, year_of_birth):
self.connection.create(Node("Person", name=person_name, born=year_of_birth))
def add_relationship(self, start_id, end_id, relationship_type):
start_node = self.connection.node(start_id)
end_node = self.connection.node(end_id)
self.connection.create(Relationship(start_node, relationship_type, end_node))
def remove_relationship(self, relationship_id):
self.connection.cypher.stream(
"MATCH (n) - [r] - () WHERE ID(r) = {} DELETE r".format(relationship_id))
def remove_person(self, person_id):
self.connection.cypher.stream(
"MATCH(p:Person) where ID(p) = {} OPTIONAL MATCH(p) - [r] - () DELETE r, p".format(
person_id))
def add_person_property(self):
pass
def update_person(self, person_id, person_properties):
node_to_update = self.get_neo4j_person(person_id)
keys = node_to_update.properties.keys()
for key in keys:
del node_to_update.properties[key]
if person_properties:
for key in person_properties:
node_to_update.properties[key] = person_properties[key]
node_to_update.push()
def update_relationship(self, relationship_id, relationship_properties):
relationship_to_update = self.get_neo4j_relationship(relationship_id)
keys = relationship_to_update.properties.keys()
for key in keys:
del relationship_to_update.properties[key]
if relationship_properties:
for key in relationship_properties:
relationship_to_update.properties[key] = relationship_properties[key]
relationship_to_update.push()
def get_neo4j_person(self, person_id):
single_node_list = self.connection.cypher.stream(
"MATCH(p:Person) where ID(p) = {} RETURN p".format(person_id))
for a_node in single_node_list:
return a_node[0]
def get_person(self, person_id):
neo_node = self.get_neo4j_person(person_id)
return person.Person(str(neo_node.uri).rsplit('/', 1)[-1],
neo_node.properties["name"],
neo_node.properties["born"],
neo_node.properties)
def get_all_persons(self):
nodes = list()
for n in self.connection.cypher.stream("START z=node(*) RETURN z"):
new_node = person.Person(str(n[0].uri).rsplit('/', 1)[-1], n[0].properties["name"],
n[0].properties["born"], n[0].properties)
nodes.append(new_node)
return nodes
def get_relationship(self, relationship_id):
neo_relationship = self.get_neo4j_relationship(relationship_id)
relationship_to_return = relationship.Relationship(
relationship_id=str(neo_relationship.uri).rsplit('/', 1)[-1],
start_node=neo_relationship.start_node,
end_node=neo_relationship.end_node,
relationship_type=neo_relationship.type,
properties=neo_relationship.properties)
return relationship_to_return
def get_neo4j_relationship(self, relationship_id):
single_relationship_list = self.connection.cypher.stream(
"MATCH (n) - [r] - () WHERE ID(r) = {} RETURN r"
.format(relationship_id))
for a_relation in single_relationship_list:
return a_relation[0]
def get_all_relationships(self):
relations = list()
for relation in self.connection.cypher.stream("Match (a)-[r]->(b) return r"):
new_relationship = relationship.Relationship(
relationship_id=str(relation[0].uri).rsplit('/', 1)[-1],
start_node=relation[0].start_node,
end_node=relation[0].end_node,
relationship_type=relation[0].type,
properties=relation[0].properties)
relations.append(new_relationship)
return relations
def get_child_generations_for_person(self, person_id):
return_value = next(self.connection.cypher.
stream(
"MATCH p=(r:Person)<-[:CHILD_OF*1..20]-(x) WHERE ID(r) = {} RETURN max(length(p))".
format(person_id)))[0]
#.........这里部分代码省略.........
示例7: __init__
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
class Neo4jModel:
def __init__(self):
self.graph = Graph()
def create(self):
self.graph.schema.create_uniqueness_constraint("Region", "name")
self.graph.schema.create_uniqueness_constraint("Court", "name")
self.graph.schema.create_uniqueness_constraint("Court_Decision_Type", "name")
self.graph.schema.create_uniqueness_constraint("Court_Judgement_Type", "name")
self.graph.schema.create_uniqueness_constraint("Case", "id")
self.graph.schema.create_uniqueness_constraint("Chairman", "name")
def region(self, region_name):
__region = self.graph.merge_one("Region", "name", region_name)
__region.push()
return __region
def court(self, court_name, region_name):
__court = self.graph.merge_one("Court", "name", court_name)
__court.push()
self.graph.create_unique(Relationship(__court, "SITUATED_IN", self.region(region_name)))
return __court
def chairman(self, chairman_name):
__chairman = self.graph.merge_one("Chairman", "name", chairman_name)
__chairman.push()
return __chairman
def decision_type(self, decision_type_name):
__decision_type = self.graph.merge_one("Court_Decision_Type", "name", decision_type_name)
__decision_type.push()
return __decision_type
def judgement_type(self, judgement_type_name):
__judgement_type = self.graph.merge_one("Court_Judgement_Type", "name", judgement_type_name)
__judgement_type.push()
return __judgement_type
def case(self, court_case, region_name):
__case = self.graph.merge_one("Case", "id", court_case.decision_number)
__case["reg_date"] = __timestamp__(court_case.reg_date)
__case["law_date"] = __timestamp__(court_case.law_date)
__case["link"] = court_case.link
__case["text"] = court_case.text
__case["case_number"] = court_case.case_number
self.graph.create_unique(Relationship(__case, "RULED_BY", self.court(court_case.court_name, region_name)))
self.graph.create_unique(Relationship(__case, "CARRIED_BY", self.chairman(court_case.chairman)))
self.graph.create_unique(Relationship(__case, "OF_JUDGEMENT_TYPE", self.judgement_type(court_case.vr_type)))
self.graph.create_unique(Relationship(__case, "OF_DECISION_TYPE", self.decision_type(court_case.cs_type)))
__case.push()
return __case
def change_date(self):
query = "MATCH (n:Case) WHERE NOT (n.law_date='') RETURN n LIMIT 5"
id_list = []
for n in self.graph.cypher.execute(query):
id_list.append(n[0].__str__()[2:].split(':')[0]) # getting an id
for _id in id_list:
n = self.graph.node(str(_id))
n['law_date'] = __timestamp__(n['law_date'])
n.push()
print(n)
示例8: ApiProvider
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import node [as 别名]
class ApiProvider():
def __init__(self, request_data):
self._request_data = request_data
authenticate("localhost:7474", "neo4j", "1234")
# authenticate("52.27.227.159:7474", "neo4j", "1234")
self.graph = Graph(GRAPH_CONNECTION_STRNIG)
def _update_show(self, show_id):
# get the node from the graph
node_show = self.graph.node(show_id)
if node_show['updated'] == True:
return
result_dict = {}
try:
show_info_e_list = requests.get(
'http://services.tvrage.com/feeds/full_show_info.php?sid={0}'.format(node_show['id']))
result_dict = xmltodict.parse(show_info_e_list.text)
omdb_show_info = requests.get(
'http://www.omdbapi.com/?t={0}&y=&plot=full&r=json'.format(node_show['name']))
dict_omdb_show_info = json.loads(omdb_show_info.text)
if dict_omdb_show_info['Response'] == 'True':
for key, value in dict_omdb_show_info.iteritems():
node_show[key] = value
success = False
except ValueError as e:
logger.exception("Value Error")
return
except Exception as e:
logger.exception("Some network issue, will try again")
return
# add the new extracted data to the show
node_show['started'] = result_dict['Show'].get('started', None)
node_show['ended'] = result_dict['Show'].get('ended', None)
node_show['image'] = result_dict['Show'].get('image', None)
node_show['status'] = result_dict['Show'].get('status', None)
node_show.push()
# Country
from_country = result_dict['Show'].get('origin_country', 'unknown')
node_country = self.graph.merge_one("Country", 'country', from_country)
node_country.push()
# add the relation to the graph
show_from_country = Relationship(node_show, "from", node_country)
self.graph.create(show_from_country)
# Genres
if result_dict['Show'].get('genres', None) is not None:
genre_list = []
if type(result_dict['Show']['genres']['genre']) is list:
genre_list = result_dict['Show']['genres']['genre']
else:
genre_list.append(result_dict['Show']['genres']['genre'])
for genre in genre_list:
# create the genre node
node_genre = self.graph.merge_one("Genre", 'name', genre)
node_genre.push()
# add the Genre relation to the graph
show_of_genre = Relationship(node_show, "of genre", node_genre)
self.graph.create(show_of_genre)
# Seasons
season_list = []
if result_dict['Show'].get('Episodelist', None) is None:
return
if type(result_dict['Show']['Episodelist']['Season']) is list:
season_list = result_dict['Show']['Episodelist']['Season']
else:
season_list.append(result_dict['Show']['Episodelist']['Season'])
for season in season_list:
# create node for season
node_season = Node.cast('Season', {'no': season['@no']})
self.graph.create(node_season)
# create the relation n the graph
show_season = Relationship(node_show, "has", node_season)
self.graph.create(show_season)
# Episodes
episode_list = []
if type(season['episode']) is list:
episode_list = season['episode']
else:
episode_list.append(season['episode'])
count = 1
for episode in episode_list:
# create a node for episode
node_episode = Node.cast('Episode', {
'airdate': episode.get('airdate', None),
'epnum': count,
'screencap': episode.get('screencap', None),
'title': episode.get('title', None)
#.........这里部分代码省略.........