本文整理汇总了Python中neo4j.v1.GraphDatabase类的典型用法代码示例。如果您正苦于以下问题:Python GraphDatabase类的具体用法?Python GraphDatabase怎么用?Python GraphDatabase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GraphDatabase类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
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()
开发者ID:rlinkul,项目名称:cycli,代码行数:12,代码来源:driver.py
示例2: connect
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)
开发者ID:TwoBitAlchemist,项目名称:NeoAlchemy,代码行数:30,代码来源:graph.py
示例3: run_graph
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)
开发者ID:xiyangliu,项目名称:pydemo,代码行数:30,代码来源:__main__.py
示例4: main
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()
开发者ID:DanielMcFall,项目名称:pubmed-retraction-analysis,代码行数:33,代码来源:load.py
示例5: main
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)
开发者ID:pegerto,项目名称:t2n4j,代码行数:32,代码来源:insert.py
示例6: export_to_neo4j
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()
开发者ID:pitcons,项目名称:bme-parser,代码行数:25,代码来源:export_to_neo4j.py
示例7: test_construct_dwpc_query
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)
开发者ID:dhimmel,项目名称:hetio,代码行数:34,代码来源:neo4j_test.py
示例8: get_session
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
开发者ID:OC-NTNU,项目名称:baleen-python,代码行数:18,代码来源:n4j.py
示例9: __init__
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))
开发者ID:IPStreet,项目名称:Blogs,代码行数:10,代码来源:neo4j_writer.py
示例10: init_neo4j_connection
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
开发者ID:OC-NTNU,项目名称:MVL,代码行数:11,代码来源:mvl.py
示例11: server
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)
开发者ID:lambdafu,项目名称:minos,代码行数:11,代码来源:minos.py
示例12: __init__
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()
开发者ID:popart,项目名称:wikipath,代码行数:12,代码来源:neo4jconn.py
示例13: neo4j
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()
开发者ID:duffj,项目名称:neo4j-batch-executor,代码行数:13,代码来源:test_connection.py
示例14: __init__
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.")
开发者ID:L4in,项目名称:AMX_HIVE,代码行数:14,代码来源:neo4j_comm.py
示例15: __init__
def __init__(self, username = None, password = None, server = None):
if username == None or password == None:
username, password, server = self.loadAuthCredentials()
print(username, password, server)
uri = "bolt://{}:{}@{}".format(username, password, server)
print("Connecting to " + uri)
try:
self.conn = GraphDatabase.driver(uri, auth = (username, password))
self.session = self.conn.session()
except ServiceUnavailable as e:
raise Exception(str(e))
开发者ID:wacky-tracky,项目名称:wacky-tracky-server,代码行数:15,代码来源:wrapper.py
示例16: create_app
def create_app():
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = config['auth_secret']
app.config['JWT_BLACKLIST_ENABLED'] = False
app.config['JWT_BLACKLIST_STORE'] = simplekv.memory.DictStore()
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = 'all'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(minutes=15)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
driver = GraphDatabase.driver(config['database_url'], auth=basic_auth(config['database_user'],config['database_pass']))
db_session = driver.session()
# start jwt service
jwt = JWTManager(app)
# Import blueprints
from auth import auth_blueprint
from banner import banner_blueprint
from people import people_blueprint
from organizations import organizations_blueprint
from repos import repositories_blueprint
from schema import schema_blueprint
from data import data_blueprint
from search import search_blueprint
from upload import upload_blueprint
from export import export_blueprint
from list import list_blueprint
from .sockets import sockets as socket_blueprint
# register API modules
app.register_blueprint(banner_blueprint)
app.register_blueprint(auth_blueprint)
app.register_blueprint(people_blueprint)
app.register_blueprint(organizations_blueprint)
app.register_blueprint(repositories_blueprint)
app.register_blueprint(schema_blueprint)
app.register_blueprint(search_blueprint)
app.register_blueprint(data_blueprint)
app.register_blueprint(upload_blueprint)
app.register_blueprint(socket_blueprint)
app.register_blueprint(export_blueprint)
app.register_blueprint(list_blueprint)
x_socketio.init_app(app)
return app, jwt
开发者ID:inquisite,项目名称:Inquisite-Core,代码行数:47,代码来源:__init__.py
示例17: set_connection
def set_connection(self, url):
self.url = url
u = urlparse(url)
if u.netloc.find('@') > -1 and u.scheme == 'bolt':
credentials, hostname = u.netloc.rsplit('@', 1)
username, password, = credentials.split(':')
else:
raise ValueError("Expecting url format: bolt://user:[email protected]:7687"
" got {}".format(url))
self.driver = GraphDatabase.driver('bolt://' + hostname,
auth=basic_auth(username, password),
encrypted=config.ENCRYPTED_CONNECTION,
max_pool_size=config.MAX_POOL_SIZE)
self._pid = os.getpid()
self._active_transaction = None
开发者ID:pvanheus,项目名称:neomodel,代码行数:17,代码来源:util.py
示例18: __init__
def __init__(self, driver=None, uri=None,
user=None, password=None,
node_label="node",
edge_label="edge",
unique_node_ids=True):
"""Initialize Neo4jGraph object.
Parameters
----------
driver : neo4j.v1.direct.DirectDriver, optional
Driver providing connection to a Neo4j database
uri : str, optional
Uri for a new Neo4j database connection (bolt)
user : str, optional
Username for the Neo4j database connection
password : str, optional
Password for the Neo4j database connection
node_label : optional
Label of nodes inducing the subgraph to scope.
By default `"node"`.
edge_label : optional
Type of relations inducing the subgraph to scope.
By default `"edge"`.
unique_node_ids : bool, optional
Flag, if True the uniqueness constraint on the property
'id' of nodes is imposed, by default True
If database driver is provided, uses it for
connecting to database, otherwise creates
a new driver object using provided credentials.
"""
if driver is None:
self._driver = GraphDatabase.driver(
uri, auth=(user, password))
else:
self._driver = driver
self._node_label = node_label
self._edge_label = edge_label
self.unique_node_ids = unique_node_ids
if unique_node_ids:
try:
self.set_constraint('id')
except:
warnings.warn(
"Failed to create id uniqueness constraint")
开发者ID:Kappa-Dev,项目名称:ReGraph,代码行数:46,代码来源:graphs.py
示例19: __init__
def __init__(self, authfile, session_name):
self._authfile = authfile
self._session_name = session_name
self._num_variables = 0
self._num_landmarks = 50
self._pose_to_odometry_or_prior = {}
self._pose_to_measurements = {}
self._landmark_to_prior = {}
self._pose_ids = []
self._max_factor_id = 0
# initialize Neo4j session
self.username, self.password, self.DB_address = open(self._authfile).read().splitlines()
print self.username, self.password, self.DB_address
self.driver = GraphDatabase.driver(self.DB_address, auth=basic_auth(self.username, self.password))
self.session = self.driver.session()
self.session.run("MATCH (n:" + self._session_name + ") DETACH DELETE n")
开发者ID:dehann,项目名称:Caesar.jl,代码行数:17,代码来源:neo4j_interact_segments.py
示例20: __init__
def __init__(self, settings_file_name = None, working_directory = None):
super().__init__(settings_file_name, working_directory = working_directory)
# Read secret data file
secret_data_file_name = self.get_setting("secret_data_file_name")
with open(os.path.join(self.working_directory, os.path.normpath(secret_data_file_name)), "r") as file_:
fileData = file_.read()
secret_data = json.loads(fileData)
# Initialize the graph database
self._db = GraphDatabase.driver("bolt://localhost", auth=basic_auth(secret_data["neo4j_user_name"], secret_data["neo4j_password"]))
self.orion_ns = "http://www.orion-research.se/ontology#"
# Initialize proxies
self.authentication_proxy = self.create_proxy(self.get_setting("authentication_service"))
self.ontology = None
开发者ID:orion-research,项目名称:coach,代码行数:17,代码来源:KnowledgeRepositoryService.py
注:本文中的neo4j.v1.GraphDatabase类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论