def test_must_use_valid_url_scheme(self): try: GraphDatabase.driver("x://xxx") except ValueError: assert True else: assert False
def test_can_run_simple_statement(self): session = GraphDatabase.driver("bolt://localhost").session() count = 0 for record in session.run("RETURN 1 AS n"): assert record[0] == 1 assert record["n"] == 1 try: record["x"] except AttributeError: assert True else: assert False assert record.n == 1 try: record.x except AttributeError: assert True else: assert False try: record[object()] except TypeError: assert True else: assert False assert repr(record) assert len(record) == 1 count += 1 session.close() assert count == 1
def __init__(self, options, columns): # Calling super constructor super(Neo4jForeignDataWrapper, self).__init__(options, columns) # Managed server option if 'url' not in options: log_to_postgres('The Bolt url parameter is required and the default is "bolt://localhost:7687"', WARNING) self.url = options.get("url", "bolt://localhost:7687") if 'user' not in options: log_to_postgres('The user parameter is required and the default is "neo4j"', ERROR) self.user = options.get("user", "neo4j") if 'password' not in options: log_to_postgres('The password parameter is required for Neo4j', ERROR) self.password = options.get("password", "") if 'cypher' not in options: log_to_postgres('The cypher parameter is required', ERROR) self.cypher = options.get("cypher", "MATCH (n) RETURN n LIMIT 100") # Setting table columns self.columns = columns # Create a neo4j driver instance self.driver = GraphDatabase.driver( self.url, auth=basic_auth(self.user, self.password)) self.columns_stat = self.compute_columns_stat() self.table_stat = int(options.get("estimated_rows", -1)) if(self.table_stat < 0): self.table_stat = self.compute_table_stat() log_to_postgres('Table estimated rows : ' + unicode(self.table_stat), DEBUG)
def test_can_run_statement_that_returns_multiple_records(self): session = GraphDatabase.driver("bolt://localhost").session() count = 0 for record in session.run("unwind(range(1, 10)) AS z RETURN z"): assert 1 <= record[0] <= 10 count += 1 session.close() assert count == 10
def test_can_handle_cypher_error(self): with GraphDatabase.driver("bolt://localhost").session() as session: try: session.run("X") except CypherError: assert True else: assert False
def test_fails_on_bad_syntax(self): session = GraphDatabase.driver("bolt://localhost").session() try: session.run("X").consume() except CypherError: assert True else: assert False
def test_can_obtain_summary_info(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("CREATE (n) RETURN n") summary = result.summarize() assert summary.statement == "CREATE (n) RETURN n" assert summary.parameters == {} assert summary.statement_type == "rw" assert summary.statistics.nodes_created == 1
def test_fails_on_missing_parameter(self): session = GraphDatabase.driver("bolt://localhost").session() try: session.run("RETURN {x}").consume() except CypherError: assert True else: assert False
def test_can_return_relationship(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("MERGE ()-[r:KNOWS {since:1999}]->() RETURN r") assert len(result) == 1 for record in result: rel = record[0] assert isinstance(rel, Relationship) assert rel.type == "KNOWS" assert rel.properties == {"since": 1999}
def test_can_return_node(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("MERGE (a:Person {name:'Alice'}) RETURN a") assert len(result) == 1 for record in result: alice = record[0] assert isinstance(alice, Node) assert alice.labels == {"Person"} assert alice.properties == {"name": "Alice"}
def test_can_obtain_plan_info(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("EXPLAIN CREATE (n) RETURN n") plan = result.summarize().plan assert plan.operator_type == "ProduceResults" assert plan.identifiers == ["n"] assert plan.arguments == {"planner": "COST", "EstimatedRows": 1.0, "version": "CYPHER 3.0", "KeyNames": "n", "runtime-impl": "INTERPRETED", "planner-impl": "IDP", "runtime": "INTERPRETED"} assert len(plan.children) == 1
def test_can_return_path(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("MERGE p=({name:'Alice'})-[:KNOWS]->({name:'Bob'}) RETURN p") assert len(result) == 1 for record in result: path = record[0] assert isinstance(path, Path) assert path.start.properties == {"name": "Alice"} assert path.end.properties == {"name": "Bob"} assert path.relationships[0].type == "KNOWS" assert len(path.nodes) == 2 assert len(path.relationships) == 1
def test_can_run_simple_statement_from_bytes_string(self): session = GraphDatabase.driver("bolt://localhost").session() count = 0 for record in session.run(b"RETURN 1 AS n"): assert record[0] == 1 assert record["n"] == 1 assert record.n == 1 assert repr(record) assert len(record) == 1 count += 1 session.close() assert count == 1
def test_can_obtain_profile_info(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("PROFILE CREATE (n) RETURN n") profile = result.summarize().profile assert profile.db_hits == 0 assert profile.rows == 1 assert profile.operator_type == "ProduceResults" assert profile.identifiers == ["n"] assert profile.arguments == {"planner": "COST", "EstimatedRows": 1.0, "version": "CYPHER 3.0", "KeyNames": "n", "runtime-impl": "INTERPRETED", "planner-impl": "IDP", "runtime": "INTERPRETED", "Rows": 1, "DbHits": 0} assert len(profile.children) == 1
def test_can_rollback_transaction_using_with_block(self): with GraphDatabase.driver("bolt://localhost").session() as session: with session.new_transaction() as tx: # Create a node result = tx.run("CREATE (a) RETURN id(a)") node_id = result[0][0] assert isinstance(node_id, int) # Update a property tx.run("MATCH (a) WHERE id(a) = {n} " "SET a.foo = {foo}", {"n": node_id, "foo": "bar"}) # Check the property value result = session.run("MATCH (a) WHERE id(a) = {n} " "RETURN a.foo", {"n": node_id}) assert len(result) == 0
def test_can_run_simple_statement(self): session = GraphDatabase.driver("bolt://localhost").session() count = 0 for record in session.run("RETURN 1 AS n"): assert record[0] == 1 assert record["n"] == 1 with self.assertRaises(AttributeError): _ = record["x"] assert record.n == 1 with self.assertRaises(AttributeError): _ = record.x with self.assertRaises(TypeError): _ = record[object()] assert repr(record) assert len(record) == 1 count += 1 session.close() assert count == 1
def test_can_commit_transaction(self): with GraphDatabase.driver("bolt://localhost").session() as session: tx = session.new_transaction() # Create a node result = tx.run("CREATE (a) RETURN id(a)") node_id = result[0][0] assert isinstance(node_id, int) # Update a property tx.run("MATCH (a) WHERE id(a) = {n} " "SET a.foo = {foo}", {"n": node_id, "foo": "bar"}) tx.commit() # Check the property value result = session.run("MATCH (a) WHERE id(a) = {n} " "RETURN a.foo", {"n": node_id}) foo = result[0][0] assert foo == "bar"
def test_can_obtain_notification_info(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("EXPLAIN MATCH (n), (m) RETURN n, m") notifications = result.summarize().notifications assert len(notifications) == 1 notification = notifications[0] assert notification.code == "Neo.ClientNotification.Statement.CartesianProduct" assert notification.title == "This query builds a cartesian product between disconnected patterns." assert notification.description == \ "If a part of a query contains multiple disconnected patterns, " \ "this will build a cartesian product between all those parts. " \ "This may produce a large amount of data and slow down query processing. " \ "While occasionally intended, it may often be possible to reformulate the query " \ "that avoids the use of this cross product, perhaps by adding a relationship between " \ "the different parts or by using OPTIONAL MATCH (identifier is: (m))" position = notification.position assert position.offset == 0 assert position.line == 1 assert position.column == 1
def __init__(self, **kwargs): """Initialize.""" super().__init__(**kwargs) self.url = f'bolt://{self.hostname}:{self.port}' self.driver = GraphDatabase.driver(self.url, auth=basic_auth(*self.auth))
def conectar(self): self.__driver = GraphDatabase.driver(self.__host, auth=(self.__usuario, self.__password)) self.__sesion = self.__driver.session()
def __init__(self, googleapi, bolt_url, neoUsername, neoPassword): self.gmaps = googlemaps.Client(key=googleapi) self.graph = GraphDatabase.driver(uri=bolt_url, auth=(neoUsername, neoPassword)) self.session = self.graph.session()
def loadFamilies(families): driver = GraphDatabase.driver("bolt://192.168.2.130:7687") with driver.session() as session: for family in families: result = session.write_transaction(addFamilyToGraph, family)
from neo4j import GraphDatabase ingredients = ["apple", "orange", "peach"] driver = GraphDatabase.driver(uri='bolt://localhost:11005', auth=("neo4j", "GlassGlobe101!")) session = driver.session() query_sample = '''MATCH (a { ingredientName: 'salt' })-[nn:INGREDIENT_IN]->(recipe) MATCH (k { ingredientName: 'sugar' })-[j:INGREDIENT_IN]->(recipe) MATCH (b { ingredientName: 'apple' })-[d:INGREDIENT_IN]->(recipe) MATCH (la { ingredientName: 'cranberry' })-[aa:INGREDIENT_IN]->(recipe) return recipe''' query = '' temp = 'a' temp2 = 'b' for i in ingredients: word = i.lower() query += 'MATCH (' + temp + ' { ingredientName: \'' + str( word) + '\' })-[' + temp2 + ':INGREDIENT_IN]->(recipe) ' temp += 'a' temp2 += 'b' query += ' return recipe' results = session.run(query) for result in results: print(result.data()['recipe']['name'], result.data()['recipe']['url'])
from neo4j import GraphDatabase uri = "bolt://localhost:7687" dri = GraphDatabase.driver(uri, auth=("dancer", "dancer")) with dri.session() as ses: ses.run("MATCH ()-[r]->() " "DELETE r") ses.run("MATCH (a) " "DELETE a") for i in range(6): ses.run("CREATE (a:Node {id:{id}, funds:1000, payout:{id}})", id=i) for i in range(10): ses.run("CREATE (a:Agent {id:{id}, funds:10, switch:0.5})", id=i) ses.run("CREATE (a:Clock {time:0})") ses.run("MATCH (a:Node), (b:Node) " "WHERE a.id=0 AND b.id=2 " "CREATE (a)-[r:REACHES {cost:5, outlook:b.id}]->(b)") ses.run("MATCH (a:Node), (b:Node) " "WHERE a.id=0 AND b.id=5 " "CREATE (a)-[r:REACHES {cost:5, outlook:b.id}]->(b)") ses.run("MATCH (a:Node), (b:Node) " "WHERE a.id=1 AND b.id=0 " "CREATE (a)-[r:REACHES {cost:5, outlook:b.id}]->(b)") ses.run("MATCH (a:Node), (b:Node) " "WHERE a.id=1 AND b.id=3 " "CREATE (a)-[r:REACHES {cost:5, outlook:b.id}]->(b)") ses.run("MATCH (a:Node), (b:Node) " "WHERE a.id=2 AND b.id=1 " "CREATE (a)-[r:REACHES {cost:5, outlook:b.id}]->(b)") ses.run("MATCH (a:Node), (b:Node) "
def test_can_handle_cypher_error(self): with GraphDatabase.driver("bolt://localhost").session() as session: with self.assertRaises(CypherError): session.run("X")
def test_no_notification_info(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("CREATE (n) RETURN n") notifications = result.summarize().notifications assert notifications == []
def test_can_use_with_to_auto_close_session(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("RETURN 1") assert len(result) == 1 for record in result: assert record[0] == 1
def test_no_plan_info(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("CREATE (n) RETURN n") assert result.summarize().plan is None assert result.summarize().profile is None
USERNAME = os.getenv('userName') PASSWORD = os.getenv('password') nodeStartedNonFreeChoice = [] nodeLeafNonFreeChoice = [] dataInArray = "" dataTestingInArray = "" dataTestingInArrayOneOfEachRow = [] dataLeafTestingEachNode = [] dataHeaderInArray = "" dataLeaf = [] dataCaseActivity = [] dataCaseId = "" endNode = "H" driver = GraphDatabase.driver(PORT, auth=(USERNAME, PASSWORD)) def deleteRelation(tx): tx.run("match p=()-[]-(), q=() delete p, q") def deletenNode(tx, nodeName): tx.run("match (c:"+nodeName+") delete c") def importActivity(tx, fileName): tx.run("LOAD CSV with headers FROM 'file:///"+fileName+"' AS line " "Merge (:Activity {CaseId:line.Case_ID, Name:line.Activity, Time:line.Time})") def importCaseActivity(tx, fileName): tx.run("LOAD CSV with headers FROM 'file:///"+fileName+"' AS line " "Merge (:CaseActivity {Name:line.Activity })")
def test_must_use_valid_url_scheme(self): with self.assertRaises(ValueError): GraphDatabase.driver("x://xxx")
logger.debug('[*] Arguments: ' + str(arguments)) if arguments.mode == 'h': operation = 'highvalue = true' elif arguments.mode == 'o': operation = 'owned = true' elif arguments.mode == 's': operation = 'hassigning = false' else: operation = arguments.operation logger.debug('[*] Operation: ' + operation) try: driver = GraphDatabase.driver(arguments.databaseUri, auth=(arguments.databaseUser, arguments.databasePassword)) logger.info('[*] Connected to BloodHound Neo4j database') except: logger.error('[-] Connection to BloodHound Neo4j database failed') exit() with driver.session() as session: for filePath in arguments.filePaths: with open(filePath) as file: logger.info('[*] Opened file: ' + filePath) for line in file: item = line.strip() logger.debug('[*] Current item: ' + item)
from xml.etree import ElementTree from neo4j import GraphDatabase, Node, Relationship, Path, CypherError import urllib2 from bs4 import BeautifulSoup session = GraphDatabase.driver("bolt://localhost").session() resultEMS = urllib2.urlopen('https://www.gocolumbiamo.com/PSJC/Services/911/911dispatch/fire_georss.php').read() treeEMS = ElementTree.fromstring(resultEMS) resultPolice = urllib2.urlopen('https://www.gocolumbiamo.com/PSJC/Services/911/911dispatch/police_georss.php').read() treePolice = BeautifulSoup(resultPolice) def getEmergencyType(truck): if truck[0] == "M": return "Medical" else: return "Fire" def getTruckType(truck): if truck[:2] == "SN": return "Snozzle" elif truck[0] == "S": return "Squad" elif truck[0] == "Q": return "Quint" elif truck[0] == "E": return "Engine" elif truck[0] == "L":
import json from vcd import core from vcd.core import ElementType from neo4j import GraphDatabase, basic_auth with open("../etc/neo4j.json") as config_file: config = json.load(config_file) host = config['host'] port = config['port'] user = config['user'] password = config['password'] # Connection with Neo4j: driver = GraphDatabase.driver('bolt://' + host + ":" + port, auth=basic_auth(user=user, password=password), encrypted=False) session = driver.session() class Neo4jScenarioDB: @staticmethod def clear_database(): """ Clear the database before reloading the ontology to delete the graph elements and removing existing constraints. """ with session: # If reload=True --> first delete database elements: session.run(""" MATCH (n) DETACH DELETE n """) @staticmethod def add_property(labels, node_identifier, identifier_value, properties):
app = Flask(__name__) redis = redis.Redis( host='localhost', port=6379 ) mongo = MongoClient( 'mongodb://localhost', port=27017, username='******', password='******' ) es = Elasticsearch( ['localhost'], port=9200 ) postgresConnect = psycopg2.connect( dbname='yourdatabasename', user='******', password='******', host='localhost', port=5432 ) neo = GraphDatabase.driver('bolt://localhost:7687', auth=('yourusername', 'yourpassword')) from app import routes
def loadPersons(persons): driver = GraphDatabase.driver("bolt://192.168.2.130:7687") with driver.session() as session: for person in persons: result = session.write_transaction(addIndividualToGraph, person)
def __init__(self): url, user, password = load_config() self.driver = GraphDatabase.driver(url, auth=(user, password))
from neo4j import GraphDatabase from neo4j.exceptions import ClientError import os bolt_url = os.getenv("NEO4J_BOLT_URL", "bolt://localhost") user = os.getenv("NEO4J_USER", "neo4j") password = os.getenv("NEO4J_PASSWORD", "neo4j123") driver = GraphDatabase.driver("bolt://localhost", auth=(user, password)) def connect_db(): with driver.session() as session: try: results = session.run(""" CREATE (a:Greeting) SET a.message = 'Hello, Neo4j' RETURN a.message AS message """) result_list = [record['message'] for record in results] message = result_list[0] print('message: {0}'.format(message)) except ClientError as ex: print(ex) def main(): connect_db() if __name__ == "__main__":
from neo4j import GraphDatabase uri = "bolt://babvs65.rothamsted.ac.uk:7687" uri = "bolt://knetminer-wheat.cyverseuk.org:7687" uri = "bolt://www.marcobrandizi.info:7687" #uri = "bolt://knetminer-ara.cyverseuk.org:7687" #driver = GraphDatabase.driver ( uri, auth = ( 'rouser', 'rouser' ) ) driver = GraphDatabase.driver(uri) def show_results(tx): qr = tx.run("MATCH (g:Gene) RETURN g LIMIT 25") for r in qr: g = r['g'] print(g['identifier']) with driver.session() as session: session.read_transaction(show_results)
def __database_session(self): driver = GraphDatabase.driver(dot_env["NEO4J_BOLT_IP"], auth=basic_auth( dot_env["NEO4J_USER"], dot_env["NEO4J_PASSWORD"])) return driver.session()
def server_version_info(cls): with GraphDatabase.driver(cls.bolt_uri, auth=cls.auth_token) as driver: with driver.session() as session: full_version = session.run("RETURN 1").summary().server.version return ServerVersion.from_str(full_version)
import requests from bs4 import BeautifulSoup from urllib.parse import quote import redis from neo4j import GraphDatabase import logging driver = GraphDatabase.driver('bolt://neo:7687/', auth=('neo4j', 'test')) r = redis.Redis(host="redis", port=6379, db=0) BASE_URL = "https://scholar.google.com" SEARCH_AUTHOR_URL = BASE_URL + "/scholar?hl=it&as_sdt=0%2C5&q={}&btnG=" AUTHORS_PAGE_URL = BASE_URL + "/citations?view_op=search_authors&mauthors={}&hl=it&oi=ao" COATHOURS_URL = BASE_URL + "/citations?view_op=list_colleagues&hl=it&json=&user={}#t=gsc_cod_lc" def add_node(tx, id_, name, affiliation): query_string = """MERGE (a:Person {google_id: $google_id, name: $name, affiliation: $affiliation})""" tx.run(query_string, google_id=id_, name=name, affiliation=affiliation) def get_nodes_by_name(tx, name): query_string = """MATCH(p:Person {name: $name}) where not exists (p.google_id) return ID(p), p""" return tx.run(query_string, name=name) def search(q): # convert spaces to %20 quoted_query = quote(q) page_elenco_profili = requests.get(AUTHORS_PAGE_URL.format(quoted_query)) soup_elenco_profili = BeautifulSoup(page_elenco_profili.content,
def test_fails_on_missing_parameter(self): session = GraphDatabase.driver("bolt://localhost").session() with self.assertRaises(CypherError): session.run("RETURN {x}").consume()
def __init__(self, uri, user, password): self.driver = GraphDatabase.driver(uri, auth=(user, password))
def test_record_equality(self): with GraphDatabase.driver("bolt://localhost").session() as session: result = session.run("unwind([1, 1]) AS a RETURN a") assert result[0] == result[1] assert result[0] != "this is not a record"
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 13:10:29 2020 @author: YuJeong """ import csv, sys from neo4j import GraphDatabase with open(sys.argv[1], 'r', encoding='UTF-8') as f: matrix = list(csv.reader(f, delimiter=",")) driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "wowhi223")) def add_node(tx, s_name, s_pid, s_type, dataName1, value1, file_path1, origin1, activityType, date, detail, r_name, r_pid, r_type, allowed_period_from, allowed_period_to, price, is_agreed): if activityType == "생성": tx.run( "CREATE (p:Person), (d:Data), (ac:Activity)" "SET p = {name: $s_name, pid: $s_pid, p_type: $s_type}, " " d = {name: $dataName1, value: $value1, file_path: $file_path1, origin: $origin1}, " " ac = {name: $activityType, date: $date, detail: $detail} " "CREATE (ac) <- [g:Generate] - (d), (ac)-[a:Act]->(p)", s_name=s_name, s_pid=s_pid, s_type=s_type,
def setUp(self): from neo4j import GraphDatabase self.driver = GraphDatabase.driver(self.neo4j_uri, auth=self.auth_token)
# 获取vertica连接配置 logging.info('load db config') config = configparser.ConfigParser() config.read('E:\\MySelfcode\\h3c\\neo4j\\access.conf', encoding='utf-8') vertica_config = dict(config.items('vertica')) vertica_config['backup_server_node'] = vertica_config[ 'backup_server_node'].split(',') # 应该是数据平衡(先搁置) # vertica_config['connection_load_balance'] = bool(vertica_config['connection_load_balance']) objs = [] # get vertica objects uri = "bolt://10.90.15.10:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "admin")) with vertica_python.connect(**vertica_config) as connection: logging.info('get connection with vertica') # 创建连接数据库实例 cur = connection.cursor() cur.execute("""SELECT DISTINCT b.inventory_item_id, a.ITEM_ID, a.PRODUCT_CODE, b.enabled_flag, b.DESCRIPTION, a.PRODUCT_TYPE, a.PRODUCTLINE FROM bigdata.ebs_it_product_line a LEFT JOIN E2E.ebs_system_items_b B ON b.dw_status='A' AND b.ORGANIZATION_ID=473 AND b.segment1=a.item_id WHERE a.dw_status = 'A' AND a.PRODUCT_CODE NOT IN
"C:/Users/Cole/.Neo4jDesktop/relate-data/dbmss/dbms-c8b10dae-58ca-4177-a7a0-55cf4c1fa27b/import/blocked_graph.csv", "r") for line in fin: contents += line fin.close() fout = open( "C:/Users/Cole/.Neo4jDesktop/relate-data/dbmss/dbms-c8b10dae-58ca-4177-a7a0-55cf4c1fa27b/import/blocked_graph.csv", "w") fout.write("supernode1,supernode2\n" + contents) fout.close() #Get API set up uri = "bolt://127.0.0.1:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "cali"), max_connection_lifetime=1000) session = driver.session() #Clean slate neo4j session.run(''' MATCH (n) DETACH DELETE n ''') #Create the new graph database via neo4j API by reading in the exported .csv file session.run(''' LOAD CSV WITH HEADERS FROM 'file:/blocked_graph.csv' AS row CREATE(sn1:Node {name: row.supernode1}) CREATE(sn2:Node {name: row.supernode2})
from html.parser import HTMLParser from datetime import datetime import urllib.request as urllib3 import ssl from neo4j import GraphDatabase import csv # gitFile = open('githubList.csv', 'w') # primeGitFile = open('primeGithubList.csv', 'w') # writer = csv.writer(ofile) driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "neofour")) ssl._create_default_https_context = ssl._create_unverified_context #Neo4J Cypher commands #Create Node def add_package(tx, name): tx.run("CREATE (p:Package {name: $name}) ", name=name) #Set git link exists = true def set_git_true(tx, name): tx.run("MATCH (p:Package) WHERE p.name = $name SET p.gitLinkExists = TRUE", name=name) #Set number of reverse dependencies def set_num_rev_deps(tx, name, num_rev_deps): tx.run(
def __init__(self, creds): self._driver = GraphDatabase.driver(creds["uri"], auth=(creds["user"], creds["password"])) self.session = self._driver.session()
def protocol_version(cls): with GraphDatabase.driver(cls.bolt_uri, auth=cls.auth_token) as driver: with driver.session() as session: return session.run("RETURN 1").summary().protocol_version
def test_fails_on_bad_syntax(self): session = GraphDatabase.driver("bolt://localhost").session() with self.assertRaises(CypherError): session.run("X").consume()
from neo4j import GraphDatabase import json driver = GraphDatabase.driver("bolt://neo4j:7687", auth=("neo4j", "test"), encrypted=False) session = driver.session() similar_ids = [290, 11, 16] res_arr = {} res_arr['sentences'] = [] res_arr['clauses'] = [] id_list = similar_ids query = "MATCH (rn:RootNode)--(cf:ContentField)--(sen:Sentence) " query += 'WHERE (ID(sen) in ' + str(id_list) + ') ' query += "RETURN rn.name as node_id, rn.title as node_title, rn.created as node_created, rn.changed as node_changed, sen.original_sent as sent, sen.shorten_lemma_original as shorten_original" result = session.run(query) for record in result: res_arr['sentences'].append({ 'node_id': record['node_id'], 'node_title': record['node_title'], 'node_created': record['node_created'], 'node_changed': record['node_changed'], 'sent': record['sent'], 'shorten_original': record['shorten_original'] })
import numpy as np import pandas as pd import editdistance # import gensim from neo4j import GraphDatabase, basic_auth,kerberos_auth,custom_auth,TRUST_ALL_CERTIFICATES ''' 需要先构建好图谱才能进行融合操作 ''' #链接数据库 driver = GraphDatabase.driver("neo4j://localhost:7687", auth=basic_auth("neo4j","admin"), encrypted=False) session = driver.session() csv_data = pd.read_csv("./data/DBLP-Scholar_perfectMapping.csv") csv_data['idDBLP'] = csv_data['idDBLP'].map(lambda x: str(x)) # #加载预训练模型 # word2vec = gensim.models.KeyedVectors.load_word2vec_format("./data/GoogleNews-vectors-negative300.bin.gz", binary=True) #读取Neo4j的值 data_DBLP_paper = session.run("MATCH (DBLP_paper:DBLP_paper) return DBLP_paper.DBLP_title,DBLP_paper.DBLP_id,DBLP_paper.year ") data_Scholar_paper = session.run("MATCH (Scholar_paper:Scholar_paper) return Scholar_paper.Scholar_title,Scholar_paper.Scholar_id,Scholar_paper.year,Scholar_paper.remark ") #初始化 dlists = [] dlists_id = [] dlists_year = [] dlists_t = [] slists = [] slists_id = [] slists_year = [] slists_t = [] slists_remark = []
#过程导入 import csv from neo4j import GraphDatabase as GD driver = GD.driver("bolt://localhost:7687", auth = ("neo4j","123")) def addData(gr, node1, rela, node2): #cypher gr.run( "MERGE (a:Object {name: $node1})" "MERGE (b:Object {name: $node2})" "MERGE (a)-[:"+rela+"]->(b)", node1 = node1,node2 = node2 ) path = "C:\\User\\a_080\\Desktop\\test.csv" csv_file = open(path, 'r') csvReader=csv.reader(csv_file) with driver.session() as session: for eachline in csvReader: print(eachline) input() try: session.write_transaction(addData,eachline[0],eachline[1],eachLine[2]) except Exception as e:
} for s in subset[0].get('article:section') or []] json_ld_as_map = { '@context': 'http://schema.org', '@id': url, 'author': authors, 'section': sections } return json.dumps(json_ld_as_map) def load_json_ld(tx, json_ld_data): cypher_neosemantics = " CALL semantics.importRDFSnippet($payload,'JSON-LD');" import_summary = tx.run(cypher_neosemantics, payload=json_ld_data) print(import_summary) uri = "bolt://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "neo")) rss_entries_as_json_ld, entry_url_list = get_rss( 'https://www.theguardian.com/uk/rss') with driver.session() as session: session.write_transaction(load_json_ld, rss_entries_as_json_ld) rdfa_ext = RDFaExtractor() for url in entry_url_list: session.write_transaction(load_json_ld, get_article_additional_details(url)) driver.close()
def get_repodb_subgraph_given_genes(gene_ids): #Connect to RepotrialDB connect_url = "bolt://repotrial.bioswarm.net:8687" username = "******" password = "******" driver = GraphDatabase.driver(connect_url, auth=(username, password)) repodb_ids = ["entrez.{}".format(i) for i in gene_ids] print("Repodb ids ",repodb_ids) #Format the query string # Drugs, disorders query = """ UNWIND {repodb_ids} as i MATCH (gene:Gene {primaryDomainId:i}) OPTIONAL MATCH (gene)<-[peg:ProteinEncodedBy]-(pro:Protein) OPTIONAL MATCH (pro)<-[dht:DrugHasTarget]-(drug) OPTIONAL MATCH (drug)-[dsim:MoleculeSimilarityMolecule]-(drug1) WHERE dsim.morganR2 > 0.5 OPTIONAL MATCH (gene)-[gawd:GeneAssociatedWithDisorder]-(disorder) RETURN gene, peg, pro, drug, disorder, dht, gawd, dsim, drug1 """ print (query) R = nx.Graph() #Execute the query with driver.session() as session: for result in session.run(query, repodb_ids=repodb_ids): # Imagine result as a hash map. The keys are the variables you had # in the return clase of the query. gene = result["gene"] # Imagine gene is now a hash map of the node / edge requested, with # key:value pairs being attribute_name : attribute_value. # The primaryDomainId is most ideal for the node label (we can swap # this out after). gene_id = gene["primaryDomainId"] # Add node to graph R. **gene is some syntactic sugar. Basically, # add_node takes a label as 0th positional argument, then keyword # arguments for the remaining attributes. **gene takes a hash map # (e.g., {"geneType": "protein-coding", "displayName": "TMPRSS2"}), # and expands it as keyword arguments for the function (i.e., # (geneType = "protein-coding", displayName = "TMPRSS2")) R.add_node(gene_id, **flatten(gene)) # Changed the query to OPTIONAL MATCH -- this means that, if the # pattern doesn't match, the variables are replaced with None / Null pro = result["pro"] # Because pro can be Null / None, we check for this and don't want # to add anything if not. if pro: pro_id = pro['primaryDomainId'] R.add_node(pro_id, **flatten(pro)) peg = result["peg"] # Similarly, peg can be None. if peg: R.add_edge(pro_id, gene_id, **flatten(peg)) drug = result["drug"] if drug: drug_id = drug['primaryDomainId'] R.add_node(drug_id, **flatten(drug)) drug1 = result["drug1"] if drug1: drug1_id = drug1['primaryDomainId'] R.add_node(drug1_id, **flatten(drug1)) disorder = result["disorder"] if disorder: disorder_id = disorder["primaryDomainId"] R.add_node(disorder_id, **flatten(disorder)) gawd = result["gawd"] if gawd: R.add_edge(gene_id, disorder_id, **flatten(gawd)) dsim = result["dsim"] if dsim: R.add_edge(drug_id, drug1_id, **flatten(dsim)) dht = result["dht"] if dht: R.add_edge(drug_id, pro_id, **flatten(dht)) return R
from IPython.display import Image nodeStartedNonFreeChoice = [] nodeLeafNonFreeChoice = [] dataInArray = "" dataTestingInArray = "" dataTestingInArrayOneOfEachRow = [] dataLeafTestingEachNode = [] dataHeaderInArray = "" dataLeaf = [] dataCaseActivity = [] dataCaseId = "" nodeRoot = ["A"] endNode = "H" driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "sanggung2")) def deleteRelation(tx): tx.run("match p=()-[]-(), q=() delete p, q") def deletenNode(tx, nodeName): tx.run("match (c:"+nodeName+") delete c") def importActivity(tx, fileName): tx.run("LOAD CSV with headers FROM 'file:///"+fileName+"' AS line " "Merge (:Activity {CaseId:line.Case_ID, Name:line.Activity, Time:line.Time})") def importCaseActivity(tx, fileName): tx.run("LOAD CSV with headers FROM 'file:///"+fileName+"' AS line " "Merge (:CaseActivity {Name:line.Activity })")
def create_and_return_greeting(tx, name): return tx.run("CREATE (n:Company {name:'" + name + "'})") def link_cypher(tx, source_name, target_name): return tx.run( "MATCH (s:Company) WHERE s.name = '" + source_name + "' MATCH (t:Company) WHERE t.name = '" + target_name + "' CREATE (s)-[:TRANSFER]->(t)", ) if __name__ == '__main__': with open('graph.json') as json_file: data = json.load(json_file) driver = GraphDatabase.driver('neo4j://neo4j.mogbymo.io:7687', auth=('neo4j', 'neo4j')) with driver.session() as session: [ session.write_transaction(create_and_return_greeting, node['id']) for node in data['nodes'] ] print("Nodes created") [ session.write_transaction(link_cypher, link['source'], link['target']) for link in data['links'] ] print("Links created") driver.close()