本文整理汇总了Python中neo4j.GraphDatabase.query方法的典型用法代码示例。如果您正苦于以下问题:Python GraphDatabase.query方法的具体用法?Python GraphDatabase.query怎么用?Python GraphDatabase.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类neo4j.GraphDatabase
的用法示例。
在下文中一共展示了GraphDatabase.query方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: showAllDB
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
def showAllDB():
db = GraphDatabase(workingdb)
query = """START n=node(*)
MATCH (n) - [r] -> (m)
RETURN n.name, r, m.name"""
print db.query(query)
db.shutdown()
示例2: showAllRelations
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
def showAllRelations(qname):
db = GraphDatabase(workingdb)
query = """START n=node(*)
MATCH (n) - [r] -> (m)
WHERE HAS(n.name) AND n.name = {name}
RETURN n.name, r, m.name"""
print db.query(query, name=qname)
db.shutdown()
示例3: showAllNodes
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
def showAllNodes():
# open the db
db = GraphDatabase(workingdb)
number_of_nodes = len(db.nodes)
query = "START n=node(*) RETURN n"
print "This db has " + str(number_of_nodes) +"nodes"
if(number_of_nodes>0):
print db.query(query)
else:
print "no nodes"
db.shutdown()
示例4: __init__
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
class SocialGraph:
def __init__(self, neo4j_url="graph.db"):
self.db = GraphDatabase(neo4j_url)
self.nodes = {}
self.rels = []
def file_to_db(self, data_path):
data = json_io.read_json(data_path)
with self.db.transaction:
for source_name, targets in data.iteritems():
if source_name in self.nodes:
source = self.nodes[source_name]
else:
source = self.db.node(name=source_name)
self.nodes[source_name] = source
for target_name in targets:
if target_name in self.nodes:
target = self.nodes[target_name]
else:
target = self.db.node(name=target_name)
self.nodes[target_name] = target
#for attr, val in targets[target_name].iteritems():
self.rels.append(source.knows(target))
return self.nodes
def load_pattern(self, dir_file, clip_file):
self.dir_patterns = json_io.read_json(dir_file)
self.clip_patterns = json_io.read_json(clip_file)
def has_relationship(self, source_name, target_name):
source = self.nodes[source_name]
target = self.nodes[target_name]
query = '''start source=node({s_id}) \
match (source)-[r]->(target) \
where target.name = {t_name} return r'''
number_rel = self.db.query(query, s_id=source.id, t_name=target_name)['r']
if len(number_rel) > 1:
return True
else:
return False
def pattern_matching(self, source_name, target_name, keyword):
source = self.nodes[source_name]
target = self.nodes[target_name]
result = self.dir_query(source, target_name)
if result == keyword:
return True
elif result:
return result
elif result == False:
return False
result = self.dir_query(target, source_name)
if result == keyword:
return True
elif result:
return result
elif result == False:
return False
result = self.clip_query(source, target_name)
if result == keyword:
return True
elif result:
return result
elif result == False:
return False
return True
def dir_query(self, source, target_name):
dir_query = '''START source=node({s_id}) \
MATCH (source)-[r1]->(middleman)-[r2]->(target) \
WHERE target.name = {t_name} RETURN r1, r2'''
results = self.db.query(dir_query, s_id=source.id, t_name=target_name)
for result in results:
if 'rel' in result['r1'].keys() and \
'rel' in result['r2'].keys():
relationship1 = result['r1']['rel']
relationship2 = result['r2']['rel']
if relationship2 in self.dir_patterns[relationship1]:
predict_rel = self.dir_patterns[relationship1][relationship2]
else:
return False
return predict_rel
return None
def clip_query(self, source, target_name):
dir_query = '''START source=node({s_id}) \
MATCH (source)-[r1]->(middleman)<-[r2]-(target) \
WHERE target.name = {t_name} RETURN r1, r2'''
#.........这里部分代码省略.........
示例5: Memory
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
#.........这里部分代码省略.........
self.vars["me"] = [rel for rel in self.vars["objectroot"].ISA.incoming if rel["type"]=="me" ][0].start
self.vars["master"] = [rel for rel in self.vars["objectroot"].ISA.incoming if rel["type"]=="master" ][0].start
def initialGraph(self,create=False):
if create:
self.log("create Graph ...")
with self.db.transaction:
self.vars["root"] = self.db.node[0]
self.vars["root"]['name'] = 'ROOT'
self.nameIndex = self.db.node.indexes.create('name')
self.indexName(self.vars["root"])
self.messageIndex = self.db.node.indexes.create('message',type='fulltext')
else:
self.log("initial graph...")
with self.db.transaction:
self.vars["root"] = self.db.node[0]
self.nameIndex = self.db.node.indexes.get('name')
self.messageIndex = self.db.node.indexes.get('message')
self.initialTime(create)
self.initialPlace(create)
self.initialObjects(create)
def getNodes(self,str):
if str.startswith("`") and str.endswith("`"):
result = []
for id in str[1:-1].split(","):
result.append(self.db.node[int(id)])
if len(result)==1:
return result[0]
if len(result)>1:
return result
return str
def cypher(self,query):
return self.db.query(query)
def findNodeById(self,id):
return self.db.nodes[id]
def indexName(self,obj):
try:
del self.nameIndex['name'][obj['name']][obj]
except: pass
self.nameIndex['name'][obj['name']] = obj
def createNode(self,name=None):
with self.db.transaction:
if name == None:
node = self.db.node()
else:
node = self.db.node(name=name)
self.indexName(node)
return node
def createNodeOFType(self, typename=None, prop={}):
with self.mind.memory.db.transaction:
name = None
if "name" in prop.keys():
name = prop["name"]
node = self.createNode(name)
self.setNodeProperties(node,prop)
if typename is not None:
typevar = self.objectType(typename)
node.IS(typevar)
return node
示例6: GraphDatabase
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
import os,jpype,time,random, cPickle
os.environ['NEO4J_PYTHON_JVMARGS'] = '-Xms4G -Xmx8G -XX:MaxPermSize=1G'
os.environ['JAVA_HOME']='/usr/lib/jvm/jdk1.7.0/'
from neo4j import GraphDatabase
db = GraphDatabase('data')
print 'deleting'
with db.transaction:
db.query('start r=relationship(*) delete r');
db.query('start n=node(*) delete n;')
print 'reading'
friends = cPickle.load(open('friends.pickle'))
print 'nodes'
nodes = {}
with db.transaction:
for a,data in friends.items():
n = db.node(noscenda_name='person%s'%a)
nodes[a]=n
if a%1000==0:
print 'n ',a
i= 0
print 'relations'
with db.transaction:
for a,targets in friends.items():
for b in targets:
i+=1
getattr(nodes[a],'friend')(nodes[b])
if i%1000==0:
示例7: get_user
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
return user
#根据用户名获得用户节点
def get_user(name):
return user_idx['name'][name].single
#建立节点
for name in ['user1', 'user2','user3','user4']:
create_user(name)
#为节点间添加关注关系(FOLLOWS)
with db.transaction:
get_user('user2').FOLLOWS(get_user('user1'))
get_user('user3').FOLLOWS(get_user('user1'))
get_user('user4').FOLLOWS(get_user('user3'))
# 获得用户1的粉丝
for relationship in get_user('user1').FOLLOWS.incoming:
u = relationship.start
print u['name']
#输出结果:user2,user3
#为用户4推荐好友,即该用户关注的用户所关注的用户
nid = get_user('user4').id
#设置查询语句
query = "START n=node({id}) MATCH n-[:FOLLOWS]->m-[:FOLLOWS]->fof RETURN n,m,fof"
for row in db.query(query,id=nid):
node = row['fof']
print node['name']
#输出结果:user1
示例8: GraphDatabase
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import query [as 别名]
#script for excecuting a cypher query with embedded python
from neo4j import GraphDatabase
import traceback
import time
import redis
r = redis.StrictRedis(host='46.137.39.99', port=6379, db=0)
cypherRedisKey = r.get("cypherQueries")
db = GraphDatabase("/mnt/neo4py_store/data/graph.db")
try:
cypher_query = ""
while cypher_query is not None:
print "query found"
cypher_query = r.rpop(cypherRedisKey)
if cypher_query is not None:
db.query(cypher_query)
print "sleeping..."
time.sleep(10)
except Exception, e:
logfile = open('./pythonError.log', 'a')
logfile.write("\n"+e.message())
logfile.close()
db.shutdown()