python访问neo4j数据库读取数据

1. 与neo4j数据库建立连接

import copy
from neo4j import GraphDatabase

def connect():
    driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j","password"))
    return driver

2.访问并处理数据

#查询
def query(tx, name):
    content = []
    link_list = []
    id_list = []
    # 模糊查询
    statementrecord = tx.run("MATCH (n) WHERE n.name =~ '.*" + name + ".*' RETURN n ORDER BY n.name DESC")
    # 查询结果存入字典
    for record in statementrecord.records():
        dic = dict(record['n'])
        id_list.append(record['n'].id)
        dic['id'] = record['n'].id
        dic['labels'] = str(record['n'].labels)[12:-3]
        content.append(dic)
    # 根据id查询关系节点
    linkrecord = tx.run("MATCH (n)<-[r]->(x) WHERE id(n) in {list} RETURN id(n), labels(x), x.name, r", list=id_list)
    dic = {}
    count = 1
    # 存入字典,将id相同的查询结果进行整合
    for record in linkrecord.records():
        idn = record['id(n)']
        xlabels = record['labels(x)'][0].lower()
        xname = record['x.name']
        if dic.get('id') == idn:
            if dic.get(xlabels):
                if xname not in dic[xlabels]:
                    dic[xlabels].append(xname)
                    count += 1
            else:
                count += 1
                dic[xlabels] = [xname]
        else:
            if dic != {}:
                dic['cnt'] = count
                count = 1
                link_list.append(copy.copy(dic))
            dic = {}
            dic['id'] = idn
            dic[xlabels] = [xname]
    dic['cnt'] = count
    link_list.append(dic)
    for link in link_list:
        for con in content:
            try:
                if con['id'] == link['id']:
                    con.update(link)
            except:
                pass
    return content

#排序
def sort_data(data):
    data = sorted(data, key=lambda x: x.__getitem__('cnt'), reverse=True)
    return data

#获取查询结果
def get_data(name):
    driver = connect()
    with driver.session() as session:
        data = session.read_transaction(query,name)
        data = sort_data(data)
    return data

if __name__ == '__main__':
    for i in get_data('石油'):
        print(i)

运行结果如下:

python访问neo4j数据库读取数据_第1张图片

你可能感兴趣的:(KG知识图谱)