本文整理汇总了Python中neo4j.v1.GraphDatabase.driver方法的典型用法代码示例。如果您正苦于以下问题:Python GraphDatabase.driver方法的具体用法?Python GraphDatabase.driver怎么用?Python GraphDatabase.driver使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类neo4j.v1.GraphDatabase
的用法示例。
在下文中一共展示了GraphDatabase.driver方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def __init__(self, host, port, username=None, password=None, ssl=False, timeout=None):
port = "7687" if port is None else port
bolt_uri = "bolt://{host}".format(host=host, port=port)
self.http_uri = "http://{host}:{port}/db/data/".format(host=host, port=port)
if username and password:
driver = GraphDatabase.driver(bolt_uri, auth=basic_auth(username, password), encrypted=False)
else:
driver = GraphDatabase.driver(bolt_uri, encrypted=False)
self.session = driver.session()
示例2: connect
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def connect(self, url=None, user=None, password=None, **kw):
"""
Parse a Neo4J URL and attempt to connect using Bolt
Note: If the user and password arguments are provided, they
will only be used in case no auth information is provided as
part of the connection URL.
"""
if url is None:
url = 'bolt://localhost'
if user is None:
user = 'neo4j'
if password is None:
password = 'neo4j'
try:
protocol, url = url.split('://')
if protocol.lower() != 'bolt':
warnings.warn('Switching protocols. Only Bolt is supported.')
except ValueError:
pass
try:
credentials, url = url.split('@')
except ValueError:
kw['auth'] = basic_auth(user, password)
else:
kw['auth'] = basic_auth(*credentials.split(':', 1))
self.driver = GraphDatabase.driver('bolt://%s' % url, **kw)
示例3: run_graph
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def run_graph(neo4j_conf, args):
opts, args = getopt.getopt(args, "rcsa", ["related", "cluster", "similar", "all"])
if len(args) < 1:
raise getopt.GetoptError("Invalid graph arguments")
query = args[0]
stmt = ''
for o, v in opts:
if o in ["-r", "--related"]:
stmt = ('match (q:Query)<-[r:RELATED]-(a:Query) where q.query={query}'
'return a.query, r.norm_weight order by r.norm_weight desc')
elif o in ["-c", "--cluster"]:
stmt = ('match (q:Query)<-[r:CLUSTER_REP]-(a:Query) where q.query={query}'
'return r.rank, a.query, r.query_terms order by r.rank')
elif o in ["-s", "--similar"]:
stmt = ('match (q:Query)-[r:SIMILAR]-(a:Query) where q.query={query}'
'return a.query, r.score order by r.score desc')
elif o in ["-a", "--all"]:
stmt = ('match (q:Query)<-[r]-() where q.query={query}'
'return q.query, type(r) as rel_type, count(r) as rel_count')
if not stmt:
raise getopt.GetoptError("Invalid graph arguments")
graph = GraphDatabase.driver(neo4j_conf.uri, auth=basic_auth(neo4j_conf.username, neo4j_conf.password))
session = graph.session()
rs = session.run(stmt, parameters={'query': query})
for r in rs:
pprint.pprint(r)
示例4: __new__
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def __new__(cls, *args, **kwargs):
"""
Return neo4j-driver ou neo4jrestclient object
"""
_auth = None
if kwargs and ('user' or 'password') in list(kwargs.keys()):
user = kwargs['user']
password = kwargs['password']
if 'bolt://' in cls._default_host:
_auth = basic_auth(user, password)
else:
_url = 'http://{0}:{1}@localhost:7474'.format(user, password)
cls.host = _url
if 'bolt://' in cls._default_host:
driver = Neo4j3.driver(cls._default_host)
if _auth:
driver.auth = _auth
cls._graph = Cypher(driver)
return cls._graph
elif cls.host is not None and type(cls.host) is str:
cls._graph = Neo4j2(cls.host)
return cls._graph
else:
cls._graph = Neo4j2(cls._default_host)
return cls._graph
示例5: main
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def main(argv=None):
"""Import all data in JSON file into Neo4j database."""
parser = argparse.ArgumentParser(description="Load articles into Neo4j")
parser.add_argument("file",
help="File to read",
type=str,
nargs="?",
metavar="FILE")
parser.add_argument("--no-execute",
action="store_true")
parse_result = parser.parse_args(argv or sys.argv[1:])
with open_or_default(parse_result.file, sys.stdin) as fileobj:
data = json.load(fileobj)
commands = list(commands_from_data(data))
if parse_result.no_execute:
sys.stdout.write(json.dumps(commands))
elif len(commands):
if all(var in os.environ for
var in ["DATABASE_URL", "DATABASE_PASS"]):
url = os.environ["DATABASE_URL"]
pwd = os.environ["DATABASE_PASS"]
usr = os.environ.get("DATABASE_USER", "")
else:
raise ValueError("Ensure environment variables DATABASE_URL, "
"DATABASE_PASS and DATABASE_USER set.")
driver = GraphDatabase.driver(url, auth=basic_auth(usr, pwd))
session = driver.session()
for command in commands:
session.run(command)
session.close()
示例6: main
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def main():
parser = argparse.ArgumentParser(description="""
Insert a Terraform state file into neo4j
""")
parser.add_argument('-d','--db', required=True, help="Neo4j host")
parser.add_argument('-u','--username', required=True, help="Neo4j user")
parser.add_argument('-p','--password', required=True, help="Neo4j password")
parser.add_argument('state_file', help="Terraform state file")
args = parser.parse_args()
print args
with open(args.state_file, 'r') as f:
state = json.load(f)
driver = GraphDatabase.driver("bolt://{}".format(args.db),
auth=basic_auth(args.username, args.password))
session = driver.session()
# Reduce all the modules and resouces to a single array of objects
resources = reduce( lambda a,b: a+b,
map(lambda m: m['resources'].values(),
state['modules']))
# Run actions for resources and capture hooks
hooks = set()
for resource in resources:
hooks.add(insert_item(resource, session))
# Run hooks
for hook in hooks:
if hook:
hook(session)
示例7: export_to_neo4j
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def export_to_neo4j():
driver = GraphDatabase.driver("bolt://localhost:7687",
encrypted=False,
auth=basic_auth("neo4j", "asdzxc"))
session = driver.session()
for article in db.Article.objects.all():
if article['links']:
# session.run("CREATE (a:Article {name: {name}})",
# {"name": article['title']})
for link in article['links']:
to_article = db.Article.objects.get(id=link)
print(to_article['title'])
session.run("CREATE (a:Article {name: {name}})",
{"name": article['title']})
#
# result = session.run("MATCH (a:Person) WHERE a.name = {name} "
# "RETURN a.name AS name, a.title AS title",
# {"name": "Arthur"})
# for record in result:
# print("%s %s" % (record["title"], record["name"]))
#
session.close()
示例8: test_construct_dwpc_query
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def test_construct_dwpc_query():
"""
Test dwpc query construction and computation on the metapath from
https://doi.org/10.1371/journal.pcbi.1004259.g002
"""
directory = pathlib.Path(__file__).parent.absolute()
path = directory.joinpath('data/hetionet-v1.0-metagraph.json')
metagraph = hetio.readwrite.read_metagraph(path)
compound = 'DB01156' # Bupropion
disease = 'DOID:0050742' # nicotine dependency
damping_exponent = 0.4
metapath = metagraph.metapath_from_abbrev('CbGpPWpGaD')
query = hetio.neo4j.construct_dwpc_query(metapath, property='identifier', unique_nodes=True)
assert len(query) > 0
driver = GraphDatabase.driver("bolt://neo4j.het.io")
params = {
'source': compound,
'target': disease,
'w': damping_exponent,
}
with driver.session() as session:
results = session.run(query, params)
results = results.single()
assert results
dwpc = results['DWPC']
assert dwpc == pytest.approx(0.03287590886921623)
示例9: get_session
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def get_session(warehouse_home, server_name, password=None,
encrypted=DEFAULT_ENCRYPTED,
silence_loggers=DEFAULT_SILENCE_LOGGERS):
if silence_loggers:
logging.getLogger('neo4j.bolt').setLevel(logging.WARNING)
server = neokit.Warehouse(warehouse_home).get(server_name)
address = server.config('dbms.connector.bolt.address', 'localhost:7687')
server_url = 'bolt://' + address
if password:
driver = GraphDatabase.driver(server_url, encrypted=encrypted,
auth=basic_auth(DEFAULT_USER, password))
else:
driver = GraphDatabase.driver(server_url, encrypted=encrypted)
session = driver.session()
return session
示例10: __init__
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def __init__(self):
config = configparser.ConfigParser()
config.read('config.ini')
user_name = config.get('neo4j credentials', 'user_name')
password = config.get('neo4j credentials', 'password')
bolt_host = config.get('neo4j credentials', 'bolt_host')
self.driver = GraphDatabase.driver(bolt_host,
auth=basic_auth(user_name, password))
示例11: init_neo4j_connection
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def init_neo4j_connection(app):
server_url = app.config.get('NEO4J_URL', 'bolt://localhost:7687')
encrypted = app.config.get('NEO4J_ENCRYPTED', True)
user = app.config.get('NEO4J_USER', 'neo4j')
password = app.config.get('NEO4J_PASSWORD')
auth = basic_auth(user, password) if password else None
driver = GraphDatabase.driver(server_url,
encrypted=encrypted,
auth=auth)
app.config['NEO4J_DRIVER'] = driver
示例12: server
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def server(ctx, host, port, debug):
from . server import app
config = ctx.obj.config
from neo4j.v1 import GraphDatabase, basic_auth
auth = basic_auth(config.neo4j.user, config.neo4j.password)
driver = GraphDatabase.driver(config.neo4j.address, auth=auth)
from attrdict import AttrDict
app.minos = AttrDict({ 'config': config, 'driver': driver })
app.run(host, port, debug)
示例13: __init__
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def __init__(self, **kwargs):
#super(Neo4JConn, self).__init__()
config = {
'host': kwargs['db_addr'],
'port': kwargs['db_port'],
'user': kwargs['username'],
'password': kwargs['password']
}
driver = GraphDatabase.driver(
"bolt://%s:%d" % (config['host'], config['port']),
auth=basic_auth(config['user'], config['password']))
self.__session = driver.session()
示例14: neo4j
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def neo4j():
from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7474", auth=basic_auth("neo4j", "neo4j"))
session = driver.session()
session.run("CREATE (a:Person {name:'Arthur', title:'King'})")
result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title")
for record in result:
print("%s %s" % (record["title"], record["name"]))
session.close()
示例15: __init__
# 需要导入模块: from neo4j.v1 import GraphDatabase [as 别名]
# 或者: from neo4j.v1.GraphDatabase import driver [as 别名]
def __init__(self, adress, user, password):
"""
Creates the session to the database
"""
self.driver = GraphDatabase.driver(adress, \
auth=basic_auth(user, password))
try:
self.session = self.driver.session()
except ProtocolError:
print("Cannot connect to neo4j. Aborting.")
exit()
print("Connected to neo4j.")