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


Python Graph.merge_one方法代码示例

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


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

示例1: import_api_data2

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

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

示例4: VbplPipeline

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

示例5: main1

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
def main1():
    authenticate("localhost:7474", "neo4j", "1234")
    graph = Graph(GRAPH_CONNECTION_STRNIG)

    graph.delete_all()

    banana = Node("Fruit", name="banana", colour="yellow", tasty=True)
    graph.create(banana)

    t = graph.merge_one("Fruit", 'name', 'apple')
    t['colour'] = 'green'
    t['tasty'] = True
    t.push()
开发者ID:vovacooper,项目名称:FreeTv,代码行数:15,代码来源:update_tv_data_new.py

示例6: main2

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
def main2():
    authenticate("localhost:7474", "neo4j", "1234")
    graph = Graph(GRAPH_CONNECTION_STRNIG)

    graph.delete_all()

    banana = Node("Fruit", name="banana", colour="yellow", tasty=True)
    graph.create(banana)

    t = graph.merge_one("Fruit", 'name', 'apple')
    t['colour'] = 'green'
    t['tasty'] = True
    t.push()

    alice = Node("Person", name="Alice")
    bob = Node("Person", name="Bob")
    alice_knows_bob = Relationship(alice, "KNOWS", bob, since=1999)
    graph.create(alice)
    graph.create(bob)
    graph.create(alice_knows_bob)
开发者ID:vovacooper,项目名称:FreeTv,代码行数:22,代码来源:update_tv_data_new.py

示例7: SyntaxGraph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
class SyntaxGraph():
    
    """
    The aim of this class is to find associated words to database syntax.
    A user will input a sentence, and these associations will be used to
    find the correct SQL statement to execute in the database.
    
    The relations between words are modelled as a graph. The nodes of the 
    graph are the words, and the edges (relationships) between nodes
    represent when a word means another word (e.g. is a synonym).
    
    The graph is "seeded" using a set of database syntax words, finding 
    synonyms/related words to these initial words using a call to a
    thesaurus API.
    
    The graph is then "grown" from the resulting synonyms using subsequent
    API calls, in a recursive fashion.
    
    When a user enters a sentence, this graph will be used to find 
    database syntax words which are within a certain "degree of 
    separation" from each word in the sentence, in an attempt to 
    start building a SQL query from this sentence.
    """
    
    def __init__(self, seed_words=None, seed_mappings=None):
        
        self.sql_terms = SQLTerms().sql_terms
        
        self.graph = Graph(DB_URI)
        self.tx = self.graph.cypher.begin()
        
        self.seed_mappings = seed_mappings or {'where': ['filter', 'for', 'during'],
                                               'from': ['source', 'in'],
                                               'into': ['toward', 'within', 'inside'],
                                               'group':['by'],
                                               'and': ['with']}
        
        self.seed_words = seed_words or [x for x in self.sql_terms if x not in self.seed_mappings]
    
        self.seed_words.extend([x for x in self.seed_mappings.iterkeys()])
        
        self.exclude_words = ['display']
        
    def seed(self, reset=False):
        
        print 'Seeding graph'
        
        if reset:
            self.graph.delete_all()
        
        for word in self.seed_words:
            if not self.already_called(word):
                self.add_synonyms(word)
            if word in self.seed_mappings:
                print 'Mapping %s to %s' % ( ','.join(self.seed_mappings[word]), word )
                base = self.graph.merge_one('Word', 'name', word)
                synonyms = [self.graph.merge_one('Word', 'name', x) for x in self.seed_mappings[word]]
                [self.graph.create_unique(Relationship(base, 'MEANS', synonym)) for synonym in synonyms]
                [self.graph.create_unique(Relationship(synonym, 'MEANS', base)) for synonym in synonyms]
            
                
    def grow(self, levels=1):
        
        print 'Levels left: %d' % levels
        
        query = ''' MATCH (w:Word)
                    WHERE NOT HAS (w.called)
                    RETURN w.name
                '''
        
        results = self.graph.cypher.execute(query)     
        
        for word in results:
            self.add_synonyms(word['w.name'])
            
        if levels > 1:
            self.grow(levels-1)
                
            
    def already_called(self, word):
        
        if len (self.graph.cypher.execute('''MATCH (w:Word)
                                             WHERE w.name = '%s'
                                               AND HAS (w.called)
                                             RETURN w.name 
                                          ''' % word) ) > 0:
            return True
        
    def update_set_called(self, word):
        
        word_node = self.graph.merge_one('Word', 'name', word)
        word_node.properties['called'] = 1
        word_node.push()
        
    def add_synonyms(self, word):
                                     
        url = 'http://words.bighugelabs.com/api/2/%s/%s/json' % (API_KEY, word)
        print url
        
        response = requests.get(url)
#.........这里部分代码省略.........
开发者ID:ndesmo,项目名称:Search-to-SQL,代码行数:103,代码来源:SearchToSQL.py

示例8: Graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
'''
Import the third level in the subjects hierarchy. By default, this will be from the level2list.json file.

CLI parameters:
argv[1] - full path to json file, including filename
argv[2] - optional flag to print or not
'''
import json
import sys

from py2neo import Graph
graph = Graph()
from py2neo import Node, Relationship

level2_f = sys.argv[1]
verbose = sys.argv[2]

subjects = json.loads(open(level2_f).read())

for d in subjects:
    parent = graph.merge_one("Subject", "id", d["parent1"])
    if verbose:
        print str(d["id"]) + ":" + d["name"] + "--" + parent["name"]
    n = Node("Subject", id=d["id"], name=d["name"], level=2)
    r = Relationship(n, "TYPE_OF", parent)
    graph.create(r)
开发者ID:dlarkinc,项目名称:tate2neo,代码行数:28,代码来源:subjects_level2.py

示例9: Node

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
			if "children" in artwork["subjects"]:
				for sl1 in artwork["subjects"]["children"]:
					#print sl1["name"]
					if "children" in sl1:
						for sl2 in sl1["children"]:
							#print "-" + sl2["name"]
							if "children" in sl2:
								for sl3 in sl2["children"]:
									#print "--" + sl3["name"]
									subjects.append(sl3["id"])
		
		node = Node("Artwork", id=artwork["id"], title=artwork["title"], acno=artwork["acno"])		
		graph.create(node)

		for s in subjects:
			subject = graph.merge_one("Subject", "id", s)
			r = Relationship(node, "FEATURES", subject)
			graph.create(r)

		if artwork["medium"]:
			for m in artwork["medium"].split(","):
				for n in m.split(" and "):
					for o in n.split(" on "):
						s = ''.join([i for i in o if not i.isdigit()])
						if s.strip().lower() not in mediums:
							mediums.append(s.strip().lower())
		
		for m in mediums:
			medium = graph.merge_one("Medium", "id", m)
			r = Relationship(node, "MADE_OF", medium)
			graph.create(r)
开发者ID:dlarkinc,项目名称:tate2neo,代码行数:33,代码来源:parse_json.py

示例10: open

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
# Read the author data structure file for ACM Scraping.
with open('data/acm_author.json') as author_file:
	author_structure = json.load(author_file)

# Create a node for every author of type "Author" storing the first, middle, last and full name. Currently we use the unique ACM Profile link for the author as the unique constraint while creating the node.
for key, value in author_structure.items():
	for record in value:
		link = str(record['link'])
		# print(link)
		first_name = record['FName']
		mid_name = record['MName']
		last_name = record['LName']
		full_name = record['FULL Name']

		author_to_be_added = graph.merge_one("Author", "link", link)
		author_to_be_added['full_name'] = full_name
		author_to_be_added['fist_name'] = first_name
		author_to_be_added['middle_name'] = mid_name
		author_to_be_added['last_name'] = last_name
		author_to_be_added.push()
		print(record['FULL Name'] + "\t")

print("\n")
# Read the journal and article data structure file for ACM Scraping
with open('data/tmp.json') as journal_article_file:
	acm_structure = json.load(journal_article_file)

j_list = []
a_list = []
开发者ID:SciBase-Project,项目名称:SciBaseGraphDB,代码行数:31,代码来源:journal_article.py

示例11: ApiProvider

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
class ApiProvider():
    def __init__(self, request_data):
        self._request_data = request_data
        authenticate("localhost:7474", "neo4j", "1234")
        # authenticate("52.27.227.159:7474", "neo4j", "1234")
        self.graph = Graph(GRAPH_CONNECTION_STRNIG)


    def _update_show(self, show_id):
        # get the node from the graph
        node_show = self.graph.node(show_id)
        if node_show['updated'] == True:
            return

        result_dict = {}
        try:
            show_info_e_list = requests.get(
                'http://services.tvrage.com/feeds/full_show_info.php?sid={0}'.format(node_show['id']))
            result_dict = xmltodict.parse(show_info_e_list.text)

            omdb_show_info = requests.get(
                'http://www.omdbapi.com/?t={0}&y=&plot=full&r=json'.format(node_show['name']))
            dict_omdb_show_info = json.loads(omdb_show_info.text)
            if dict_omdb_show_info['Response'] == 'True':
                for key, value in dict_omdb_show_info.iteritems():
                    node_show[key] = value
            success = False
        except ValueError as e:
            logger.exception("Value Error")
            return
        except Exception as e:
            logger.exception("Some network issue, will try again")
            return

        # add the new extracted data to the show
        node_show['started'] = result_dict['Show'].get('started', None)
        node_show['ended'] = result_dict['Show'].get('ended', None)
        node_show['image'] = result_dict['Show'].get('image', None)
        node_show['status'] = result_dict['Show'].get('status', None)
        node_show.push()

        # Country
        from_country = result_dict['Show'].get('origin_country', 'unknown')
        node_country = self.graph.merge_one("Country", 'country', from_country)
        node_country.push()

        # add the relation to the graph
        show_from_country = Relationship(node_show, "from", node_country)
        self.graph.create(show_from_country)

        # Genres
        if result_dict['Show'].get('genres', None) is not None:
            genre_list = []
            if type(result_dict['Show']['genres']['genre']) is list:
                genre_list = result_dict['Show']['genres']['genre']
            else:
                genre_list.append(result_dict['Show']['genres']['genre'])

            for genre in genre_list:
                # create the genre node
                node_genre = self.graph.merge_one("Genre", 'name', genre)
                node_genre.push()

                # add the Genre relation to the graph
                show_of_genre = Relationship(node_show, "of genre", node_genre)
                self.graph.create(show_of_genre)

        # Seasons
        season_list = []
        if result_dict['Show'].get('Episodelist', None) is None:
            return
        if type(result_dict['Show']['Episodelist']['Season']) is list:
            season_list = result_dict['Show']['Episodelist']['Season']
        else:
            season_list.append(result_dict['Show']['Episodelist']['Season'])

        for season in season_list:
            # create node for season
            node_season = Node.cast('Season', {'no': season['@no']})
            self.graph.create(node_season)

            # create the relation n the graph
            show_season = Relationship(node_show, "has", node_season)
            self.graph.create(show_season)

            # Episodes
            episode_list = []
            if type(season['episode']) is list:
                episode_list = season['episode']
            else:
                episode_list.append(season['episode'])

            count = 1
            for episode in episode_list:
                # create a node for episode
                node_episode = Node.cast('Episode', {
                    'airdate': episode.get('airdate', None),
                    'epnum': count,
                    'screencap': episode.get('screencap', None),
                    'title': episode.get('title', None)
#.........这里部分代码省略.........
开发者ID:vovacooper,项目名称:FreeTv,代码行数:103,代码来源:api_provider.py

示例12: open

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

示例13: print

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

    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:
开发者ID:ruettet,项目名称:belgianstartupmaffia,代码行数:33,代码来源:bsm_netlog.py

示例14: update_show_info_old

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
def update_show_info_old():
    print 'updating show info'
    authenticate("localhost:7474", "neo4j", "1234")
    graph = Graph(GRAPH_CONNECTION_STRNIG)

    results = graph.cypher.stream("match (s:Show) return id(s) as eid,s.id")
    start_id = 764
    for record in results:
        if int(record['s.id']) < start_id:
            continue

        node_show = graph.node(record['eid'])

        result_dict = {}

        success = True
        while success:
            try:
                show_info_e_list = requests.get(
                    'http://services.tvrage.com/feeds/full_show_info.php?sid={0}'.format(node_show['id']))
                result_dict = xmltodict.parse(show_info_e_list.text)

                omdb_show_info = requests.get(
                    'http://www.omdbapi.com/?t={0}&y=&plot=full&r=json'.format(node_show['name']))
                dict_omdb_show_info = json.loads(omdb_show_info.text)
                if dict_omdb_show_info['Response'] == 'True':
                    for key, value in dict_omdb_show_info.iteritems():
                        node_show[key] = value
                success = False
            except ValueError as e:
                logger.exception("Value Error")
                continue
            except Exception as e:
                logger.exception("Some network issue, will try again")
                success = True

        print str(node_show['name'])
        # info

        node_show['started'] = result_dict['Show'].get('started', None)
        node_show['ended'] = result_dict['Show'].get('ended', None)
        node_show['image'] = result_dict['Show'].get('image', None)
        node_show['status'] = result_dict['Show'].get('status', None)
        node_show.push()

        #Country
        from_country = result_dict['Show'].get('origin_country', 'unknown')

        node_country = graph.merge_one("Country", 'country', from_country)
        node_country.push()

        show_from_country = Relationship(node_show, "from", node_country)
        graph.create(show_from_country)


        #Genres
        if result_dict['Show'].get('genres', None) is not None:
            genre_list = []
            if type(result_dict['Show']['genres']['genre']) is list:
                genre_list = result_dict['Show']['genres']['genre']
            else:
                genre_list.append(result_dict['Show']['genres']['genre'])

            for genre in genre_list:
                node_genre = graph.merge_one("Genre", 'name', genre)
                node_genre.push()

                show_of_genre = Relationship(node_show, "of genre", node_genre)
                graph.create(show_of_genre)

        """try:
            print node_show['started']
            a = node_show['started'].split("/")
            if int(a[len(a)-1]) < 2000:
                continue
        except Exception:
            continue
        """

        #Seasons
        season_list = []
        if result_dict['Show'].get('Episodelist', None) is None:
            continue
        if type(result_dict['Show']['Episodelist']['Season']) is list:
            season_list = result_dict['Show']['Episodelist']['Season']
        else:
            season_list.append(result_dict['Show']['Episodelist']['Season'])

        for season in season_list:
            node_season = Node.cast('Season', {'no': season['@no']})
            graph.create(node_season)

            show_season = Relationship(node_show, "has", node_season)
            graph.create(show_season)

            #Episodes
            episode_list = []
            if type(season['episode']) is list:
                episode_list = season['episode']
            else:
#.........这里部分代码省略.........
开发者ID:vovacooper,项目名称:FreeTv,代码行数:103,代码来源:update_tv_data_new.py

示例15: Relationship

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import merge_one [as 别名]
    if (colorFound == False):
        prod_name = node.properties['product_name']
        color = utilities.searchPrefix(prod_name)
        #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()
    
开发者ID:Diwahars,项目名称:python-scripts-1,代码行数:32,代码来源:test_fk.py


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