欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

py2neo操作neo4j

程序员文章站 2022-07-14 11:32:08
...
docker run -it -d -p 7474:7474 -p 7687:7687 neo4j:3.4

http://localhost:7474/browser/
neo4j/neo4j
# -*- coding: utf-8 -*-
# @Author: xiaodong
# @Date  : 2020/7/20

import json

from py2neo import NodeMatcher
from py2neo import Graph, Node, Relationship


def load_json(path):
    with open(path, encoding="utf-8") as file:
        data = json.load(file)
    return data

g = Graph("bolt://localhost:7687", password="your-password")
matcher = NodeMatcher(g)

if __name__ == '__main__':
    records = load_json("movies.json")
    
    history = {}
    mapping = {
        "name": "电影名称",
        "to_url": "百度链接",
        "actors": "演员名称",
    }
    for movie, detail in records.items():
        for k, v in detail.items():
            k = mapping.get(k, k)
            if isinstance(v, list):
                v = list(filter(lambda obj: obj.strip(), v))
                history.setdefault(k, set()).update(set(v))
            else:
                if v.strip():
                    history.setdefault(k, set()).add(v)

    tx = g.begin()
    for label, aset in history.items():
        for element in aset:
            node = Node(label, **{"label": element})
            tx.create(node)
    tx.commit()

    tx = g.begin()
    for movie, detail in records.items():
        movie_nodes = matcher.match(**{"label": movie})
        for movie_node in movie_nodes:
            for k, v in detail.items():
                if k == "name":
                    continue
                if isinstance(v, list):
                    for _v in v:
                        nodes = matcher.match(**{"label": _v})
                        for node in nodes:
                            relation = Relationship(movie_node, mapping.get(k, k), node)
                            tx.create(relation)
                else:
                    nodes = matcher.match(**{"label": v})
                    for node in nodes:
                        relation = Relationship(movie_node, mapping.get(k, k), node)
                        tx.create(relation)
    tx.commit()

py2neo操作neo4j
py2neo操作neo4j

详情:python操作数据库