本文整理汇总了Python中py2neo.Graph.find方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.find方法的具体用法?Python Graph.find怎么用?Python Graph.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类py2neo.Graph
的用法示例。
在下文中一共展示了Graph.find方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_track_comments
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
def get_track_comments():
track_comments = {}
graph = Graph()
for comment in graph.find("Comment"):
track_comments[comment.properties['id']] = inflate(comment.properties)
return track_comments
示例2: Neo4j
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
class Neo4j():
graph = None
def __init__(self):
print("create neo4j class ...")
def connectDB(self):
self.graph = Graph("http://localhost:7474", username="neo4j", password="8313178")
print('connect successed')
def matchItembyTitle(self,value):
answer = self.graph.find_one(label="Item",property_key="title",property_value=value)
return answer
# 根据title值返回互动百科item
def matchHudongItembyTitle(self,value):
answer = self.graph.find_one(label="HudongItem",property_key="title",property_value=value)
return answer
# 返回限定个数的互动百科item
def getAllHudongItem(self, limitnum):
List = []
ge = self.graph.find(label="HudongItem", limit=limitnum)
for g in ge:
List.append(HudongItem(g))
print('load AllHudongItem over ...')
return List
#test = Neo4j()
#test.connectDB()
#a = test.getLabeledHudongItem('labels.txt')
#print(a[10].openTypeList)
示例3: get_tracks
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
def get_tracks():
track_metadata = {}
graph = Graph()
for track in graph.find("Track"):
track_metadata[track.properties['id']] = inflate(track.properties)
return track_metadata
示例4: city
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
def city():
location = request.args['meetup_group']
graph = Graph(host=config['neo4j']['host'], user=config['neo4j']['user'],
password=config['neo4j']['password'])
logger.info('Finding upcoming meetup events in {}'.format(location))
groups_data = defaultdict()
groups = graph.find('Group')
for group in groups:
groups_data[group.properties['name']] = []
for rel in graph.match(start_node=group, rel_type="HAS EVENT"):
groups_data[group.properties['name']].append(rel.end_node().properties['time'])
return json.dumps(groups_data)
示例5:
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
for article_key, article_value in issue_attributes_value.items():
title = journal_structure["ACM"][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["title"]
abstract = journal_structure["ACM"][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["abstract"]
authors = journal_structure["ACM"][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["authors"]
doi = journal_structure["ACM"][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["doi"]
references = journal_structure["ACM"][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["references"]
citations = journal_structure["ACM"][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["citations"]
article_to_be_added = graph.merge_one("Article", "doi", doi)
article_to_be_added['abstract'] = abstract
article_to_be_added['authors'] = authors[0]["name"]
article_to_be_added['title'] = title
article_to_be_added['citations'] = []
article_to_be_added['references'] = []
if ( len(references) > 0 ) and ( len(citations) > 0 ) :
article_to_be_added['references'] = references
article_to_be_added['citations'] = citations
article_to_be_added.push()
#print(title)
relationship_to_be_added = graph.create_unique(Relationship(article_to_be_added, "printed_in", journal_to_be_added, volume=volume_key, issue=issue_key, issn=journal_structure["ACM"][journal_key][volume_key][issue_key]["issn"]))
primary_author_bool = True
for author in authors:
if primary_author_bool:
author_relationship_to_be_added = graph.create_unique(Relationship(article_to_be_added, "authored_by", graph.find('Author', 'full_name', author), primary_author="YES"))
primary_author_bool = False
else:
author_relationship_to_be_added = graph.create_unique(Relationship(article_to_be_added, "authored_by", graph.find('Author', 'full_name', author), primary_author="NO"))
示例6: main
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
def main():
graph = Graph()
graph.cypher.execute("CREATE CONSTRAINT ON (user:User) ASSERT user.username IS UNIQUE" )
graph.cypher.execute("CREATE CONSTRAINT ON (job:Job) ASSERT job.title IS UNIQUE" )
graph.cypher.execute("CREATE CONSTRAINT ON (city:City) ASSERT city.name IS UNIQUE" )
userFile = open("users.csv", "r")
userFile.readline()
lineNumber = 0
for line in userFile.readlines():
print("\r Processing line " + str(lineNumber), end="")
lineNumber += 1
parsedLine = line.split(",")
user = Node("User", username=parsedLine[0],
name=parsedLine[1],
biography=parsedLine[4],
password=bcrypt.encrypt("password"))
graph.create(user)
city = graph.merge_one("City", "name", parsedLine[2])
job = graph.merge_one("Job", "title", parsedLine[3])
livesIn = Relationship(user, "IS_FROM", city)
hasJob = Relationship(user, "HAS_JOB_TITLE", job)
graph.create(livesIn)
graph.create(hasJob)
result = graph.cypher.execute("MATCH (beer:Beer) "
" RETURN beer, rand() as rand "
" ORDER BY rand"
" LIMIT {range}", range=random.randrange(100,600))
for beer in result:
beerNode = graph.find_one("Beer", "breweryDbId", beer.beer["breweryDbId"])
likesBrewery = Relationship(user, "LIKES", beerNode)
graph.create(likesBrewery)
result = graph.cypher.execute("MATCH (brewery:Brewery) "
" RETURN brewery, rand() as rand "
" ORDER BY rand"
" LIMIT {range}", range=random.randrange(0,10))
for brewery in result:
breweryNode = graph.find_one("Brewery", "breweryDbId", brewery.brewery["breweryDbId"])
likesBrewery = Relationship(user, "LIKES", breweryNode)
graph.create(likesBrewery)
if lineNumber > 300:
break
for user in graph.find("User"):
userNode = graph.find_one("User", "username", user["username"])
result = graph.cypher.execute("MATCH (user:User) "
"WHERE user.username <> {me}"
" RETURN user, rand() as rand "
" ORDER BY rand"
" LIMIT {range}", me=userNode["username"], range=random.randrange(5,40))
for person in result:
dude = graph.find_one("User", "username", person.user["username"])
buddiesWith = Relationship(userNode, "FOLLOWS", dude)
graph.create(buddiesWith)
示例7: print
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
# graph.run(CREATE (Song2-[:Key]->Node2))
# graph.run(CREATE (Song3-[:Key]->Node1))
graph.create(Rel1)
graph.create(Rel2)
graph.create(Rel3)
graph.create(Rel4)
graph.create(Rel5)
graph.create(Rel6)
graph.create(Rel7)
graph.create(Rel8)
graph.create(Rel9)
graph.create(Rel10)
graph.create(Rel11)
graph.create(Rel12)
results = graph.find("Word","Name","baby")
for result in results:
print(result)
#
# MATCH (pee1)-[:Key]->(n:Word {Name:"baby"})<-[:Key]-(pee2) WHERE pee1<>pee2 RETURN pee1,pee2,n
# FOREACH(p1 in pee1 |
# FOREACH (p2 in pee2 |
# MATCH (p1)-[:Key]->(n:Word)<-[:Key]-(p2) WHERE p1<>p2)) RETURN p1,p2,n
#
# FOREACH(country in cou |
# FOREACH (c in ch |
# FOREACH (a in addresses |
# CREATE (s:Store {name:c.name+"_"+a, address:a})
# CREATE (s-[:BELONGS_TO]->c)
# CREATE (s-[:IN]->country) )))
示例8: __init__
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
class GraphExporter:
def __init__(self):
authenticate(neo4j.HOST_PORT, neo4j.USERNAME, neo4j.PASSWORD)
self.neo4j_db = Graph(neo4j.REMOTE_URI)
def create_taikonetwork_graph(self):
print("> Taiko Network Graph: querying all nodes and relationships...")
self.graph = nx.Graph()
self._add_group_nodes()
self._add_memberships()
self._add_member_nodes()
self._add_unique_connections()
print("> Taiko Network Graph: SUCCESSFULLY CREATED!\n"
"> Export to graph file format to save.\n")
def create_demographic_graph(self):
print("> Demographic Graph: querying all Member nodes and Connection rels...")
self.graph = nx.Graph()
self._add_member_nodes(demo=True)
self._add_unique_connections(demo=True)
print("> Demographic Graph: SUCCESSFULLY CREATED!\n"
"> Export to graph file format to save.\n")
def export_gexf_graph(self, filepath='graph.gexf'):
nx.write_gexf(self.graph, filepath,
encoding='utf-8', prettyprint=True, version='1.2draft')
def _add_group_nodes(self):
groups = self.neo4j_db.find('Group')
color = {'r': 255, 'g': 2, 'b': 97, 'a': 1}
for g in groups:
data = g.properties
self.graph.add_node(
g._id, label=data['name'], sf_id=data['sf_id'],
viz={'color': color})
def _add_member_nodes(self, demo=False):
members = self.neo4j_db.find('Member')
for m in members:
data = m.properties
color = self._random_color(m._id, 1)
if demo:
self.graph.add_node(
m._id, label=data['firstname'] + ' ' + data['lastname'],
gender=data['gender'], dob=data['dob'],
race=data['race'], ethnicity=data['asian_ethnicity'],
viz={'color': color})
else:
self.graph.add_node(
m._id, label=data['firstname'] + ' ' + data['lastname'],
sf_id=data['sf_id'],
viz={'color': color})
def _add_unique_connections(self, demo=False):
connections = self.neo4j_db.match(rel_type='CONNECTED_TO')
unique_rels = []
for c in connections:
start = c.start_node._id
end = c.end_node._id
if (start, end) not in unique_rels and (end, start) not in unique_rels:
if demo:
color = {'r': 213, 'g': 213, 'b': 213, 'a': 0.3}
else:
color = self._random_color(start, 0.3)
self.graph.add_edge(start, end, viz={'color': color})
unique_rels.append((start, end))
def _add_memberships(self):
memberships = self.neo4j_db.match(rel_type='MEMBER_OF')
for ms in memberships:
color = self._random_color(ms.start_node._id, 0.3)
self.graph.add_edge(ms.start_node._id, ms.end_node._id,
viz={'color': color})
def _random_color(self, obj_id, alpha):
colors = [{'r': 164, 'g': 243, 'b': 121},
{'r': 243, 'g': 230, 'b': 121},
{'r': 243, 'g': 121, 'b': 184},
{'r': 154, 'g': 121, 'b': 243},
{'r': 202, 'g': 243, 'b': 121},
{'r': 243, 'g': 177, 'b': 121},
{'r': 243, 'g': 121, 'b': 238},
{'r': 121, 'g': 243, 'b': 212},
{'r': 243, 'g': 190, 'b': 121},
{'r': 121, 'g': 194, 'b': 243},
{'r': 157, 'g': 2, 'b': 253},
{'r': 2, 'g': 86, 'b': 253}]
c = colors[obj_id % 12]
c['a'] = alpha
return c
示例9: print
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
for row in bsm.rows[1:]:
from_type, from_name, edge_type, edge_name, to_type, to_name, netlog = [cell.value for cell in row]
if netlog is None:
from_type = "grey"
to_type = "grey"
print(from_type, from_name, edge_type, to_type, to_name)
from_node = graph.merge_one(from_type.strip(), "name", from_name.strip())
to_node = graph.merge_one(to_type.strip(), "name", to_name.strip())
from_to = Relationship(from_node, edge_type, to_node)
graph.create_unique(from_to)
# get nodes with degree
nodes = []
for label in graph.node_labels:
for p in graph.find(label):
node = {"id": p.ref.split("/")[-1],
"label": p["name"],
"title": p["name"],
"value": p.degree,
"group": label}
nodes.append(node)
with open("report/nodesnetlog.js", "w") as f:
f.write("var nodesraw = " + dumps(nodes, indent=2) + ";")
# get edges
edges = []
for r in graph.match():
edge = {"to": r.end_node.ref.split("/")[-1],
"from": r.start_node.ref.split("/")[-1]
}
示例10: Title
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
con = sqlite3.connect('../db/search_title.db')
cur = con.cursor()
cur.execute("CREATE TABLE Title (title TEXT, item_id INT, poster_path TEXT, year INT)")
cur.execute("CREATE INDEX title_index ON Title (title)")
def get_new_id():
query = """MERGE (nid:ItemIncremental)
ON CREATE SET nid.count = 1
ON MATCH SET nid.count = nid.count + 1
RETURN nid.count"""
new_id = graph.cypher.execute(query)[0][0]
return new_id
# graph = Graph()
genres = graph.find('Genre')
genre_dict = {}
for genre in genres:
genre_dict[genre.properties['name']] = genre
with con:
with open (titles_file, 'r') as f_in:
counter = 0
more_than_one = 0
no_genre_counter = 0
for line in f_in:
try:
obj = json.loads(line)
except:
obj = ast.literal_eval(line)
示例11: Graph
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
from __future__ import print_function
from py2neo import Graph, Node, Relationship
graph_db = Graph()
person = Node("Person", name="JUHASZ Lilla Linda")
for record in graph_db.cypher.execute("Match (n) return n"):
print(record)
new_person = Node("Person", name="JUHASZ Peter", born=1930)
print("exists: " + str(list(graph_db.find("Person", property_key="name", property_value="JUHASZ Peter"))))
new_person.bind(graph_db.uri)
print("exists: " + str(new_person.exists))
father = graph_db.find_one("Person", property_key='name', property_value="JUHASZ Peter")
child = graph_db.find_one("Person", property_key='name', property_value="JUHASZ Lilla Linda")
child_of_rel = "CHILD_OF"
father_daughter_relationship = Relationship(child, child_of_rel, father)
graph_db.create(father_daughter_relationship)
示例12: authenticate
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
from py2neo import authenticate, Graph, Node, Relationship
from passlib.hash import bcrypt
import os
authenticate("localhost:7474", "neo4j", "shanghai")
#graph = Graph(os.environ.get('GRAPHENEDB_URL', 'http://localhost:7474') + '/db/data/')
graph = Graph("http://localhost:7474/db/data/")
"""
py2neo API
graph.find() ; graph.match()
> RETURNS generator
> elem in generator: Node or Relationship
graph.execute() > RETURNS RecordList
> elem in RecordList: Record
> elem[0]: Node
graph.find(label, property_key=None, property_value=None, limit=None)
graph.find_one(label, property_key=None, property_value=None)
"""
class Person:
"""
- id (UNIQUE CONSTRAINT)
示例13: test_pipeline
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
class test_pipeline(unittest.TestCase):
LEN_DATETIME = 26
LEN_TEST_FILE = 632
def setUp(self):
try:
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
self.src = open(
os.path.join(__location__, "data/bit-test-data.txt"))
self.badFreq = open(
os.path.join(__location__, "data/bad-frequency.txt"))
self.badStartTime = open(
os.path.join(__location__, "data/bad-starttime.txt"))
self.graph = Graph("http://localhost:8484/db/data")
self.graph.delete_all()
self.service = WaferService(self.graph)
except:
print "Error during unittest setup"
def tearDown(self):
self.graph.delete_all()
#
# File tests
#
def test_open(self):
self.assertEquals(len(self.src.read().split("\n")), 20)
#
# Parser tests
#
def test_parser(self):
bitdo = parser.BITdo(self.src)
self.assertEquals(len(bitdo.toJson()), test_pipeline.LEN_TEST_FILE)
self.assertEquals(len(bitdo.channels.keys()), 5)
self.assertEquals(bitdo.header["SamplingFrequency"], "1000")
self.assertEquals(len(bitdo.channels["EMG"]), 16)
# Assure that datetime is to microsecond precision
self.assertEquals(
len(bitdo.header["StartDateTime"]), test_pipeline.LEN_DATETIME)
def test_parser_errors(self):
self.assertRaises(AttributeError, parser.BITdo, (self.badFreq))
self.assertRaises(AttributeError, parser.BITdo, (self.badStartTime))
#
# Aggregator tests
#
def test_aggregator_nums(self):
a = [0, 0, 1, 1, 1]
s = aggregator.streaksIn(a)
self.assertEquals(s[0].getStreaks(), [2])
self.assertEquals(s[0].getStreakExp(2), [4])
self.assertEquals(s[1].getStreaks(), [3])
self.assertEquals(s[1].getStreakExp(2), [9])
def test_aggregator_bools(self):
b = [True, False, False, True, False]
s = aggregator.streaksIn(b)
self.assertEquals(s[True].getStreaks(), [1, 1])
self.assertEquals(s[False].getStreaks(), [2, 1])
self.assertEquals(s[False].getStreakExp(2), [4, 1])
def test_aggregator_strings(self):
c = ["cat", "826", "826", "826", "~~", "~~", "cat", "cat", "~~"]
s = aggregator.streaksIn(c)
self.assertEquals(s["cat"].getStreaks(), [1, 2])
self.assertEquals(s["cat"].getStreakExp(2), [1, 4])
self.assertEquals(s["826"].getStreaks(), [3])
self.assertEquals(s["826"].getStreakExp(3), [27])
self.assertEquals(s["~~"].getStreaks(), [2, 1])
self.assertEquals(s["~~"].getStreakExp(-1), [0.5, 1])
def test_aggregator_average(self):
bitdo = parser.BITdo(self.src)
self.assertEquals(aggregator.average(bitdo.channels['EMG']), 525.4375)
self.assertEquals(aggregator.average([1, 2, 3]), 2)
self.assertEquals(aggregator.average([x for x in range(1000)]), 499.5)
#
# Graph Service
#
def test_add_new_user(self):
user = self.service.add_user("Duke")
userid = user.properties["userid"]
activity = self.service.add_activity(
userid, "Free Throws", "no description")
activityname = activity.properties["name"]
self.service.add_moment(
userid, activityname, "timestamp", ["a1:true", "a2:false"])
self.service.add_moment(
userid, activityname, "timestamp", ["a1:true", "a2:false"])
self.assertEquals(count(self.graph.find("User")), 1)
self.assertEquals(count(self.graph.find("Activity")), 1)
self.assertEquals(count(self.graph.find("Moment")), 2)
#.........这里部分代码省略.........
示例14: authenticate
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
from py2neo import Graph,authenticate,Node,Relationship
import MySQLdb
import threading
authenticate("localhost:7474","neo4j","8760neo4j")
graph = Graph()
mynode = list(graph.find('fw', property_key='count'))
ct=1
fobj = open("textdump1.txt","r").readlines()
file_tacker=open("tarcker.txt","a")
#for i in fobj:
def indexing(i):
global ct
print "*********"
print i
print ct
print "**********"
i = i.lower()
file_tacker.write(str(i))
temp = i.split(" ",3)
b=""
for i in temp:
b=b+"".join(" "+str(i).replace("'",""))
b=b.strip()
s=b.split(" ",3)
dic={}
for i in range(len(s)):
n2=graph.cypher.execute("""MATCH (a: `%s`) where a.auto_name = '%s' return a"""%(str(s[i][0]),str(s[i])))
示例15: print
# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import find [as 别名]
title = acm_structure[publisher_key][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["title"]
abstract = acm_structure[publisher_key][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["abstract"]
authors = acm_structure[publisher_key][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["authors"]
doi = acm_structure[publisher_key][journal_key][volume_key][issue_key][issue_attributes_key][article_key]["doi"]
article_to_be_added = graph.merge_one("Article", "doi", doi)
article_to_be_added['abstract'] = abstract
# article_to_be_added['authors'] = authors
article_to_be_added['title'] = title
article_to_be_added.push()
print("\t\t\t" + title)
relationship_to_be_added = graph.create_unique(Relationship(article_to_be_added, "printed_in", journal_to_be_added, volume=volume_key, issue=issue_key, issue_date=str(acm_structure[publisher_key][journal_key][volume_key][issue_key]["date"]["month"])+str(acm_structure[publisher_key][journal_key][volume_key][issue_key]["date"]["year"]), issn=acm_structure[publisher_key][journal_key][volume_key][issue_key]["issn"]))
# primary_author_bool = True
for author in authors:
# print("Author detected is: " + author["name"])
# print("Author_link detected is: " + author["link"])
results = graph.find('Author', 'link', author["link"])
# print(type(results))
if len(list(results)) == 1:
for result in results:
print("\t\t\t\t" + result['full_name'] + " FOUND")
else:
# print("\t\t\t\tNOT FOUND! Creating Author...")
author_to_be_added = graph.merge_one("Author", "link", author["link"])
author_str_split_list = author["name"].split()
if (len(author_str_split_list) == 1):
author_to_be_added['full_name'] = author["name"].title()
author_to_be_added['fist_name'] = author_str_split_list[0]
author_to_be_added['middle_name'] = " "
author_to_be_added['last_name'] = " "
elif (len(author_str_split_list) == 2):
author_to_be_added['full_name'] = author["name"].title()