Ejemplo n.º 1
0
def main():
    bolt_url = default(prompt('bolt url(default=bolt://localhost:7687): '),
                       'bolt://localhost:7687')
    username = default(prompt('username(defalt=neo4j): '), 'neo4j')
    password = prompt('password: '******'MATCH (n) DETACH DELETE n')

    tx = graph.begin()
    alice = Node("Person", name="Alice")
    tx.create(alice)
    bob = Node("Person", name="Bob")
    relationship = Relationship(alice, "KNOWS", bob)
    tx.create(relationship)
    tx.commit()

    for rel in graph.match(start_node=alice, rel_type="KNOWS"):
        print(rel.end_node()["name"])

    print(graph.exists(relationship))

    a = graph.find_one(label="Person",
                       property_key="name",
                       property_value="Alice")
    r = graph.match_one(start_node=a, rel_type="KNOWS")
    print(r.end_node()['name'])
Ejemplo n.º 2
0
class BaikeGraph:
    def __init__(self):
        cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1])
        self.cur_dir = cur_dir
        self.g = Graph(
            host="10.37.2.248",
            http_port=7474,
            user="******",
            password="******")
        self.matcher = NodeMatcher(self.g)
        #self.rel_matcher = RelationshipMatcher(self.g)
    def nodeExist(self,lable,iid):
        dict_id = {"iid":iid}
        m = self.matcher.match(lable, **dict_id).first()
        if m is None:
            return False
        else:
            return True
    
    def nodeExist_new(self, lable,iid):
        query = "MATCH (n:%s) where n.iid='%s' RETURN n"%(lable,iid)
        try:
            m = self.g.run(query).data()
            if m:
                return True
            else:
                return False
        except Exception as e:
            print(e)
            return False

    def create_baike_node(self, baike_infos):
        node = Node("Baike6", **baike_infos)
        if not self.g.exists(node):
            self.g.create(node)
        return

    def relExist(self,start_iid,rel,end_iid):
        query = "MATCH p=(n:Baike4{vid:'%s'})-[r:`%s`]->(m:Baike4{vid:'%s'}) return p"%(start_iid,rel,end_iid)
        try:
            m=self.g.run(query).data()
            if m:
                return True
            else:
                return False
        except Exception as e:
            print(e)
            return False        

    def create_relationship(self, start_node_vid, start_node_iid,end_node_vid, end_node_iid,rel, start_node="Baike6", end_node="Baike6"):

        query = "match(p:%s),(q:%s) where p.vid='%s' and p.iid='%s' and q.vid='%s' and q.iid='%s' merge (p)-[rel:%s{name:'%s'}]->(q)" % (
            start_node, end_node, start_node_vid, start_node_iid, end_node_vid,end_node_iid,rel, rel)
        try:
            self.g.run(query)
        except Exception as e:
            print(e)
        return
Ejemplo n.º 3
0
from py2neo import Graph, Node, Relationship

g = Graph()
tx = g.begin()
a = Node("Person", name="Alice")
tx.create(a)
b = Node("Person", name="Bob")
ab = Relationship(a, "KNOWS", b)
tx.create(ab)
tx.commit()
g.exists(ab)


"""
Sample Query
>>> from py2neo import Graph
>>> g = Graph()
>>> g.run("MATCH (a) WHERE a.name={x} RETURN a.name", x="Bob").evaluate()
u'Bob'
>>>
"""
Ejemplo n.º 4
0
# Create basic relationships

# Query the whole DB
x = food_gr.run('MATCH (r) RETURN r').to_data_frame()
x

# Show how many nodes were retrieved.
print(len(x))

# Delete the current Graph
food_gr.delete_all()

tx = food_gr.begin()

mac_n_cheese = Node("Recipe", name="Macaroni and Cheese")
tx.create(mac_n_cheese)
pasta = Node("Ingredient", name="elbow macaroni")
tx.create(pasta)
cheese = Node("Ingredient", name="shredded cheddar")
tx.create(cheese)
milk = Node("Ingredient", name="milk")
tx.create(milk)

rels = {"r1": Relationship(pasta, 'IS_USED_IN', mac_n_cheese)}

tx.create(rels["r1"])
tx.commit()
print(food_gr.exists(rels["r1"]))

print(rels['r1'])
Ejemplo n.º 5
0
class CallGraph:
    def __init__(self,uri,user,password):
        self._graph = Graph(uri,auth=(user,password))
        self.db = GraphDatabase.driver(uri,auth=(user,password))
        self.sess = self.db.session(default_access_mode=WRITE_ACCESS)
        self.user=user
        self.pw = password

    def __del__(self):
        self.sess.close()
        self.db.close()
        
    def addNode(self,node):
        if not (self._graph.exists(node)):      
            self._graph.create(node)
            
    #relationship as string!    
    def addNodeR(self,node_from,relationship,node_to):
        if not (self._graph.exists(Relationship(node_from,relationship,node_to))):
            self._graph.create(Relationship(node_from,relationship,node_to))
            
    #relationship as relationship type!
    def addRelationship(self,relationship):
        if not (self._graph.exists(relationship)):
            self._graph.create(relationship) 
       

    def merge(self,label):
        cg._graph.merge(label)
        
    def commit(self):
        self._tx.commit()

    def getGraph(self):
        return self._graph


    def getNode(self,node_label,properties=None,limit=1):
        #print("########################")
        q = "MATCH (n:"+node_label+") "
        if properties is not None:
            allNone = True
            for p in properties.values():
                if p is not None:
                    allNone = False
                    break

            if not allNone:
                q +="WHERE "
                nd = False
                for i in properties.items():
                    if i[1] is None:
                        continue
                    if nd:
                        q+=" AND "
                    q+= "n."+str(i[0])+ "='"+str(i[1]).replace("'","\'")+"'"
                    nd = True
                    

        q+= "RETURN (n) "
        if limit is not None:
            q+= "LIMIT "+str(limit)+";"
        else:
            q+=";"
            
        #print(q)
        #tprint("RUNNING QUERY:\n"+q)
        maxtries=10
        res2 = None
        #try avoid deadlocks
        for i in range(0,maxtries):
            try:
                res2 = self.sess.run(q)
            except:
                time.sleep(random.randrange(10))

        node = None
        try:
            res2 = iter(res2)
            res2= next(res2)
            n = res2.get("n")
            node = Node()
            node.identity = n.id
            node.update_labels(n.labels)
            for prop in n.items():
                node[prop[0]] = prop[1]           
            node.graph = self._graph
        except Exception as e:
            pass
        

        #tprint("QUERY:\n"+q+"\nSUCCESS\nRESULT: "+str(node))
        return node
Ejemplo n.º 6
0
class Neo4j(object):
    def __init__(self):
        self.graph = Graph(Config.NEO_URL,
                           username=Config.NEO_USR,
                           password=Config.NEO_PSW)
        self.mm = MongoManager.DBManager()

    def add_relation(self,
                     node_name1,
                     node_name2,
                     movie_name='name',
                     url='url'):
        """
        图中添加新的导演关系
        若关系中的两个节点不在图中则自动创建
        同时为关系添加电影名、发行时间、关系计数这几个参数
        :param node_name1:
        :param node_name2:
        :param movie_name:
        :param release_time:
        :return:
        """
        node1 = Node(DIRECTOR_LABEL, name=node_name1)
        node1['type'] = 'director'
        node2 = Node(ACTOR_LABEL, name=node_name2)
        # node3 = Node(MOVIE_LABEL, name=movie_name)
        # node3['url'] = url
        #
        # actor_movie_relation = Relationship(node2, ACTIN_LABEL, node3)
        # director_movie_relation = Relationship(node1, DIRECT_LABEL, node3)
        # self.graph.merge(actor_movie_relation, DEFAULT_LABEL, 'name')
        # self.graph.merge(director_movie_relation, DEFAULT_LABEL, 'name')

        # print(actor_movie_relation)
        # print(director_movie_relation)

        # if self.find_relation(node_name1, node_name2):
        #     print('relation already existed, add count')
        # else:
        relation = Relationship(node1, COOPERATE_LABEL, node2)
        relation['count'] = 1
        self.graph.merge(relation, DEFAULT_LABEL, 'name')
        # print("成功创建关系", node_name1, ',', COOPERATE_LABEL, ',', node_name2)

    def print(self, name, relation):
        """
        打印所有以名字为name的节点开始、具有relation关系的边的终节点的信息
        :param name:
        :param relation:
        :return:
        """
        print('##########')
        query = 'MATCH (n) WHERE n.name={name} RETURN n'
        params = dict(name=name)
        node = self.graph.evaluate(query, params)
        print(node)
        for rel in self.graph.match((node, ), relation):
            print(rel.end_node['name'], rel.end_node.labels, rel['movie_name'],
                  rel['release_time'])

    def find_director_node(self, name):
        """
        查找具有某名字的节点,若图中有此节点则返回true,反之返回false
        :param name:
        :return:
        """
        query = 'MATCH (n:Director) WHERE n.name={name} RETURN n'
        params = dict(name=name)
        node = self.graph.evaluate(query, params)
        if node is None:
            return False
        if self.graph.exists(node):
            return True
        else:
            return False

    def find_actor_node(self, name):
        """
        查找具有某名字的节点,若图中有此节点则返回true,反之返回false
        :param name:
        :return:
        """
        query = 'MATCH (n:Actor) WHERE n.name={name} RETURN n'
        params = dict(name=name)
        node = self.graph.evaluate(query, params)
        if node is None:
            return False
        if self.graph.exists(node):
            return True
        else:
            return False

    def get_labeled_node(self, count=1):
        """
        获取具有某个标签的节点列表
        打印节点数量
        并返回该list
        :return:
        """
        # 用CQL进行查询,返回的结果是list
        datas = self.graph.data('MATCH(p:Director) return p')
        # 目标节点数量
        # print(len(datas))
        # 数据类型为list
        # print(type(datas))
        _count = 1
        for data in datas:
            # data类型为dict
            # print(type(data))
            # if _count > count:
            #     break
            print(data)
            _count += 1
        print('Total count of Director is', _count)
        return datas

    def find_relation_and_add_count(self, name1, name2):
        """
        查找分别以name1, name2为起始、终止节点的 CooperateWith 关系
        若找到则对应count数加一
        :param name1:
        :param name2:
        :return:
        """
        sn = self.graph.find_one(DIRECTOR_LABEL,
                                 property_key='name',
                                 property_value=name1)
        en = self.graph.find_one(ACTOR_LABEL,
                                 property_key='name',
                                 property_value=name2)
        rel = self.graph.match(start_node=sn,
                               rel_type=COOPERATE_LABEL,
                               end_node=en)
        # print(rel)

        # print('--------')
        query = 'MATCH(n:Director)-[r:CooperateWith]->(m:Actor) WHERE n.name={name1} and m.name={name2} RETURN r'
        params = dict(name1=name1, name2=name2)
        relation = self.graph.evaluate(query, params)
        if relation is None:
            print('relation is none')
            self.add_relation(name1, name2)
            return False
        if self.graph.exists(relation):
            print('relation exists, add count')
            relation['count'] += 1
            self.graph.push(relation)
            print(relation.start_node()['name'], '->', relation['count'], '->',
                  relation.end_node()['name'])
            return True
        else:
            print('relation does not exist')
            return False

    def clear_graph(self):
        """
        清空图数据库
        :return:
        """
        self.graph.delete_all()

    def show_end_node(self, name, relation_label):
        """
        根据输入的起始节点名和关系标签,遍历全部对应关系,并打印终节点的属性群
        :param name:
        :param relation_label:
        :param attrs:
        :return:
        """
        query = 'MATCH (n) WHERE n.name={name} RETURN n'
        params = dict(name=name)
        node = self.graph.evaluate(query, params)
        if node is None:
            print('node is None!')
            return False
        if self.graph.exists(node):
            print(node)
            # 遍历此起始节点的全部关系,打印关系的个数
            for rel in self.graph.match((node, ), relation_label):
                print(name, '->', rel['count'], '->', rel.end_node['name'])
        else:
            print('node not exists!')
            return False

    def get_coop_count(self):
        """
        获取全部导演、演员合作关系及次数并打印
        :return:
        """
        directors = self.get_labeled_node()
        # print(type(directors))
        count = 1
        for director in directors:
            if count > 1:
                break
            # print(director['p']['name'])
            self.show_end_node(director['p']['name'], COOPERATE_LABEL)
            count += 1

    def get_cooperations(self):
        directors = self.get_labeled_node()
        # datas = []
        for director in directors:
            query = 'MATCH (n) WHERE n.name={name} RETURN n'
            params = dict(name=director['p']['name'])
            node = self.graph.evaluate(query, params)
            if node is None:
                print('node is None!')
                return None
            if self.graph.exists(node):
                # 遍历此起始节点的全部关系,一一存入结果集并返回
                for rel in self.graph.match(start_node=node,
                                            rel_type=COOPERATE_LABEL):
                    data = {
                        'director': director['p']['name'],
                        'actor': rel.end_node()['name'],
                        'count': rel['count']
                    }
                    # print("合作信息,", data)
                    self.mm.save_data(Config.COOPERATION_TEMP, data)
                    # datas.append(data)
            else:
                print('node not exists!')
                return None
Ejemplo n.º 7
0
    parent["real_enzyme"] = False
    graph.merge(parent)
uniques = set()
time_begin = datetime.now()

with open('data_files/allenz_altered.txt') as input_file:
    lines = input_file.readlines()
    for line in lines:
        line = line.strip('\n')
        name, pattern = line.split(",")
        node = Node(label_word)
        node["name"] = name
        node["pattern"] = pattern
        node["real_enzyme"] = True

        seq_list = expand_seqs(pattern)
        for seq in seq_list:
            if seq in uniques:
                continue
            uniques.add(seq)
            entry_copy = deepcopy(node)
            entry_copy["pattern"] = seq

            if not graph.exists(entry_copy):
                insert_node(entry_copy)


time_end = datetime.now()

print("time:", time_end - time_begin)
Ejemplo n.º 8
0
sys.exit(1)
"""

# 方式2:  *****访问被代理或docker 容器中的 neo4j server的话,只能用这种方式 *********
# set up authentication parameters
http_port = "7476"
authenticate("localhost:"+http_port, "username", "password")
# connect to authenticated graph database
g = Graph("http://localhost:"+http_port+"/db/data/", bolt_port=7689)


g.data('match (n) return count(*)')
g.run('match (n) return count(*)').dump()


# import data in one transaction
tx = g.begin()
a = Node("Person", name="Alice")
b = Node("Person", name="Bob")
tx.create(a)
ab = Relationship(a, "KNOWS", b)
tx.create(ab)
#tx.commit()
print g.exists(ab)

# get nodes in one autocommit transaction
g.run("MATCH (a:Person) RETURN a.name, a.born LIMIT 4").data()

# get 
g.run('match (n) return count(*)').dump()
Ejemplo n.º 9
0
from py2neo import Graph, Node, Relationship
from py2neo import Watch

watch("httpstream")

# graph = Graph()
graph = Graph("http://localhost:7474/db/data/",  user = "******", password = "******")

# transactionContainer
register = graph.begin()

alice = Node("Friend", name="Alice", age=33)
bob = Node("Friend", name="Bob", age=44)

alice["age"] = 33
bob["age"] = 44

register.create(alice)
register.create(bob)

alice_knows_bob = Relationship(alice, "KNOWS", bob)
register.create(alice_knows_bob)

print (alice_knows_bob)

register.commit()

print(graph.exists(alice_knows_bob))

# graph.delete_all()
Ejemplo n.º 10
0
#transaction about commit
from py2neo import Graph, Node, Relationship

graph = Graph(password='******')
# tx = graph.begin()
# # a = Node("Person", name="Lilei")
# # tx.create(a)
# # b = Node("Person", name="Hanmeimei")
# # ab = Relationship(a, "KNOWS", b)
# # tx.create(ab)
# # tx.commit()
# # graph.exists(ab)

tx = graph.begin()
a = Node("Person", name="Jack")
tx.create(a)
# b = Node("Person", name="Hanmeimei")
b = graph.nodes[25]
ab = Relationship(a, "KNOWS", b)
tx.create(ab)
tx.commit()
print(graph.exists(ab))
Ejemplo n.º 11
0
from py2neo import Graph, Node, Relationship

g = Graph()
tx = g.begin()
a = Node("Person", name="Alice")
tx.create(a)
b = Node("Person", name="Bob")
ab = Relationship(a, "KNOWS", b)
tx.create(ab)
tx.commit()
g.exists(ab)
"""
Sample Query
>>> from py2neo import Graph
>>> g = Graph()
>>> g.run("MATCH (a) WHERE a.name={x} RETURN a.name", x="Bob").evaluate()
u'Bob'
>>>
"""
Ejemplo n.º 12
0
class NeoInterface:
    def __init__(self, uri, user, password):
        self.graph = Graph(host="localhost", auth=("neo4j", "neo5j"))

    def close(self):
        self.driver.close()

    def print_greeting(self, message):
        with self.driver.session() as session:
            greeting = session.write_transaction(
                self._create_and_return_greeting, message)
            print(greeting)

    @staticmethod
    def _create_and_return_greeting(tx, message):
        result = tx.run(
            "CREATE (a:Greeting) "
            "SET a.message = $message "
            "RETURN a.message + ', from node ' + id(a)",
            message=message)
        return result.single()[0]

    def traceroute_to_transaction(self, traceroute):
        print(traceroute)
        for index, traceroute_hop in enumerate(traceroute):
            tx = self.graph.begin()
            if index == 0:
                src_ip = traceroute_hop[1]
                src_node = Node("IPAddress", ip_addr=src_ip)
                tx.create(src_node)

            elif index == len(traceroute):
                dst_ip = traceroute_hop[2]
                dst_node = Node("IPAddress", ip_addr=dst_ip)
                tx.create(dst_node)

            traceroute_id = traceroute_hop[0]
            hop_number = traceroute_hop[3]
            hop_ip = traceroute_hop[4]
            hop_node = Node("IPAddress", ip_addr=hop_ip)
            tx.create(hop_node)
            relation_properties = {
                'hop_number': hop_number,
                'traceroute_id': traceroute_id
            }

            if index == len(traceroute):
                relation = Relationship(hop_node, 'ROUTES_TO', dst_node,
                                        **relation_properties)
            elif index == 0:
                relation = Relationship(src_node, 'ROUTES_TO', hop_node,
                                        **relation_properties)
            else:
                relation = Relationship(prev_hop, 'ROUTES_TO', hop_node,
                                        **relation_properties)
            print(relation)
            tx.create(relation)
            tx.commit()
            prev_hop = hop_node
            print(prev_hop)
            print(hop_node)
            time.sleep(1)
            print(self.graph.exists(relation))