当前位置: 首页>>代码示例>>Python>>正文


Python Graph.push方法代码示例

本文整理汇总了Python中py2neo.Graph.push方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.push方法的具体用法?Python Graph.push怎么用?Python Graph.push使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在py2neo.Graph的用法示例。


在下文中一共展示了Graph.push方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import push [as 别名]
class Graph(object):

    def __init__(self, neo4j_uri):
        self.graph = NeoGraph(neo4j_uri)
        self.nodes = Nodes(self.graph)
        self.links = Links(self.graph)

    def execute_raw(self, cqlfile):
        cypher = self.graph.cypher
        with open(cqlfile, 'r') as query:
            return cypher.execute(query.read())
        return []

    def create_user(self, args):
        node = self.nodes.find("User", args["username"])
        if not node:
            passhash = Authenticate.hashgen(args["username"], args["password"])
            properties = dict(
                node_id=args["username"],
                name=args["name"],
                city=args["city"],
                passhash=passhash
            )
            node = Node("User", **properties)
            self.graph.create(node)
            return node, True
        return node, False

    def create_issue_nodes(
            self, parent, names, node_type, link_type="HAS", link_prop={}):
        # support function for create_issue 
	# create nodes of 1 type (value/objective/policy)
	# and link those to the sourceNode, with specified linkType and properties
        nodes = []
        for name in names:
            properties = dict(
                node_id=str(uuid.uuid4()),
                name=name
            )
            node = Node(node_type, **properties)
            self.graph.create(node)
            self.graph.create(Relationship(parent, link_type, node, **link_prop))
            nodes.append(node)
        return nodes

    def create_issue(self, args):
        # create a new issue Node
        # assign a random node_id using python uuid module
	# below try uuid4, uuid1 works as well 
        issue_properties = dict(
                node_id=str(uuid.uuid4()),
                name=args["issue_name"],
                desc=args["desc"]
            )
        issue_node = Node("Issue", **issue_properties)
        self.graph.create(issue_node)
 
        # create new nodes and links for values/objectives/policies
        # associated with the new issue
        self.create_issue_nodes(issue_node, args["values"], "Value")
        self.create_issue_nodes(issue_node, args["objectives"], "Objective")
        self.create_issue_nodes(issue_node, args["policies"], "Policy")
        return issue_properties["node_id"]

    def user_rank(self, args, node_type):
        # success = False
        # errors = []

        user = self.nodes.find("User", args["user_id"])
        if not user:
            return False, "invalid user_id"

        node = self.nodes.find(node_type, args["node_id"])
        if not node:
            return False, "invalid node_id"

        link = self.links.find(user, node, "RANKS")
        if link:
            link.properties["rank"] = args["rank"]
            link.push()
        else:
            properties = {"rank": args["rank"]}
            if "issue_id" in args:
                properties["issue_id"] = args["issue_id"]
            self.graph.create(Relationship(user, "RANKS", node, **properties))
        return True, ""

    def user_map(self, args, src_node, dst_node):
        # TODO refactor this into smaller units

        # success = False
        errors = []

        # retrieve nodes and existing links
        user = self.nodes.find("User", args["user_id"])
        if not user:
            errors.append("invalid user_id")
        src = self.nodes.find(src_node, args["src_id"])
        if not src:
            errors.append("invalid src_id")
#.........这里部分代码省略.........
开发者ID:psu-capstone,项目名称:dlab-api,代码行数:103,代码来源:graph.py

示例2: TwitterGraph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import push [as 别名]
class TwitterGraph(object):
    '''A class for interfacing with the Neo4j Twitter network database'''

    # Initial setup and linking into the database
    def __init__(self, host_port, user, password):
        '''Makes connection to Neo4j database'''
        # set up authentication parameters
        authenticate(host_port, user, password)
        # connect to authenticated graph database
        url = 'http://{}/db/data/'.format(host_port)
        self.graph = Graph(url)
        try:
            self.graph.schema.create_uniqueness_constraint('User', 'id')
        except: #ConstraintViolationException
            print 'Unique id on Node User already exists'

    # Functions to add data to the database
    def add_following(self, user_id, following_ids, rec_count):
        '''Given a unique user id, adds the relationship for who they follow.
        Adds a User Node with the id if it doesn't exist.'''
        user = Node('User', id=user_id)
        self.graph.merge(user) # important to merge before doing anything
        rec = 1 + rec_count
        # preserving the order of the following. 1 = most recent
        for fid in following_ids:
            user2 = Node('User', id=fid)
            self.graph.merge(user2)
            self.graph.merge(Relationship(user, 'FOLLOWS', user2, rec=rec))
            rec += 1
        user['following_added'] = True
        self.graph.push(user)

    def add_followers(self, user_id, follower_ids, rec_count):
        '''Given a unique user id, adds the relationship for follows them.
        Adds a User Node with the id if it doesn't exist.'''
        user = Node('User', id=user_id)
        self.graph.merge(user)
        rec = 1 + rec_count
        for fid in follower_ids:
            user2 = Node('User', id=fid)
            self.graph.merge(user2)
            self.graph.merge(Relationship(user2, 'FOLLOWS', user, rec=rec))
            rec += 1
        user['followers_added'] = True
        self.graph.push(user)

    def add_user_properties(self, user):
        '''Given a unique user id, adds properties to the existing user Node'''
        try:
            user_id = user.id
            existing_user = Node('User', id=user_id)
            clean_prop_dict = self.__clean_user_dict(user.__dict__)
            self.graph.merge(existing_user)
            for k, v in clean_prop_dict.iteritems():
                existing_user[k] = v
            # add additional label to verified accounts
            if clean_prop_dict['verified']:
                print True
                existing_user.add_label('Verified')
        except:
            # bad user id
            user_id = user['user_id']
            error = user['error']
            existing_user = Node('User', id=user_id)
            self.graph.merge(existing_user)
            existing_user['screen_name'] = 'INVALID'
            existing_user['error'] = error
            print 'Found invalid user id'
        self.graph.push(existing_user)

    def __clean_user_dict(self, user_prop_dict):
        '''Given the '''

        keep = ['contributors_enabled', 'created_at', 'default_profile',
                'default_profile_image', 'description', 'favourites_count',
                'followers_count', 'friends_count', 'geo_enabled', 'id',
                'id_str', 'is_translator', 'lang', 'listed_count', 'location',
                'name', 'profile_image_url_https', 'protected', 'screen_name',
                'statuses_count', 'time_zone', 'utc_offset', 'verified',
                'withheld_in_countries', 'withheld_scope']

        # only keep the above keys for inserting
        clean = {k: v for k, v in user_prop_dict.iteritems() if k in keep}
        image = os.path.splitext(clean['profile_image_url_https'])[0]
        ext = os.path.splitext(clean['profile_image_url_https'])[1]
        clean['profile_image_url_https'] = image.rstrip('_normal') + ext
        # convert date time to string
        clean['created_at_ord'] = clean['created_at'].toordinal()
        clean['created_at'] = clean['created_at'].strftime('%Y-%m-%d %H:%M:%S')
        return clean

    # Functions to query database
    def get_nodes_missing_props(self, limit=100):
        '''Returns the first 100 ids of nodes without user properties'''
        selector = NodeSelector(self.graph)
        selected = selector.select('User').where("_.screen_name IS NULL").limit(limit)
        return [s['id'] for s in selected]

    def get_nodes_missing_props_follb(self, limit=100):
        cypherq = """MATCH (n)-[r:FOLLOWS]->(m)
#.........这里部分代码省略.........
开发者ID:kaylaandersen,项目名称:twitter-graph,代码行数:103,代码来源:tgdb.py

示例3: Graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import push [as 别名]
__author__ = "Andrei"

from py2neo import Graph
from py2neo import Node, Relationship


graph = Graph("http://neo4j:[email protected]:7474/db/data")
alice = Node("Person", name="Alice")
bob = Node("Person", name="Bob")
alice_knows_bob = Relationship(alice, "KNOWS", "bob")
graph.create(alice_knows_bob)

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

graph.push(alice, bob)
开发者ID:chiffa,项目名称:Chiffa_Area51,代码行数:18,代码来源:py2neo_trial.py

示例4: TestNeoDBHandler

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import push [as 别名]

#.........这里部分代码省略.........
            "mention_date":"today"
        })
        mbe2.properties.update({
            "replies":10,
            "reply_last":"2000000",
            "reply_date":"tommorow"
        })
        lrich.properties.update({
            "replies":15,
            "reply_last":"3000000",
            "reply_date":"yesterday"
        })
        tbw.properties.update({
            "retweets":20,
            "retweet_last":"4000000",
            "retweet_date":"thismorning"
        })
        tbw2.properties.update({
            "mentions":1,
            "mention_last":"3000000",
            "mention_date":"yesterday"
        })


        for node in self.node_list:
            self.graph.create(node)
        
        self.graph.create(mbe1)
        self.graph.create(mbe2)
        self.graph.create(lrich)
        self.graph.create(tbw)
        self.graph.create(tbw2)

        self.graph.push()

    def tearDown(self):
        
        # remove test items
        self.graph.cypher.execute("MATCH (n:TEST) DETACH DELETE n")

        empty_list = [ _ for _ in self.graph.find('TEST') ]
        self.assertEqual( empty_list, [])




        ########################################################################
        #                          CYPHER QUERIES                              #
        ########################################################################

    def test_get_party_nodes(self):
        neo_db_handler = NeoDBHandler(n4_database=TEST_GRAPH_DB)

        test_reference = [
           {
                "name":"Kendog Lamar", 
                "handle":"Kdog", 
                "party":"Marvel",
                "constituency":"CB3",
                "offices":["office3", "sedge steward"],

                "tweets": 30,
                "friends": 150, 
                "followers": 300,
                "archipelago_id": 3,
开发者ID:condnsdmatters,项目名称:twirps,代码行数:69,代码来源:test_databasehandlers.py

示例5: Relationship

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import push [as 别名]
node_2_call_node_1 = Relationship(test_node_2, 'CALL', test_node_1)
node_2_call_node_1['count'] = 2
test_graph.create(node_1_call_node_2)
test_graph.create(node_2_call_node_1)
# 如以上代码,分别建立了test_node_1指向test_node_2和test_node_2指向test_node_1两条关系,关系的类型为"CALL",两条关系都有属性count,且值为1。

# 在这里有必要提一下,如果建立关系的时候,起始节点或者结束节点不存在,则在建立关系的同时建立这个节点。

# 四、节点/关系的属性赋值以及属性值的更新

# 节点和关系的属性初始赋值在前面节点和关系的建立的时候已经有了相应的代码,在这里主要讲述一下怎么更新一个节点/关系的属性值。

# 我们以关系建立里的 node_1_call_node_2 为例,让它的count加1,再更新到图数据库里面。

node_1_call_node_2['count'] += 1
test_graph.push(node_1_call_node_2)
# 更新属性值就使用push函数来进行更新即可。

# 五、通过属性值来查找节点和关系(find,find_one)

# 通过find和find_one函数,可以根据类型和属性、属性值来查找节点和关系。

find_code_1 = test_graph.find_one(
		label="Person",
		property_key="name",
		property_value="test_node_1"
)
print(find_code_1['name'])
# find和find_one的区别在于:
# find_one的返回结果是一个具体的节点/关系,可以直接查看它的属性和值。如果没有这个节点/关系,返回None。
# find查找的结果是一个游标,可以通过循环取到所找到的所有节点/关系。
开发者ID:gswyhq,项目名称:hello-world,代码行数:33,代码来源:neo4j使用实例.py

示例6: Node

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import push [as 别名]
graph.schema.create_uniqueness_constraint("Album", "slug")
# graph.schema.create_uniqueness_constraint("Word", "slug")
# graph.schema.create_uniqueness_constraint("Genre", "slug")

for i,r in df.iterrows():

    s_id = r['spotify_id']
    cover = r['albumcover']
    artist = r['artist_column']
    album = r['album_column']
    slug = r['slug_column']
    print [album]
    album = Node('Album', name = album, artist = artist, albumcover = cover, s_id = s_id, slug = slugify(slug))
    graph.create(album)
    graph.push()

    if pd.Series(r['genre_column']).any():
        for each in r['genre_column']:
            genre = graph.find_one('Genre', 'slug', slugify(each[0]))
            if not genre:
                genre = Node('Genre', name=each[0], slug=slugify(each[0]))
            rel = Relationship(album, 'Performs', genre, dist=each[1])
            graph.create(rel)
    for value in zip(r.index[5:],r[5:]):
        if value[1] != 1:
            word = graph.find_one('Word', 'slug', slugify(value[0]))
            if not word:
                word = Node('Word', name=value[0], slug=slugify(value[0]))
            rel = Relationship(word, 'Describes', album, dist=value[1])
            graph.create(rel)
开发者ID:rlkelly,项目名称:CAPSTONE,代码行数:32,代码来源:populatemoody.py

示例7: Graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import push [as 别名]
class Graph(object):
    def __init__(self, neo4j_uri):
        self.graph = NeoGraph(neo4j_uri)
        self.nodes = Nodes(self.graph)
        self.links = Links(self.graph)

    def create_user(self, args):
        node = self.nodes.find("User", args["username"])
        if not node:
            passhash = Authenticate.hashgen(args["username"], args["password"])
            properties = dict(
                node_id=args["username"],
                name=args["name"],
                city=args["city"],
                passhash=passhash
            )
            node = Node("User", **properties)
            self.graph.create(node)
            return node, True
        return node, False

    def user_rank(self, args, node_type):
        # success = False
        # errors = []

        user = self.nodes.find("User", args["user_id"])
        if not user:
            return False, "invalid user_id"

        node = self.nodes.find(node_type, args["node_id"])
        if not node:
            return False, "invalid node_id"

        link = self.links.find(user, node, "RANKS")
        if link and ("issue_id" not in args or
                     link.properties["issue_id"] == args["issue_id"]):
            link.properties["rank"] = args["rank"]
            link.push()
        else:
            properties = {"rank": args["rank"]}
            if "issue_id" in args:
                properties["issue_id"] = args["issue_id"]
            self.graph.create(Relationship(user, "RANKS", node, **properties))

        return True, ""

    def user_map(self, args, src_node, dst_node):
        # TODO refactor this into smaller units

        # success = False
        errors = []

        # retrieve nodes and existing links
        user = self.nodes.find("User", args["user_id"])
        if not user:
            errors.append("invalid user_id")
        src = self.nodes.find(src_node, args["src_id"])
        if not src:
            errors.append("invalid src_id")
        dst = self.nodes.find(dst_node, args["dst_id"])
        if not dst:
            errors.append("invalid dst_id")
        src_link = self.links.find(user, src, "RANKS")
        if not src_link:
            errors.append("user has not ranked src_node")
        dst_link = self.links.find(user, dst, "RANKS")
        if not dst_link:
            errors.append("user has not ranked dst_node")
        if errors:
            return False, ", ".join(errors)

        src_rank = src_link.properties["rank"]
        dst_rank = dst_link.properties["rank"]

        # fetch map node or create if it doesn't exist
        map_id = "{0}-{1}".format(args["src_id"], args["dst_id"])
        map_node = self.nodes.find("Map", map_id)
        if not map_node:
            properties = dict(node_id=map_id)
            map_node = Node("Map", **properties)
            self.graph.create(map_node)
            self.graph.create(Relationship(src, "MAPS", map_node, **{}))
            self.graph.create(Relationship(map_node, "MAPS", dst, **{}))

        user_map_link = self.links.find(user, map_node, "MAPS")
        if user_map_link:
            # link already exists, update strength
            user_map_link.properties["strength"] = args["strength"]
            user_map_link.properties["src_rank"] = src_rank
            user_map_link.properties["dst_rank"] = dst_rank
            self.graph.push()
        else:
            # create new link from user to map node
            properties = dict(
                strength=args["strength"],
                src_rank=src_rank,
                dst_rank=dst_rank
            )
            self.graph.create(Relationship(user, "MAPS", map_node, **properties))

#.........这里部分代码省略.........
开发者ID:midnightlynx,项目名称:dlab-api,代码行数:103,代码来源:graph.py


注:本文中的py2neo.Graph.push方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。