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


Python Graph.create_unique方法代码示例

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


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

示例1: import_api_data2

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
def import_api_data2():
    authenticate("localhost:7474", "neo4j", "1111")
    graph = Graph()
    #graph.delete_all()

    # Uncomment on the first run!
    #graph.schema.create_uniqueness_constraint("Borjnuk", "id")
    #graph.schema.create_uniqueness_constraint("Obtaj", "id")
    #graph.schema.create_uniqueness_constraint("Property", "id")

    obtajenna = get_objects_art('obtaj')

    for api_obtaj in obtajenna:

        node_obtaj= graph.merge_one("Obtaj", "id", api_obtaj["id"])
        node_obtaj["reason_doc"] = api_obtaj["reason_doc"]
        node_obtaj["cost_size"] = api_obtaj["cost_size"]

        for api_author in api_obtaj["borjnuku"]:
            node_borjnuk = graph.merge_one("Borjnuk", "id", api_author["id"])
            node_borjnuk["name"] = api_author["name"]
            node_borjnuk["tel_number"] = api_author["tel_number"]
            node_borjnuk.push()
            graph.create_unique(Relationship(node_borjnuk, "obtajuetsa", node_obtaj))

        for api_property in api_obtaj["properties"]:
            node_property = graph.merge_one("Property", "id", api_property["id"])
            node_property["name"] = api_property["name_property"]
            node_property["ser_number"] = api_property["ser_number"]
            node_property.push()
            graph.create_unique(Relationship(node_property, "zakladena", node_obtaj))
        node_obtaj.push()
开发者ID:wlagur,项目名称:lab2_melach,代码行数:34,代码来源:neo4j.py

示例2: import_api_data

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
def import_api_data():
    """
    imports data from my register (method and all adjacent) into graph DB
    """

    graph = Graph()
    # Uncomment on the first run!
    # graph.schema.create_uniqueness_constraint("Method", "id")
    # graph.schema.create_uniqueness_constraint("Author", "id")
    # graph.schema.create_uniqueness_constraint("Category", "id")

    methods = get_objects('method')

    for api_method in methods:

        node_method = graph.merge_one("Method", "id", api_method["id"])
        node_method["name"] = api_method["name"]
        node_method["creation_date"] = api_method["creation_date"]
        node_method["approval_date"] = api_method["approval_date"]

        for api_author in api_method["authors"]:
            node_author = graph.merge_one("Author", "id", api_author["id"])
            node_author["name"] = api_author["name"]
            node_author.push()
            graph.create_unique(Relationship(node_author, "WROTE", node_method))

        api_category = api_method["category"]
        node_category = graph.merge_one("Category", "id", api_category["id"])
        node_category["name"] = api_category["name"]
        node_category.push()
        graph.create_unique(Relationship(node_category, "CONTAINS", node_method))
        node_method.push()
开发者ID:reniwiner,项目名称:Register_API_handler,代码行数:34,代码来源:neo4j.py

示例3: VbplPipeline

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
class VbplPipeline(object):
	def __init__(self):
		authenticate("localhost:7474", "neo4j", "123456")
		self.graph = Graph()
	def process_item(self, item, spider):
		document = item['document']
		histories = item['histories']
		related_documents = item['related_documents']

		# Create document node
		document_node = self.graph.merge_one("LegalNormativeDocument", "id", document['document_id'])
		document_node.properties['content'] = document.get('content', '')
		document_node.properties['title'] = document.get('title','')
		document_node.properties['official_number'] = document.get('official_number','')
		document_node.properties['legislation_type'] = document.get('legislation_type','')
		document_node.properties['source'] = document.get('source','')
		document_node.properties['department'] = document.get('department', '')
		document_node.properties['issuing_office'] = document.get('issuing_office', '')
		document_node.properties['effective_area'] = document.get('effective_area','')
		document_node.properties['effective_date'] = document.get('effective_date', '')
		document_node.properties['gazette_date'] = document.get('gazette_date', '')
		document_node.properties['field'] = document.get('field', '')
		document_node.properties['signer_title'] = document.get('signer_title', '')
		document_node.properties['signer_name'] = document.get('signer_name', '')
		document_node.push()


		for history in histories:
			history_node = self.graph.merge_one("History", "id", history['history_id'])
			# history_node.properties['document_id'] = history['document_id']
			history_node.properties['title'] = history.get('title', '')
			history_node.properties['date'] = history.get('date', '')
			history_node.properties['status'] = history.get('status', '')
			history_node.properties['original_document'] = history.get('original_document', '')
			history_node.properties['ineffective_part'] = history.get('ineffective_part', '')
			history_node.push()

			# Add 'HAS' relationship
			self.graph.create_unique(Relationship(document_node, "HAS", history_node))

		for related_document in related_documents:
			# related_document_node.properties['document_id'] = related_document['document_id']
			related_document_node = self.graph.merge_one("RelatedDocument", "id", related_document['related_document_id'])
			related_document_node.properties['title'] = related_document.get('title', '')
			related_document_node.properties['relating_type'] = related_document.get('relating_type', '')
			related_document_node.push()

			# Add "HAS" relationship
			self.graph.create_unique(Relationship(document_node, "HAS", related_document_node))

		return item
开发者ID:BienTuanAnh,项目名称:VbplScrapy,代码行数:53,代码来源:pipelines.py

示例4: import_api2_data

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
def import_api2_data():
    """
    imports data from second register (experts and all adjacent)

    """
    graph = Graph()
    # Uncomment on first run!
    # graph.schema.create_uniqueness_constraint("Expert", "id")
    # graph.schema.create_uniqueness_constraint("Document", "id")
    # graph.schema.create_uniqueness_constraint("Comission_order", "id")
    # graph.schema.create_uniqueness_constraint("Legal_issue", "id")
    # graph.schema.create_uniqueness_constraint("Expertise", "id")

    experts = get_objects2("experts")

    for api_expert in experts:
        node_expert = graph.merge_one("Expert", "id", api_expert["id"])
        node_expert["name"] = api_expert["name"]
        node_expert["workplace"] = api_expert["workplace"]
        node_expert["address"] = api_expert["address"]
        node_expert["phone"] = api_expert["phone"]

        for api_document in api_expert["documents"]:
            node_document = graph.merge_one("Document", "id", api_document["id"])
            node_document["id_doc"] = api_document["id_doc"]
            node_document["release_date"] = api_document["release_date"]
            node_document["expiry_date"] = api_document["expiry_date"]
            node_document["document_type"] = api_document["document_type"]
            node_document.push()
            graph.create_unique(Relationship(node_expert, "SIGNED", node_document))

        for api_order in api_expert["commission_orders"]:
            node_order = graph.merge_one("Comission_order", "id", api_order["id"])
            node_order["commission_name"] = api_order["commission_name"]
            node_order["order_number"] = api_order["order_number"]
            node_order["order_date"] = api_order["order_date"]
            node_order.push()
            graph.create_unique(Relationship(node_order, "APPOINTED", node_expert))

            for api_expertise in api_order["expertises"]:
                node_expertise = graph.merge_one("Category", "id", api_expertise["id"])
                node_expertise["name"] = node_expertise["name"]
                node_expertise.push()
                graph.create_unique(Relationship(node_order, "INCLUDES", node_expertise))





        for api_issue in api_expert["legal_issues"]:
            node_issue = graph.merge_one("Legal_issue", "id", api_issue["id"])
            node_issue["description"] = api_issue["description"]
            node_issue["date"] = api_issue["date"]
            node_issue.push()
            graph.create_unique(Relationship(node_expert, "WORKED_ON", node_issue))



        node_expert.push()
开发者ID:reniwiner,项目名称:Register_API_handler,代码行数:61,代码来源:neo4j.py

示例5: StuffNeo4j

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
class StuffNeo4j():
    
    def __init__(self, nodelabel, reltype):
        self.graph_db = None
        self.nodelabel = nodelabel
        self.reltype = reltype
        
    def connect(self, uri, usr="neo4j", pwd="neo4j"):
        if not uri.endswith('/'):
            uri += '/'
        authenticate(uri, usr, pwd)
        self.graph_db = Graph(uri + "db/data")
        
    def create_indexes(self):
        #If index is already created py2neo throws exception.
        try:
            self.graph_db.cypher.execute("CREATE INDEX ON :%s(name)" % 
                self.nodelabel)
        except:
            pass
        try:
            self.graph_db.cypher.execute("CREATE INDEX ON :%s(synset_id)" % 
                self.nodelabel)
        except:
            pass
        try:
            self.graph_db.cypher.execute("CREATE INDEX ON :%s(pointer_symbol)" %
                self.reltype)
        except:
            pass
    
    def create_node(self, nodetype, **kwargs):
        return Node(nodetype, **kwargs)
        
    def merge_node(self, nodetype, uniq_key, uniq_val, **kwargs):
        n = self.graph_db.merge_one(nodetype, uniq_key, uniq_val)
        for k in kwargs:        
            n.properties[k] = kwargs[k]
        n.push()
        return n
   
    def insert_rel(self, reltype, node1, node2, **kwargs):
        if node1 is not None and node2 is not None: 
            rel = Relationship(node1, reltype, node2, **kwargs)
            self.graph_db.create(rel)
        else:
            print "Could not insert relation (%s) - [%s] -> (%s)" % (           
                node1, reltype, node2)
            
    def merge_rel(self, reltype, node1, node2, **kwargs):
        if node1 is not None and node2 is not None: 
            rel = Relationship(node1, reltype, node2, **kwargs)
            return self.graph_db.create_unique(rel)
        else:
            print "Could not merge relation (%s) - [%s] -> (%s)" % (           
                node1, reltype, node2)
    
    def create_wordnet_rel(self, synset1, synset2, ptype):
        """
        Pointer symbols
        http://wordnet.princeton.edu/wordnet/man/wninput.5WN.html
        
         The pointer_symbol s for nouns are:
        
            !    Antonym
            @    Hypernym
            @i    Instance Hypernym
             ~    Hyponym
             ~i    Instance Hyponym
            #m    Member holonym
            #s    Substance holonym
            #p    Part holonym
            %m    Member meronym
            %s    Substance meronym
            %p    Part meronym
            =    Attribute
            +    Derivationally related form        
            ;c    Domain of synset - TOPIC
            -c    Member of this domain - TOPIC
            ;r    Domain of synset - REGION
            -r    Member of this domain - REGION
            ;u    Domain of synset - USAGE
            -u    Member of this domain - USAGE
        
        The pointer_symbol s for verbs are:
        
            !    Antonym
            @    Hypernym
             ~    Hyponym
            *    Entailment
            >    Cause
            ^    Also see
            $    Verb Group
            +    Derivationally related form        
            ;c    Domain of synset - TOPIC
            ;r    Domain of synset - REGION
            ;u    Domain of synset - USAGE
        
        The pointer_symbol s for adjectives are:
        
#.........这里部分代码省略.........
开发者ID:leotop,项目名称:wordnet2neo4j,代码行数:103,代码来源:neo4jstuff.py

示例6: GraphModule

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

    # db path TODO make this a parameter
    db_path = "http://neo4j:[email protected]:7474/db/data/"
    db = None
    valid_relations = ["is", "can", "similar", "describes", "likes", "dislikes"]

    def __init__(self, name):
        NaoModule.__init__(self, name)
        self.graph = Graph(self.db_path)

    def exit(self):
        NaoModule.exit(self)

    def add_constraints(self):
        self.add_constraint("Concept", "name")
        self.add_constraint("Trait", "name")
        self.add_constraint("Action", "name")

    def add_constraint(self, label, property):
        self.__add_constraint(label, property)

    def __add_constraint(self, label,property):
        try:
            self.graph.schema.create_uniqueness_constraint(label, property)
            print("%s:%s constraint created" % (label,property))
        except:
            print("%s:%s constraint already exists" % (label,property))

    # --------------------------- Add / Remove Nodes and Relationships ------------------- #

    # -- Assign a thing to a parent thing (or remove)

    def try_parse_relationship(self, text):
        params = map(lambda p: p.trim()), text.lower().split("--")

        if len(params) < 3:
            print("invalid relation use the form 'rel -- concept -- concept'")
            return None

        if self.valid_relations.count(params[0]) == 0:
            print("invalid relationship should be one of " + ', '.join(self.valid_relations))
            return None

        return params

    def relate_concepts(self, concept1, concept2, rel, label="Concept"):

        if self.valid_relations.count(rel) == 0:
            print("invalid relationship should be one of " + ', '.join(self.valid_relations))
            self.add_relationship(label, concept1, rel, label, concept2)

    def unrelate_concepts(self, text, label="Concept"):
        params = self.try_parse_relationship(text)

        if params is not None:
            rel, concept1, concept2 = params
            self.remove_relationship(label, concept1, rel, label, concept2)

    # -- Add a node (or remove)
    def add_concept(self, name, label="Concept"):
        return self.graph.cypher.execute_one("Merge(n:%s {name: '%s'}) return n" % (label, name))

    # -- Add a relationship to two nodes
    def add_relationship(self, label1, name1, rel, label2, name2):
        """ add a relationship"""
        if rel == "can":
            label2 = label2 + ":" + "Action"
        elif rel == "describes":
            label1 = label1 + ":" + "Trait"

        n = self.graph.cypher.execute_one("Merge(n:%s {name: '%s'}) return n" % (label1, name1))
        r = self.graph.cypher.execute_one("Merge(n:%s {name: '%s'}) return n" % (label2, name2))

        return self.graph.create_unique(Relationship(n, rel, r))

    # -- remove a relationship from two nodes
    def remove_relationship(self, label1, name1, rel, label2, name2):
        r = Relationship(Node(label1, "name", name1), rel, Node(label2, "name", name2))
        self.graph.delete(r)

    # ----------------------------------------------------------------------------
    # Query nodes for relationships and abilities
    # ----------------------------------------------------------------------------

    # -- get definition of a thing by finding its parents
    def what_is(self, name, neighbors=3):
        stmt = "MATCH (n:Concept { name: '%s' })-[:is*1..%s]->(neighbors) RETURN neighbors.name as name" % (name, neighbors)
        return map(lambda x: x.name.encode('utf-8'), self.graph.cypher.execute(stmt))

    # -- ask whether a thing is another thing by inheritance
    def is_it(self, name, parent):
        statement = "match p=shortestPath((a:Concept {name:'%s'})-[:IS_A*1..2]->(b:Concept {name:'%s'})) return p" % (name, parent)
        return self.graph.cypher.execute_one(statement) is not None

    # -- show examples of a thing through its children
    def instances_of(self, name):
        """ Get instances of (children of) a concept """
        stmt = "MATCH (n:Concept { name: '%s' })<-[:is*1..2]-(neighbors) RETURN neighbors.name as name" % name
        return map(lambda x: x.name.encode('utf-8'), self.graph.cypher.execute(stmt))
#.........这里部分代码省略.........
开发者ID:kevywilly,项目名称:nao,代码行数:103,代码来源:graph.py

示例7: Relationship

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
        #Create color node and relationship
        color_node = graph.merge_one('Color', 'Color', color)
        node_rel_dest = Relationship(node, "HAS_COLOR", color_node)
        graph.create_unique(node_rel_dest)
    """

# main

# Create nodes and relationship between category and sub-category

graph.delete_all()

parent_cat_node = graph.merge_one('Category', 'product_category', 'Mobiles & Tablets')
sub_cat_node = graph.merge_one('Category', 'product_sub_category', 'Mobile Phones')
node_rel_dest = Relationship(sub_cat_node, "SUB_CAT_OF", parent_cat_node)
graph.create_unique(node_rel_dest)

for d in data:
    rec = d['record']
    if not rec['product_name'] or not rec['uniq_id']:
        logging.info ("Incomplete product ... skipping")
        logging.debug(rec)
        continue
    else:
        node = createProductNode(rec)
        addNodeProperties(node, rec)
        node.push()
    
    for k,v in rec.iteritems():
        if k in keys:
            #Create relationship between product and sub-cat
开发者ID:Diwahars,项目名称:python-scripts-1,代码行数:33,代码来源:test_fk.py

示例8: AgoraGoal

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
class AgoraGoal(object):
    def __init__(self, graph_db):
        self.title = None
        self.unique_id = None
        self.description = None
        self.start_date = None
        self.end_date = None
        self.interests = []
        self.achievements = []
        self.graph_db = Graph()

    @property
    def goal_node(self):
        """
        get a single goal node based on the attributes of the goal
        :return: neo4j.Node
        """
        goal_node = self.graph_db.find_one(AgoraLabel.GOAL,
                                           property_key='unique_id',
                                           property_value=self.unique_id)
        return goal_node

    @property
    def goal_interests(self):
        goal_interests = self.graph_db.match(start_node=self.goal_node,
                                             rel_type=AgoraRelationship.GOAL_INTEREST,
                                             end_node=None)
        goal_interests_list = []
        for item in goal_interests:
            goal_interests_list.append((item["name"], item["description"]))

        return goal_interests_list

    def create_goal(self):
        """
        create a goal and relate to user
        :return: neo4j.Node
        """
        # goal_node = self.get_goal() #TO GO get goal to prevent duplication?  maybe not needed -- MMMD 11/12/2014
        # if goal_node is None:
        self.unique_id = str(uuid.uuid4())
        new_goal_properties = {
            "title": self.title,
            "description": self.description,
            "unique_id": self.unique_id,
            "start_date": self.start_date,
            "end_date": self.end_date}
        new_goal = Node.cast(AgoraLabel.GOAL, new_goal_properties)
        return new_goal

    def update_goal(self):
        """
        update goal related to user
        :return:
        """
        pass

    def link_goal_to_achievement(self):
        pass

    def add_interest(self, interest_node):
        goal_interest_relationship = Relationship(start_node=self.goal_node,
                                                  rel=AgoraRelationship.GOAL_INTEREST,
                                                  end_node=interest_node)
        self.graph_db.create_unique(goal_interest_relationship)
        return

    def get_goal(self):
        pass

    def delete_goal(self):
        pass
开发者ID:julianpistorius,项目名称:agora-development,代码行数:74,代码来源:py2neo_goal.py

示例9: Node

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
                item = Node('Item', label, item_id = id, title = obj['title'], tmdb_id = obj['id'], imdb_id = obj['imdb_id'], language = obj['original_language'], overview = obj['overview'], poster_path = obj['poster_path'], release_date = obj['release_date'], runtime = obj['runtime'])

            cur.execute("INSERT INTO Title VALUES(?, ?, ?, ?)", (obj['title'], id, obj['poster_path'], obj['release_date'].split('-')[0]))
            # no_genre_counter = no_genre_counter + 1

            # add item to server with create
            try:
                graph.create(item)
            except Exception as e:
                print e.message
                continue

            for genre in obj['genres']:
                if genre['name'] not in genre_dict:
                    new_genre = Node("Genre", tmdb_id = genre['id'], name = genre['name'])
                    graph.create(new_genre)
                    genre_dict[genre['name']] = new_genre
                genre_rel = Relationship(item, 'OF_GENRE', genre_dict[genre['name']])
                graph.create_unique(genre_rel)

            # print json.dumps(obj, indent=4, sort_keys=True)

            counter = counter + 1
            # for debug
            #if counter == 100:
            #    break

cur.close()
con.close()
print counter
开发者ID:TheMongos,项目名称:recomate,代码行数:32,代码来源:title-neo4j-sqlite.py

示例10: Organization

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

#.........这里部分代码省略.........
    def org_interests(self):
        org_interests = self._graph_db.match(start_node=self.org_node,
                                            rel_type=GraphRelationship.INTERESTED_IN,
                                            end_node=None)
        interests_list = []
        for rel in org_interests:
            interests_list.append(dict(rel.end_node.properties))
        return interests_list

    @property
    def org_locations(self):
        """
        list of locations for the org
        :return: list
        """
        locations = self._graph_db.match(start_node=self.org_node,
                                         rel_type=GraphRelationship.LOCATED_IN,
                                         end_node=None)
        locations_list = []
        for rel in locations:
            locations_list.append(dict(rel.end_node.properties))
        return locations_list

    @property
    def org_members(self):
        """
        list of users.  user is a dictionary of properties
        list of the members of the organization
        :return: list of tuple of member name, email
        """
        org_members_nodes = self._graph_db.match(start_node=self.org_node,
                                                rel_type=GraphRelationship.MEMBER_OF,
                                                end_node=None)
        org_members_list = []
        for rel in org_members_nodes:
            org_members_list.append(dict(rel.end_node.properties))
            # org_members_list.append((item.end_node["name"], item.end_node["email"]))
        return org_members_list

    def set_organization_attributes(self, org_properties):
        for key, value in org_properties.iteritems():
            setattr(self, key, value)

    def get_organization(self):
        org_node = self.org_node
        org_properties = dict(org_node.properties)
        for key, value in org_properties.iteritems():
            setattr(self, key, value)

    def create_organization(self):
        """
        create a new organization
        :return: py2neo Node
        """
        self.id = str(uuid.uuid4())
        new_org_properties = self.org_properties
        new_org_node = Node.cast(GraphLabel.ORGANIZATION, new_org_properties)
        self._graph_db.create(new_org_node)

        return new_org_node

    def add_location(self, location_dict):
        """
        add location relationship to organization
        if location does not exist, create the location node and then create relationship
        :param location_dict:  dictionary object of location to add
        :return:
        """
        location = Location()
        location.id = location_dict['id']
        location_node = location.location_node_by_place_id
        if not location_node:
            location.set_location_properties(location_dict)
            location.create_location()
            location_node = location.location_node_by_place_id
        try:
            self._graph_db.create_unique(self.org_node, GraphRelationship.LOCATED_IN, location_node)
        except:
            pass  #TODO exception handling

    def add_interest(self, interest_id):
        interest = Interest()
        interest.id = interest_id
        interest_node = interest.interest_node_by_id
        org_interest_relationship = Relationship(self.org_node,
                                                 GraphRelationship.INTERESTED_IN,
                                                 interest_node)
        try:
            self._graph_db.create_unique(org_interest_relationship)
        except:
            pass
        return self.org_interests

    def organization_relationships_for_json(self):
        root = {}
        root = dict(self.org_properties)
        root['interests'] = self.org_interests
        root['members'] = self.org_members
        root['locations'] = self.org_locations
        return root
开发者ID:julianpistorius,项目名称:back-end-api,代码行数:104,代码来源:organization.py

示例11: open

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
from py2neo import Graph, Node, Relationship
import json

f = open('tt2.json', 'r')
jj = json.loads(f.read())
f.close()


graph = Graph('http://neo4j:[email protected]:7474/db/data')

for post in jj:
    poster = graph.merge_one("User", "id", post['poster'])
    neoPost = graph.merge_one("Post", "id", post['id'])
    posted = graph.create_unique(Relationship(poster, "POSTED", neoPost))
    print "(%s)-[:POSTED]->(%s)" % (post['poster'], post['id'])

    if post.get('reblogged_from'):
        reblogger = graph.merge_one("User", "id", post['reblogged_from'])
        reblogged_post = graph.merge_one("Post", "id", post['reblog_post_id'])
        graph.create_unique(Relationship(reblogger, "POSTED", reblogged_post))
        graph.create_unique(Relationship(neoPost, "REBLOG_OF", reblogged_post))
        print "(%s)-[:POSTED]->(%s)" % (post['reblogged_from'], post['reblog_post_id'])

    if post.get('original_poster'):
        original_poster = graph.merge_one("User", "id", post['original_poster'])
        original_post = graph.merge_one("Post", "id", post['original_post_id'])
        graph.create_unique(Relationship(original_poster, "POSTED", original_post))
        graph.create_unique(Relationship(neoPost, "ORIGINATES_FROM", original_post))
        print "(%s)-[:POSTED]->(%s)" % (post['original_poster'], post['original_post_id'])
开发者ID:mkapolka,项目名称:tummy,代码行数:31,代码来源:tummy_tuck.py

示例12: __init__

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
class Access:
    def __init__(self, events):
        config = Conf()
        authenticate(config.db_host, config.db_username, config.db_password)
        self.graph = Graph()
        self.events = events

    def is_unique_entry(self, entry):
        result = self.graph.find_one('entry', 'clean_url', entry.clean_url)
        if result is None:
            node = Node('entry', clean_url=entry.clean_url, raw_url=entry.raw_url, context=entry.context, searched=0)
            self.graph.create(node)
            return True
        else:
            return result.properties['searched'] == 0

    def mark_searched(self, entry):
        stmt = 'MATCH (found:entry {clean_url: {URL}, searched:0}) SET found.searched = 1'
        self.graph.cypher.execute_one(stmt, URL=entry.clean_url)

    def is_new_node(self, entry):
        if entry.next_entry is None:
            next_id = None
        else:
            next_id = entry.next_entry.id
        result = self.graph.find_one('node', 'self_id', entry.id)
        if result is None:
            self.events.on_creating_node()
            node = Node('node', clean_url=entry.clean_url, raw_url=entry.raw_url, context=entry.context,
                        next_id=next_id, self_id=entry.id, created=entry.created, created_utc=entry.created_utc,
                        source=entry.source_comment, html=entry.html_comment, title=entry.title, user=entry.user,
                        submission_id=entry.submission_id)
            self.graph.create(node)
            return node, False
        else:
            self.events.on_node_exists()
            return result, True

    def get_parents(self, entry):
        stmt = 'MATCH (found:node {next_id: {ID}}) return found'
        results = self.graph.cypher.execute(stmt, ID=entry.id)
        return results.to_subgraph().nodes

    def add_link(self, parent, child):
        if len(list(self.graph.match(start_node=parent, end_node=child, rel_type='linksTo'))) > 0:
            return False
        rel = Relationship(parent, 'linksTo', child)
        self.graph.create_unique(rel)
        return True

    def get_terminus(self, limit=100):
        stmt = 'MATCH (a:node) WHERE NOT (a)-[:linksTo]->() and (not has(a.broken) or a.broken = false) ' + \
               'return a LIMIT {LIM}'
        results = self.graph.cypher.execute(stmt, LIM=limit)
        return results.to_subgraph().nodes

    def get_entry(self, size):
        if size > 0:
            stmt = 'MATCH (found:entry {searched:0}) RETURN found LIMIT {LIM}'
            results = self.graph.cypher.execute(stmt, LIM=size)
        else:
            stmt = 'MATCH (found:entry {searched:0}) RETURN found'
            results = self.graph.cypher.execute(stmt)
        return results.to_subgraph().nodes

    def get_starts(self):
        stmt = 'MATCH (a:node) WHERE NOT ()-[:linksTo]->(a) RETURN a'
        results = self.graph.cypher.execute(stmt)
        return results.to_subgraph().nodes

    def get_next_nodes(self, node):
        stmt = 'MATCH (a:node)-[:linksTo]->(b:node) WHERE id(a) = {ID} RETURN b'
        results = self.graph.cypher.execute(stmt, ID=node._id)
        return results.to_subgraph().nodes

    @staticmethod
    def set_terminus(node):
        node['broken'] = True
        node.push()

    @staticmethod
    def update_parent_next(parent, entry):
        parent['next_id'] = entry.id
        parent.push()
开发者ID:admgrn,项目名称:Switcharoo,代码行数:86,代码来源:data.py

示例13: AgoraUser

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

#.........这里部分代码省略.........
        :return: list of interests
        """
        user_goals = self.graph_db.match(start_node=self.user_node, rel_type=AgoraRelationship.HAS_GOAL,
                                             end_node=None)
        #create a list of tuples of interests and the users's relationship to them
        goals_list = []
        for item in user_goals:
            goals_list.append((item.end_node["title"], item["description"]))
        # return [item.end_node["name"] for item in user_interests]
        return goals_list

    @property
    def user_groups(self):
        """

        :return: list of tuples of the groups
        """
        user_groups = self.graph_db.match(start_node=self.user_node, rel_type=AgoraRelationship.STUDIES_WITH,
                                             end_node=None)
        #create a list of tuples of interests and the users's relationship to them
        groups_list = []
        for item in user_groups:
            groups_list.append((item.end_node["name"], item["unique_id"]))
        # return [item.end_node["name"] for item in user_interests]
        return groups_list

    @property
    def user_orgs(self):
        """

        :return:
        """
        user_orgs = self.graph_db.match(start_node=self.user_node,
                                        rel_type=AgoraRelationship.MEMBER_OF,
                                        end_node=None)
        orgs_list = []
        for item in user_orgs:
            orgs_list.append(item.end_node["name"])
        return orgs_list

    def add_interest(self, interest_node):
        """ Add interest to user
        :param interest_node:py2neo Node
        :return: List of interests
        """
        user_interest_relationship = Relationship(start_node=self.user_node,
                                                  rel=AgoraRelationship.INTERESTED_IN,
                                                  end_node=interest_node)
        self.graph_db.create_unique(user_interest_relationship)
        return self.user_interests

    def update_user(self):
        pass

    def make_admin(self):
        #new_user = self.graph_db.get_or_create_indexed_node(index_name=AgoraLabel.USER, key='email', value=self.email)
        self.user_node.add_labels(AgoraLabel.ADMIN)

    def add_goal(self, goal_node, goal_relationship_properties=None):
        """
        Add goal to user
        :param goal_node: py2neo Node
        :return: List of user goals
        """
        #get user node with unique id
        # user_node = self.graph_db.get_or_create_indexed_node(index_name=AgoraLabel.USER,
        #                                                      key='email', value=self.email)
        #create relationship between user and interest node
        user_goal_relationship = Relationship(start_node=self.user_node,
                                              rel=AgoraRelationship.HAS_GOAL,
                                              end_node=goal_node)

        self.graph_db.create_unique(user_goal_relationship)
        #TODO set properties on the relationship -- may use a unique id as the key
        return self.user_goals

    def add_group(self, group_node, group_relationship_properties=None):
        """
        Add user as member of group
        :param group_node: py2neo Node
        :return:
        """

        user_group_relationship = Relationship(start_node=self.user_node,
                                               rel=AgoraRelationship.MEMBER_OF,
                                               end_node=group_node)
        self.graph_db.create_unique(user_group_relationship)
        #TODO set properties on the relationsip
        # group_relationship_properties["unique_id"] = str(uuid.uuid4())

    def add_organization(self, org_node):
        """
        add user to organization
        :param org_node: py2neo Node
        :return: list of tuple of interests
        """
        user_org_relationship = Relationship(start_node=self.user_node,
                                             rel=AgoraRelationship.MEMBER_OF,
                                             end_node=org_node)
        self.graph_db.create_unique(user_org_relationship)
开发者ID:julianpistorius,项目名称:agora-development,代码行数:104,代码来源:py2neo_user.py

示例14: Relationship

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
graph.cypher.execute(query, {
                            'profile': prof,
                            'favorite': fav
                            }
                    )

dennis = graph.find_one("soundcloud", "name", "Dennis")
emma = graph.find_one("soundcloud", "name", "Emma")

print dennis.properties, emma.properties

#graph.create(alice)
#graph.create(bob)
#graph.create(chelsea)
#bob, likes = graph.create({"name": "Bob"}, (alice, "likes", 0))
#chelsea, likes = graph.create({"name": "Chelsea"}, (alice, "likes", 0))

alice_likes_bob = Relationship(alice, "likes", bob, songs=["goodsong", "nicetune"])
alice_likes_chelsea = Relationship(alice, "likes", chelsea, songs = ['greatsong'])

graph.create_unique(alice_likes_bob)
graph.create_unique(alice_likes_chelsea)

alice_likes_chelsea['songs'] += ['awesometrack']

print alice_likes_chelsea.properties

for rel in graph.match(start_node=alice, rel_type="likes"):
    print rel.end_node["name"]
    print rel.properties
开发者ID:brokoro,项目名称:cloudchaser,代码行数:32,代码来源:cloudcypher.py

示例15: print

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import create_unique [as 别名]
    graph.schema.create_uniqueness_constraint("Company", "name")
    graph.schema.create_uniqueness_constraint("Fund", "name")
    graph.schema.create_uniqueness_constraint("Institute", "name")
    graph.schema.create_uniqueness_constraint("Person", "name")

    for row in bsm.rows[1:]:
      from_type, from_name, edge_type, edge_name, to_type, to_name, netlog = [cell.value for cell in row]
      if netlog is None:
        from_type = "grey"
        to_type = "grey"
      print(from_type, from_name, edge_type, to_type, to_name)
      from_node = graph.merge_one(from_type.strip(), "name", from_name.strip())
      to_node = graph.merge_one(to_type.strip(), "name", to_name.strip())
      from_to = Relationship(from_node, edge_type, to_node)
      graph.create_unique(from_to)

    # get nodes with degree
    nodes = []
    for label in graph.node_labels:
      for p in graph.find(label):
        node = {"id": p.ref.split("/")[-1],
                "label": p["name"], 
                "title": p["name"],
                "value": p.degree,
                "group": label}
        nodes.append(node)
    with open("report/nodesnetlog.js", "w") as f:
      f.write("var nodesraw = " + dumps(nodes, indent=2) + ";")

    # get edges
开发者ID:ruettet,项目名称:belgianstartupmaffia,代码行数:32,代码来源:bsm_netlog.py


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