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


Python Graph.match方法代码示例

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


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

示例1: getTestedNeo4jDB

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

示例2: NeoProvider

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
class NeoProvider(object):
	
	def __init__(self):
		
		# TODO read this from a config file
		uri = "http://neo4j:[email protected]:7474/db/data"
		self.graph = Graph(uri)
		self.store = Store(self.graph)
		
	def get_start_screen(self):
		# Fetch the start node
		start_node = self.graph.find_one("screen", "start", True)

		# Find all the navigations from the start node
		nav_rels = self.graph.match(start_node, "nav")

		# Find all the assets for the start node
		asset_rels = self.graph.match(start_node, "hasAsset")

		# Construct the DTOs
		assets = [Asset(asset_rel.end_node) for asset_rel in asset_rels]
		navs = [Navigation(nav_rel) for nav_rel in nav_rels]
		start_screen = Screen(start_node, navs, assets)
		return start_screen

	def get_next_screen(self, current_screen_key, option):
		# Fetch the current node
		current_node = self.graph.find_one("screen", "id", current_screen_key)

		# Navigate to the next node via option
		current_rels = self.graph.match(current_node, "nav")
		selected_rel = [rel for rel in current_rels if rel.properties['opt'] == int(option)][0]
		next_node = selected_rel.end_node

		# Grab new navigations and assets for the next node
		next_nav_rels = self.graph.match(next_node, "nav")
		asset_rels = self.graph.match(next_node, "hasAsset")

		# Construct the DTOs
		assets = [Asset(asset_rel.end_node) for asset_rel in asset_rels]
		navs = [Navigation(nav_rel) for nav_rel in next_nav_rels]
		next_screen = Screen(next_node, navs, assets)
		return next_screen
开发者ID:hnkkorgris,项目名称:jelly-cake,代码行数:45,代码来源:controller.py

示例3: get_graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
def get_graph():
    graph = Graph()
    nodes = set()
    links = []
    for rel_type in [REL_FOLLOWS, REL_UPLOADED, REL_FAVORITED]:
        for rel in graph.match(rel_type=rel_type):
            start = node_to_id(rel.start_node)
            end = node_to_id(rel.end_node)
            if rel_type == REL_FAVORITED and end not in nodes:
                continue
            nodes.add(start)
            nodes.add(end)
            links.append([start, end])
    return {'nodes': list(nodes), 'links': links}
开发者ID:susurrant-audio,项目名称:susurrant-py,代码行数:16,代码来源:track_info.py

示例4: AgoraOrganization

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
class AgoraOrganization(object):
    def __init__(self):
        self.name = None
        self.unique_id = None
        self.mission_statement = None
        self.email = None
        self.is_open = False
        self.is_invite_only = False
        self.website = None
        self.graph_db = Graph()

    @property
    def org_node(self):
        return self.graph_db.find_one(AgoraLabel.ORGANIZATION,
                                      property_key='name',
                                      property_value=self.name)

    @property
    def org_members(self):
        """
        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=AgoraRelationship.MEMBER_OF,
                                                end_node=None)
        org_members_list = []
        for item in org_members_nodes:
            org_members_list.append((item.end_node["name"], item.end_node["email"]))
        return org_members_list

    def create_organization(self):
        """
        create a new organization
        :return: py2neo Node
        """
        self.unique_id = str(uuid.uuid4())
        new_org_properties = {
            "name": self.name,
            "mission_statement": self.mission_statement,
            "unique_id": self.unique_id,
            "email": self.email,
            "is_open": self.is_open,
            "is_invite_only": self.is_invite_only,
            "website": self.website}

        new_org_node = Node.cast(AgoraLabel.ORGANIZATION, new_org_properties)
        self.graph_db.create(new_org_node)

        return new_org_node
开发者ID:julianpistorius,项目名称:agora-development,代码行数:52,代码来源:py2neo_organization.py

示例5: city

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
def city():
    location = request.args['meetup_group']

    graph = Graph(host=config['neo4j']['host'], user=config['neo4j']['user'],
                  password=config['neo4j']['password'])

    logger.info('Finding upcoming meetup events in {}'.format(location))

    groups_data = defaultdict()

    groups = graph.find('Group')
    for group in groups:
        groups_data[group.properties['name']] = []
        for rel in graph.match(start_node=group, rel_type="HAS EVENT"):
            groups_data[group.properties['name']].append(rel.end_node().properties['time'])

    return json.dumps(groups_data)
开发者ID:implicit-explicit,项目名称:social_genius_backend,代码行数:19,代码来源:social_genius_backend.py

示例6: before_all

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

示例7: Group

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
class Group(object):
    def __init__(self):
        self.name = ''
        self.id = None
        self.about = ''
        self.mission_statement = ''
        self.is_open = None
        self.is_invite_only = False
        self.last_updated_date = ''
        # self.meeting_location = ''
        # self.next_meeting_date = None
        # self.next_meeting_time = None
        # self.creator = '' #by id
        # self.moderators = [] #by id
        self.website = ''
        self._graph_db = Graph(settings.DATABASE_URL)

    @property
    def group_properties(self):
        properties_dict = dict(self.__dict__)
        del properties_dict['_graph_db']
        return properties_dict

    def set_group_properties(self, group_properties):
        for key, value in group_properties.iteritems():
            setattr(self, key, value)

    def get_group(self):
        """
        get the group info (attributes) based on the id
        :return:
        """
        group_node = self.group_node
        group_properties = dict(group_node.properties)
        if not group_node is None:
            for key, value in group_properties.iteritems():
                setattr(self, key, value)

    @property
    def group_node(self):
        """
        get a group node based on the unique id attribute
        :return: neo4j.Node
        """
        return self._graph_db.find_one(GraphLabel.STUDYGROUP,
                                      property_key='id',
                                      property_value=self.id)

    @property
    def group_interests(self):
        """ get user interests
        :return: list of interests
        """
        group_interests = self._graph_db.match(start_node=self.group_node,
                                              rel_type=GraphRelationship.INTERESTED_IN,
                                              end_node=None)
        # create a list of tuples of interests and the users's relationship to them
        interests_list = []
        for rel in group_interests:
            interest = Interest()
            interest.id = rel.end_node['id']
            interest.get_interest_by_id()
            interest_dict = {}
            interest_dict = interest.interest_properties
            interests_list.append(interest_dict)
            # interests_list.append((item.end_node["name"], item["description"]))
        # return [item.end_node["name"] for item in user_interests]
        return interests_list

    @property
    def group_locations(self):
        """

        :return: list of locations
        """
        group_locations = self._graph_db.match(start_node=self.group_node,
                                              rel_type=GraphRelationship.LOCATED_IN,
                                              end_node=None)
        locations_list = []
        for rel in group_locations:
            location_dict = {}
            location = Location()
            location.id = rel.end_node['id']
            location_dict = dict(location.location_properties)
            locations_list.append(location_dict)
            # locations_list.append(item.end_node["formatted_address"])
        return locations_list

    @property
    def group_members(self):
        group_member_nodes = self._graph_db.match(start_node=self.group_node,
                                            rel_type=GraphRelationship.MEMBER_OF,
                                            end_node=None)
        members_list = []
        for rel in group_member_nodes:
            member_dict = {}
            # member = User()
            # member.id = rel.end_node['id']
            # member_dict = dict(rel.end_node.properties)
            members_list.append(dict(rel.end_node.properties))
#.........这里部分代码省略.........
开发者ID:julianpistorius,项目名称:back-end-api,代码行数:103,代码来源:group.py

示例8: main

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
def main():
    # Defaults
    protocol = "http"
    hostName = "localhost"
    portNumber = 7474
    dbPath = "/db/data/"
    userId = ""
    password = ""
    limit = 0  # limit = 0 means no limit, limit =n where n > 0 limits queries to at most n rows
    csvpath = "."
    nodeLabels = ""
    batchsize = 1000

    try:
        opts, args = getopt.getopt(sys.argv[1:], "?",
                                   ["help", "protocol=", "host=", "port=", "db=", "userid=", "password=", "limit=",
                                    "csvpath=", "nodelabels="])
    except getopt.GetoptError:
        print "ERROR unknown option!"
        print ""
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-?', '--help'):
            usage()
            sys.exit(0)
        elif opt == "--protocol":
            protocol = arg
        elif opt == "--host":
            hostName = arg
        elif opt == "--port":
            portNumber = arg
        elif opt == "--db":
            dbPath = arg
        elif opt == "--userid":
            userId = arg
        elif opt == "--password":
            password = arg
        elif opt == "--limit":
            limit = arg
        elif opt == "--csvpath":
            csvpath = arg
        elif opt == "--nodelabels":
            nodeLabels = arg
        else:
            print "ERROR: Unknown option", opt
            print ""
            usage()
            sys.exit(2)

    host = hostName + ":" + str(portNumber)
    url = protocol + "://" + host + dbPath

    print "Connect to", url

    if len(userId) > 0:
        authenticate(host, userId, password)

    graph = Graph(url)
    print "Connected:", graph.bound

    # Check if output directory exists
    if not os.path.isdir(csvpath):
        print "ERROR Directory doesn't exist", csvpath
        sys.exit(1)

    relationshipTables = {}  # one table for each of the relationship types for the current label

    if len(nodeLabels) > 0:
        labels = nodeLabels.split(',')
    else:
        labels = graph.node_labels  # Get list of labels from the database

    for label in labels:
        print "Get nodes for label:", label

        currentTable = table()

        nodecount=0

        while True:
            matchLimit = batchsize
            if limit > 0:
                if nodecount < limit:
                    if nodecount + batchsize > limit:
                        matchLimit = limit - nodecount
                else:
                    break
            nodeCountCheck = nodecount

            # nodes = graph.find(label)
            nodes = graph.cypher.stream("MATCH (n:" + str(label) + ") RETURN n ORDER BY id(n) SKIP {skip} LIMIT {limit}", {"skip": nodecount, "limit": matchLimit})

            if not nodes:
                break

            for g_node in nodes:
                nodecount += 1
                node = g_node.n
#.........这里部分代码省略.........
开发者ID:awithey,项目名称:neo2pg,代码行数:103,代码来源:neo2csv.py

示例9: key_entity

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
def key_entity():

	print "storing keywords"
	# Create the AlchemyAPI Object
	alchemyapi = AlchemyAPI()

	art_keywords = {}
	art_entities = {}
	
	count = 0 

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

	article_query =  """MATCH (n:article) 
						Return distinct n.url as url"""

	result = graph.cypher.execute(article_query)

	keyword_count = 0
	entity_count = 0
	art_count = 0
	for arti in result:

		if count >= 1000:
			print "Alchemy limit exceeds"
			exit()


		art = arti['url']

		article_node = """ MATCH (article:article{url:'"""+art+"""'})
		SET article.processed = 'yes'
		Return article;
		"""
		article = graph.cypher.execute(article_node)

		if art not in art_keywords.keys():
			art_keywords[art] = []
			response = alchemyapi.keywords('url', art, {'sentiment': 1})
			count = count + 1
			art_count = art_count + 1
			if response['status'] == 'OK':
				for keyword in response['keywords']:
					# print('text: ', keyword['text'].encode('utf-8'))
					key = str(keyword['text'].encode('utf-8')).replace("'","")
					art_keywords[art].append(key)

					rel_dict = {}

					rel_dict['relevance'] = keyword['relevance']
					rel_dict['sentiment'] = keyword['sentiment']['type']
					if 'score' in keyword['sentiment']:
						rel_dict['sentiment_score'] = keyword['sentiment']['score']

					keyword_node = """ MERGE (keyword:Keywords{text:'"""+key+"""'})
					Return keyword;
					"""
					at_keywords = graph.cypher.execute(keyword_node)

					if len(list(graph.match(start_node=article.one,end_node=at_keywords.one, rel_type=("has_keyword",rel_dict)))) == 0:
						pth = Path(article.one,("has_keyword",rel_dict),at_keywords.one)
						graph.create(pth)
						keyword_count = keyword_count + 1


		if count >= 1000:
			print "Alchemy limit exceeds"
			exit()


		if art not in art_entities.keys():
			art_entities[art] = []
			response = alchemyapi.entities('url', art, {'sentiment': 1})
			count = count + 1
			if response['status'] == 'OK':
				for entities in response['entities']:
					# print('text: ', entities['text'].encode('utf-8'))
					key = str(entities['text'].encode('utf-8')).replace("'","")
					art_entities[art].append(key)

					rel_dict = {}

					rel_dict['type'] = entities['type']
					rel_dict['relevance'] = entities['relevance']
					rel_dict['sentiment'] = entities['sentiment']['type']
					if 'score' in entities['sentiment']:
						rel_dict['sentiment_score'] = entities['sentiment']['score']
					
					entities_node = """ MERGE (entities:Entities{text:'"""+key+"""'})
					Return entities;
					"""
					if len(list(graph.match(start_node=article.one,end_node=at_entities.one, rel_type=("has_entity",rel_dict)))) == 0:		
						at_entities = graph.cypher.execute(entities_node)
						pth = Path(article.one,("has_entity",rel_dict),at_entities.one)
						graph.create(pth)
						
						entity_count  = entity_count + 1

	return {'articles':str(art_count),'keywords':str(keyword_count),'entities':str(entity_count)}
开发者ID:kaush-utkarsh,项目名称:neo4jDataStore,代码行数:101,代码来源:consolidated.py

示例10: leads

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
def leads(csvFilePath, config_file, act):
	
	config = ConfigParser.ConfigParser()
	config.read(config_file)

	nodes = config.options("nodes")
	relation = config.options("relation")

	# fetch from csv and store in graph
	print "Storing Leads"
	graph = Graph("http://neo4j:[email protected]:7474/db/data/")

	csvfile = open(csvFilePath)

	reader = csv.DictReader(csvfile)

	reslt = {}
	indi_count = 0

	for row in reader:
		try:
			nodeList={}
			for n in nodes:
				node_atr = config.get("nodes",n)
				attr = json.loads(node_atr)
				individual_node = ""
				try:
					if bool(attr):
						individual_node = """ MERGE ("""+act+""":"""+n+"""{"""

						for attr_key in attr.keys():
							individual_node=individual_node+str(attr_key)+""" :'"""+(str(row[attr[attr_key]]).replace("'",""))+"""', """
						individual_node = individual_node.strip(", ")+"""})
						Return """+act+""";
						"""
						individual = graph.cypher.execute(individual_node)		
						nodeList[n]=individual
						indi_count=indi_count+1
				except Exception,ee:
					pass

			for n in relation:
				rel_atr = config.get("relation",n)
				attr = json.loads(rel_atr)
				try:
					if bool(attr):

						start_node = attr['start_node']
						end_node = attr['end_node']
						attributes = attr['attributes']
	
						rel_dict={}

						for u in attributes.keys():

							rel_dict[u] = (str(row[attributes[u]]).replace("'",""))
						
						if len(list(graph.match(start_node=nodeList[start_node].one,end_node=nodeList[end_node].one, rel_type=(n,rel_dict)))) == 0:
							graph.create(Path(nodeList[start_node].one,(n,rel_dict),nodeList[end_node].one))
				except Exception,ee:
					pass
开发者ID:kaush-utkarsh,项目名称:neo4jDataStore,代码行数:63,代码来源:consolidated.py

示例11: Meeting

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
class Meeting(object):
    def __init__(self):
        """

        :return:
        """
        self.id = ''
        self.name = ''
        self.description = ''
        self.where = ''
        self.date = ''
        self.time = ''
        self.created_date = ''
        self.is_recurring = False
        self._graph_db = Graph(settings.DATABASE_URL)

    @property
    def meeting_properties(self):
        """

        :return:
        """
        properties_dict = dict(self.__dict__)
        del properties_dict['_graph_db']
        return properties_dict

    @property
    def meeting_node(self):
        """

        :return:
        """
        if self.id != '':
            return self._graph_db.find_one(GraphLabel.MEETING,
                                          property_key='id',
                                          property_value=self.id)

    @property
    def group(self):
        """

        :return: Group() that is attached to this meeting
        """
        meeting_group_relationship = self._graph_db.match(start_node=None,
                                                         rel_type=GraphRelationship.HAS_MEETING,
                                                         end_node=self.meeting_node)
        group = Group()
        for rel in meeting_group_relationship:
            group.id = rel.end_node.properties['id']
            group.get_group()
        return group

    def set_meeting_properties(self, meeting_properties):
        """

        :param meeting_properties:
        :return:
        """
        for key, value in meeting_properties.iteritems():
            setattr(self, key, value)

    # @staticmethod
    def get_meeting(self):
        """

        :return:
        """
        meeting_node = self.meeting_node
        if meeting_node is not None:
            meeting_properties = dict(meeting_node.properties)
            for key, value in meeting_properties.iteritems():
                setattr(self, key, value)

    def create_meeting(self, group_id, meeting_properties=None):
        """

        :param meeting_properties:
        :return:
        """
        #TODO exception handling
        self.created_date = datetime.date.today()
        self.id = str(uuid.uuid4())
        if meeting_properties is not None:
            self.set_meeting_properties(meeting_properties)
        new_meeting_node = Node.cast(GraphLabel.MEETING, self.meeting_properties)
        try:
            self._graph_db.create(new_meeting_node)
            group = Group()
            group.id = group_id
            group_node = group.group_node
            meeting_group_relationship = Relationship(group_node,
                                                     GraphRelationship.HAS_MEETING,
                                                     self.meeting_node)
            self._graph_db.create_unique(meeting_group_relationship)
        except:
            pass
        return new_meeting_node

    def update_meeting(self):
        """
#.........这里部分代码省略.........
开发者ID:julianpistorius,项目名称:back-end-api,代码行数:103,代码来源:meeting.py

示例12: AgoraGroup

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
class AgoraGroup(object):
    def __init__(self, graph_db):
        self.name = None
        self.unique_id = None
        self.description = None
        self.is_open = None
        self.is_invite_only = None
        self.meeting_location = None
        self.next_meeting_date = None
        self.members = []
        self.interests = []
        self.group_leader_username = None
        self.graph_db = Graph()

    @property
    def group_node(self):
        """
        get a group node based on the unique id attribute
        :return: neo4j.Node
        """
        return self.graph_db.find_one(AgoraLabel.STUDYGROUP,
                                      property_key='unique_id',
                                      property_value=self.unique_id)

    @property
    def group_interests(self):
        """ get user interests
        :return: list of interests
        """
        group_interests = self.graph_db.match(start_node=self.group_node,
                                              rel_type=AgoraRelationship.INTERESTED_IN,
                                              end_node=None)
        # create a list of tuples of interests and the users's relationship to them
        interests_list = []
        for item in group_interests:
            interests_list.append((item.end_node["name"], item["description"]))
        # return [item.end_node["name"] for item in user_interests]
        return interests_list

    def create_group(self):
        """
        create new study group or circle
        :return: py2neo Node
        """
        self.unique_id = str(uuid.uuid4())
        new_group_properties = {
            "name": self.name,
            "description": self.description,
            "unique_id": self.unique_id,
            "is_open": self.is_open,
            "is_invite_only": self.is_invite_only,
            "meeting_location": self.meeting_location,
            "next_meeting_date": self.next_meeting_date,
        }

        new_group_node = Node.cast(AgoraLabel.STUDYGROUP, new_group_properties)
        self.graph_db.create(new_group_node)

        return new_group_node

    def add_interest(self, interest_node):
        """
        link interests to a study group
        :return: list of group interests
        """

        group_interest_relationship = Relationship(start_node=interest_node,
                                                   rel=AgoraRelationship.INTERESTED_IN,
                                                   end_node=self.group_node)

        self.graph_db.create(group_interest_relationship)

        # TODO set properties on RELATIONSHIP
        return self.group_interests

    def update_group(self):
        pass

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

示例13: __init__

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
class GraphExporter:
    def __init__(self):
        authenticate(neo4j.HOST_PORT, neo4j.USERNAME, neo4j.PASSWORD)
        self.neo4j_db = Graph(neo4j.REMOTE_URI)

    def create_taikonetwork_graph(self):
        print("> Taiko Network Graph: querying all nodes and relationships...")
        self.graph = nx.Graph()
        self._add_group_nodes()
        self._add_memberships()
        self._add_member_nodes()
        self._add_unique_connections()
        print("> Taiko Network Graph: SUCCESSFULLY CREATED!\n"
              "> Export to graph file format to save.\n")

    def create_demographic_graph(self):
        print("> Demographic Graph: querying all Member nodes and Connection rels...")
        self.graph = nx.Graph()
        self._add_member_nodes(demo=True)
        self._add_unique_connections(demo=True)
        print("> Demographic Graph: SUCCESSFULLY CREATED!\n"
              "> Export to graph file format to save.\n")

    def export_gexf_graph(self, filepath='graph.gexf'):
        nx.write_gexf(self.graph, filepath,
                      encoding='utf-8', prettyprint=True, version='1.2draft')

    def _add_group_nodes(self):
        groups = self.neo4j_db.find('Group')
        color = {'r': 255, 'g': 2, 'b': 97, 'a': 1}

        for g in groups:
            data = g.properties
            self.graph.add_node(
                g._id, label=data['name'], sf_id=data['sf_id'],
                viz={'color': color})

    def _add_member_nodes(self, demo=False):
        members = self.neo4j_db.find('Member')

        for m in members:
            data = m.properties
            color = self._random_color(m._id, 1)
            if demo:
                self.graph.add_node(
                    m._id, label=data['firstname'] + ' ' + data['lastname'],
                    gender=data['gender'], dob=data['dob'],
                    race=data['race'], ethnicity=data['asian_ethnicity'],
                    viz={'color': color})
            else:
                self.graph.add_node(
                    m._id, label=data['firstname'] + ' ' + data['lastname'],
                    sf_id=data['sf_id'],
                    viz={'color': color})

    def _add_unique_connections(self, demo=False):
        connections = self.neo4j_db.match(rel_type='CONNECTED_TO')
        unique_rels = []

        for c in connections:
            start = c.start_node._id
            end = c.end_node._id
            if (start, end) not in unique_rels and (end, start) not in unique_rels:
                if demo:
                    color = {'r': 213, 'g': 213, 'b': 213, 'a': 0.3}
                else:
                    color = self._random_color(start, 0.3)
                self.graph.add_edge(start, end, viz={'color': color})
                unique_rels.append((start, end))

    def _add_memberships(self):
        memberships = self.neo4j_db.match(rel_type='MEMBER_OF')

        for ms in memberships:
            color = self._random_color(ms.start_node._id, 0.3)
            self.graph.add_edge(ms.start_node._id, ms.end_node._id,
                                viz={'color': color})

    def _random_color(self, obj_id, alpha):
        colors = [{'r': 164, 'g': 243, 'b': 121},
                  {'r': 243, 'g': 230, 'b': 121},
                  {'r': 243, 'g': 121, 'b': 184},
                  {'r': 154, 'g': 121, 'b': 243},
                  {'r': 202, 'g': 243, 'b': 121},
                  {'r': 243, 'g': 177, 'b': 121},
                  {'r': 243, 'g': 121, 'b': 238},
                  {'r': 121, 'g': 243, 'b': 212},
                  {'r': 243, 'g': 190, 'b': 121},
                  {'r': 121, 'g': 194, 'b': 243},
                  {'r': 157, 'g': 2, 'b': 253},
                  {'r': 2, 'g': 86, 'b': 253}]

        c = colors[obj_id % 12]
        c['a'] = alpha
        return c
开发者ID:taikonetwork,项目名称:taikonetwork,代码行数:97,代码来源:graph_exporter.py

示例14: Cq

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
class Cq(object):
    def __init__(self):
        """

        :return:
        """
        self.id = ''
        self.subject = ''
        self.message = ''
        self.created_date = ''
        self._graph_db = Graph(settings.DATABASE_URL)

    @property
    def cq_properties(self):
        """

        :return:
        """
        properties_dict = dict(self.__dict__)
        del properties_dict['_graph_db']
        return properties_dict

    @property
    def cq_node(self):
        """

        :return:
        """
        if self.id != '':
            return self._graph_db.find_one(GraphLabel.CQ,
                                          property_key='id',
                                          property_value=self.id)

    @property
    def response_list(self):
        """
        list of responses to this CQ
        :return: list of responses
        """
        cq_response_relationship = self._graph_db.match(start_node=self.cq_node,
                                                       rel_type=GraphRelationship.TO,
                                                       end_node=None)
        response_list = []
        for rel in cq_response_relationship:
            response = rel.end_node.properties
            user_response_relationship = self._graph_db.match_one(start_node=None,
                                                                 rel_type=GraphRelationship.RESPONDED,
                                                                 end_node=self.cq_node)
            user_node = user_response_relationship.start_node
            response['by'] = '%s / %s' % (user_node.properties['name'],
                                          user_node.properties['call_sign'])
            response_list.append(response)

        return response_list

    @staticmethod
    def create_cq(user_node, cq_dict):
        cq_dict['id'] = str(uuid.uuid4())
        cq_dict['created_date'] = datetime.date.today()
        cq_node = Node.cast(GraphLabel.CQ,
                            cq_dict)
        cq_node, = Graph(settings.DATABASE_URL).create(cq_node)
        cq_relationship = Relationship(user_node,
                                       GraphRelationship.SENT,
                                       cq_node)
        Graph(settings.DATABASE_URL).create_unique(cq_relationship)

    @staticmethod
    def most_recent_cqs():
        params = {

        }
        cypher_str = ""
        match_results = Graph(settings.DATABASE_URL).cypher.execute(statement=cypher_str,
                                                                    parameters=params)
        cq_list = []
        cq = {}
        for item in match_results:
            cq['id'] = item.id
            cq['subject'] = item.subject
            cq['message'] = item.message
            cq['created_date'] = item.created_date
            cq_list.append(cq)
        root = {}
        root['cqs'] = cq_list
        return root


    def response(self, response_id):
        """
        response dictionary details including user details
        :param response_id:
        :return:  dict with response details and a dict of the user who made the response
        """
        response_node = self._graph_db.find_one(GraphLabel.RESPONSE,
                                               property_key='id',
                                               property_value=response_id)
        response_user_relationship = self._graph_db.match_one(start_node=None,
                                                             rel_type=GraphRelationship.RESPONDED,
                                                             end_node=response_node)
#.........这里部分代码省略.........
开发者ID:julianpistorius,项目名称:back-end-api,代码行数:103,代码来源:cq.py

示例15: print

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import match [as 别名]
        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
    edges = []
    for r in graph.match():
      edge = {"to": r.end_node.ref.split("/")[-1],
              "from": r.start_node.ref.split("/")[-1]
             }
      edges.append(edge)
    with open("report/edgesnetlog.js", "w") as f:
      f.write("var edgesraw = " + dumps(edges, indent=2) + ";")

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


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