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


Python Graph.delete方法代码示例

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


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

示例1: Graph

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

    def __init__(self, neo4j_uri):
        self.graph = NeoGraph(neo4j_uri)

    def find_node(self, label, node_id):
        args = dict(property_key="node_id", property_value=node_id)
        return self.graph.find_one(label, **args)

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

    def delete_user(self, user):
        node = self.find_node("User", user)
        if node:
            self.graph.delete(node)    
            return True
        return False
开发者ID:uym2,项目名称:dlab-api,代码行数:30,代码来源:graph.py

示例2: getTestedNeo4jDB

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import delete [as 别名]
def getTestedNeo4jDB(graphDBurl, graphDbCredentials):
    '''Gets a Neo4j url and returns a GraphDatabaseService to the database
    after having performed some trivial tests'''
    try:
        if graphDbCredentials:
            authenticate(*graphDbCredentials)
        graphDb = Graph(graphDBurl)
        #just fetch a Node to check we are connected
        #even in DRY RUN we should check Neo4j connectivity
        #but not in OFFLINE MODE
        if not OFFLINE_MODE:
            _ = iter(graphDb.match(limit=1)).next()
    except StopIteration:
        pass
    except SocketError as ex:
        raise DbNotFoundException(ex, "Could not connect to Graph DB %s."
                                  % graphDBurl)

    if not DRY_RUN and not OFFLINE_MODE:
        try:
            test_node = Node("TEST", data="whatever")
            graphDb.create(test_node)
            graphDb.delete(test_node)
        except Exception as ex:
            raise DBInsufficientPrivileges(\
                    "Failed on trivial operations in DB %s." % graphDBurl)

    return graphDb
开发者ID:lycofron,项目名称:pysql2neo4j,代码行数:30,代码来源:graph.py

示例3: connect

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import delete [as 别名]
        def connect(login_, password_, host_port_):
            # global graph allows to get the same graph every time init_db() is called
            authenticate(host_port_, login_, password_)

            if host_port_ == "localhost:7474":
                graph_con = Graph()
            else:
                graph_con = Graph("http://"+host_port_+"/db/data/")

            node = Node("TestNodeToRemove", name="Alice", age="23", eyes="blue")
            try:
                graph_con.create(node)
                graph_con.delete(node)
            except Unauthorized:
                graph_con = None

            return graph_con
开发者ID:echinopsii,项目名称:net.echinopsii.ariane.community.relmgr,代码行数:19,代码来源:graphDBFabric.py

示例4: before_all

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import delete [as 别名]
def before_all(context):
    # import falcon_test
    # context.attachment_dir = os.path.join(os.path.dirname(falcon_test.__file__), 'tests/data')
    # context.sms_path = os.path.join(os.path.dirname(falcon_test.__file__), '../../var/sms/')
    # context.mail_path = os.path.join(os.path.dirname(falcon_test.__file__), '../../var/mail/')
    # clear database
    graph_db = Graph(settings.DATABASE_URL)
    # graph_db.delete_all()
    new_user_node = graph_db.find_one('USER',
                                      property_key='email',
                                      property_value='[email protected]')
    graph_db.delete(new_user_node)
    interest_node = graph_db.find_one('INTEREST', property_key='name',
                                      property_value=PERSONAS['interest']['name'])
    interest_relationships = graph_db.match(start_node=None,
                                            rel_type='INTERESTED_IN',
                                            end_node=interest_node)
    for relationship in interest_relationships:
        graph_db.delete(relationship)
    graph_db.delete(interest_node)
    context.base_url = "http://localhost:8000"
    benv.before_all(context)
开发者ID:julianpistorius,项目名称:back-end-api,代码行数:24,代码来源:environment.py

示例5: __init__

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import delete [as 别名]
class GraphDB:
    class SimpleNode:
        def __init__(self, node):
            self.name = node["name"].encode("utf-8")
            labels = map(lambda l: l.encode("utf-8"), node.labels)
            self.label = filter(lambda l: l != "Concept", labels)[0]

    db_path = "http://neo4j:[email protected]:7474/db/data/"

    graph = None

    interactions = ["Request", "Engagement", "Exploration", "Judgement", "Share", "Disengagment", "Unknown"]
    sentiments = ["Positive", "Neutral", "Negative", "Unknown"]

    def __init__(self):
        self.graph = Graph(self.db_path)

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

    def add_index(self, label, property):
        self.__add_index(label, property)

    def __add_index(self, label, property):
        try:
            self.graph.cypher.execute(("CREATE INDEX ON :%s(%s)") % (label, property))
            print("%s:%s index created" % (label, property))
        except:
            print("%s:%s constraint already exists" % (label, property))

    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))

    def add_unique_constraint(self, name, attr):
        self.graph.schema.create_uniqueness_constraint(name, attr)

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

    # -- Assign a thing to a parent thing (or remove)
    def assign_parent(self, label, name, parent, remove=False):
        if remove is True:
            return self.remove_relationship(label, name, "IS_A", label, parent)
        else:
            return self.add_relationship(label, name, "IS_A", label, parent)

    # -- Assign similarity between two things (or remove)
    def assign_similar(self, label, name, similar, remove=False):
        if remove is True:
            return self.remove_relationship(label, name, "SIMILAR_TO", label, similar)
        else:
            return self.add_relationship(label, name, "SIMILAR_TO", label, similar)

    # -- Assign an ability (action) to a thing (or remove)
    def assign_ability(self, name, a_name, remove=False):
        if remove is True:
            return self.remove_relationship("Concept", name, "CAN", "Action", a_name)
        else:
            return self.add_relationship("Thing", name, "CAN", "Action", a_name)

    # -- Add a node (or remove)
    def add_node(self, label, name, remove=False):
        if remove is True:
            return self.delete(Node(label, "name", name))
        else:
            return self.graph.cypher.execute_one("Merge(n:Concept:%s {name: '%s'}) return n" % (label, name))

    # -- Assign a trait to a thing (or remove)
    def assign_trait(self, thing, trait, remove=False):
        if remove is True:
            return self.remove_relationship("Trait", trait, "DESCRIBES", "Thing", thing)
        else:
            return self.add_relationship("Trait", trait, "DESCRIBES", "Thing", thing)

    # -- Assign a sense to a thing
    def assign_sense(self, thing, sense, remove=False):
        if remove is True:
            return self.remove_relationship("Thing", thing, "HAS", "Sense", sense)
        else:
            return self.add_relationship("Thing", thing, "HAS", "Sense", sense)

    # -- Add a relationship to two nodes
    def add_relationship(self, label, name, rel, r_label, r_name):
        """
        Add a relationship
        :param a_label:
        :param a_name:
        :param rel:
        :param b_label:
        :param b_name:
        :return:
#.........这里部分代码省略.........
开发者ID:kevywilly,项目名称:nao,代码行数:103,代码来源:database.py

示例6: TwitterGraph

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

    def __init__(self):
        self.graph = Graph("http://neo4j:[email protected]:7474/db/data/")
        self.popularity_heap = []
        self.reassess_popularity()

    def add_user(self, user):
        new_user = Node("User", token=user.token.session_id, user_id=user.id)
        return self.graph.create(new_user)

    def is_cached(self, screen_name):
        twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)
        if twitter_user is not None:
            return True

    def get_RT_recommendations(self, user):
        recommendations = Counter()
        user_node = self.graph.find_one("User", 'user_id', user.id)
        following = user_node.match_outgoing("FOLLOWS", limit=5)

        for rel in following:
            retweets = rel.end_node.match_outgoing("RETWEETED", limit=5)
            for r in retweets:
                recommendations[r.end_node.properties['screen_name']] += 1

        return [str for (str, count) in recommendations.most_common(10)]

    def get_generic_recommendations(self):
        return [screen_name for (count, screen_name) in heapq.nlargest(10, self.popularity_heap)]

    def reassess_popularity(self):
        # NOTE: expensive calculation, to be run threaded at multiples of x actions to graph or hourly/daily job
        all_twitter_users = self.graph.find("TwitterUser")
        for tu in all_twitter_users:
            incoming_count = sum(1 for _ in tu.match_incoming())
            heapq.heappush(self.popularity_heap, (incoming_count, tu.properties['screen_name']))

    def add_twitter_user(self, screen_name):
        twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)
        if twitter_user is None:
            new_twitter_user = Node("TwitterUser", screen_name=screen_name)
            self.graph.create(new_twitter_user)

    def add_follow(self, screen_name, user):
        user_node = self.graph.find_one("User", 'user_id', user.id)
        if user_node is None:
            # this shouldn't happen, just for testing while transitioning db
            self.add_user(user)
            user_node = self.graph.find_one("User", 'user_id', user.id)

        twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)
        if twitter_user is None:
            # this shouldn't happen, just for testing while transitioning db
            self.add_twitter_user(screen_name)
            twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)

        follow_relationship = Relationship(user_node, "FOLLOWS", twitter_user)
        self.graph.create(follow_relationship)
        self.reassess_popularity()

    def remove_follow(self, screen_name, user):
        user_node = self.graph.find_one("User", 'user_id', user.id)
        if user_node is None:
            # this shouldn't happen, just for testing while transitioning db
            self.add_user(user)
            user_node = self.graph.find_one("User", 'user_id', user.id)

        twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)
        if twitter_user is None:
            # this shouldn't happen, just for testing while transitioning db
            self.add_twitter_user(screen_name)
            twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)

        follow_relationship = self.graph.match_one(user_node, "FOLLOWS", twitter_user)
        if follow_relationship is not None:
            self.graph.delete(follow_relationship)

    def add_retweet(self, screen_name, retweeted_screen_name):
        twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)
        if twitter_user is None:
            # this shouldn't happen, just for testing while transitioning db
            self.add_twitter_user(screen_name)
            twitter_user = self.graph.find_one("TwitterUser", 'screen_name', screen_name)

        self.add_twitter_user(retweeted_screen_name)
        retweeted_twitter_user = self.graph.find_one("TwitterUser", 'screen_name', retweeted_screen_name)

        retweet = self.graph.match_one(twitter_user, "RETWEETED", retweeted_twitter_user)
        if retweet is None:
            retweet_relationship = Relationship(twitter_user, "RETWEETED", retweeted_twitter_user)
            retweet_relationship.properties['count'] = 1
            self.graph.create(retweet_relationship)
        elif retweet.properties['count'] is None:
            # this shouldn't happen, just for testing while transitioning db
            retweet.properties['count'] = 1
            retweet.push()
        else:
            retweet.properties['count'] = retweet.properties['count'] + 1
            retweet.push()
开发者ID:zsaraf,项目名称:tweed_django,代码行数:102,代码来源:graph.py

示例7: str

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import delete [as 别名]
#    has_contrast = models.Relationship(Contrast,rel_type='HASCONTRAST')

for row in conditions.iterrows():
    name = row[1].condition_text
    user = row[1].id_user
    uid = row[1].id
    task = row[1].id_term
    description = row[1].condition_description
    timestamp = row[1].event_stamp    
    if not str(name) =="nan":
        properties = {"description":description}
        node = make_node("condition",uid,name,properties)
        tasknode = find_node("task",property_value=task)
        # If the tasknode is node found, then we do not create the relation, and we delete the condition
        if tasknode == None:
            graph.delete(node)
        else:
            relation = make_relation(tasknode,"HASCONDITION",node)


#class Disorder(models.NodeModel):
#    has_difference = models.Relationship(Contrast,rel_type='HASDIFFERENCE')
#    mentioned_in = models.Relationship('PMID',rel_type='MENTIONEDIN')

disorders.columns = ["id","term","classification"] # Bug in returning column index name
for row in disorders.iterrows():
    uid = row[1].id
    classification = row[1].classification
    name = row[1].term
    properties = {"classification":classification}
    node = make_node("disorder",uid,name,properties)
开发者ID:rwblair,项目名称:cogat-docker,代码行数:33,代码来源:migrate_database.py

示例8: GraphModule

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import delete [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

示例9: User

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

#.........这里部分代码省略.........
        return interest_users_dict

    def add_interest(self, interest_id, experience_properties_dict=None):
        """ Add interest to user
        :param interest id:string uuid
        :return: List of interests
        """
        #TODO add exception handling
        interest = Interest()
        interest.id = interest_id
        interest_node = interest.interest_node_by_id
        user_interest_relationship = Relationship(self.user_node,
                                                  GraphRelationship.INTERESTED_IN,
                                                  interest_node)
        for key, value in experience_properties_dict.iteritems():
            user_interest_relationship[key] = value
        try:
            self._graph_db.create_unique(user_interest_relationship)
        except:
            pass
        return self.user_interests

    def update_interest(self, interest_id, experience_properties_dict):
        interest = Interest()
        interest.id = interest_id
        interest_node = interest.interest_node_by_id
        user_interest_relationship = self._graph_db.match_one(start_node=self.user_node,
                                                             rel_type=GraphRelationship.INTERESTED_IN,
                                                             end_node=interest_node)
        for key, value in experience_properties_dict.iteritems():
            user_interest_relationship.properties[key] = value
        user_interest_relationship.push()

    def delete_interest(self, interest_id):
        """
        drop interest relationship from user given the interest_id
        :param interest_id: str(uuid.uuid4())
        :return:
        """
        #TODO exception handling
        interest = Interest()
        interest.id = interest_id
        interest_node = interest.interest_node_by_id
        user_interest_relationship = self._graph_db.match_one(start_node=self.user_node,
                                                             rel_type=GraphRelationship.INTERESTED_IN,
                                                             end_node=interest_node)
        self._graph_db.delete(user_interest_relationship)

    def update_user(self):
        user_node = self.user_node
        user_properties = dict(self.user_properties)
        for key, value in user_properties.iteritems():
            user_node[key] = value  # user_properties[key]
        user_node.push()

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

    def add_goal(self, goal_properties):
        """
        Add goal to user
        :param goal_id: string uuid
        :return: List of user goals
        """
        #TODO exception handling
开发者ID:julianpistorius,项目名称:back-end-api,代码行数:70,代码来源:user.py


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