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


Python Graph.run方法代码示例

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


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

示例1: get_graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
def get_graph():
    global NEO4J_URL,NEO4J_HOST,NEO4J_PORT,NEO4J_AUTH

    # Connect to graph
    creds = NEO4J_AUTH.split('/')
    graph = Graph(user=creds[0], password=creds[1], host=NEO4J_HOST)

    graph.run('match (t:Tweet) return COUNT(t)')
    return graph
开发者ID:neo4j-contrib,项目名称:twitter-neo4j,代码行数:11,代码来源:import_user.py

示例2: computeShortestPathCoherence

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
def computeShortestPathCoherence(node1, node2, w):
	"""Connects to graph database, then creates and sends query to graph 
	database. Returns the shortest path between two nodes.
	Format: (67149)-[:'LINKS_TO']->(421)"""

	if node1.strip()==node2.strip():
		return w

	fromCache=rds.get("%s:%s" % (node1, node2))
	if fromCache:
		return float(fromCache)*w
	else:
		g = Graph()
		q="MATCH path=shortestPath((m:Page {name:\"%s\"})-[LINKS_TO*1..10]-(n:Page {name:\"%s\"})) RETURN LENGTH(path) AS length, path, m, n" % (node1, node2)

		cursor=g.run(q)
		path=None
		for c in cursor:
			path=c

	#
		if path:
			rds.set("%s:%s" % (node1, node2), 1/path["length"])
			rds.set("%s:%s" % (node2, node1), 1/path["length"])
			return w/path["length"]
		else:
			rds.set("%s:%s" % (node1, node2), 0.0)
			rds.set("%s:%s" % (node2, node1), 0.0)
			return 0.0
开发者ID:cltl,项目名称:ELBaselines,代码行数:31,代码来源:my_system.py

示例3: make_sequence

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
    def make_sequence(self):
        authenticate(settings.NeoHost, settings.NeoLog, settings.NeoPass)
        graph = Graph("{0}/db/data/".format(settings.NeoHost))
        query = """MATCH (start:Video)-[:Jaccard*5..10]->(sequence:Video) 
        WHERE start<>sequence MATCH p=shortestPath((start:Video)-[:Jaccard*]->(sequence:Video)) 
        WHERE NONE (n IN nodes(p) WHERE size(filter(x IN nodes(p) WHERE n = x))> 1)  
        RETURN EXTRACT(n IN NODES(p)|[n.id, n.rating]) LIMIT 100000"""
   
        r1 = graph.run(query).data()
        k = 0
        for i in r1:
            #print(i.values)
            for video in i['EXTRACT(n IN NODES(p)|[n.id, n.rating])']:
                 #print(video)
                 self.seq_ids.append(k)
                 self.video_ids.append(video[0])
                 self.ratings.append(video[1])
            k+=1
        data = {'sequence': self.seq_ids, 'video': self.video_ids, 'rating': self.ratings}
        df = pd.DataFrame(data)
        df = df[pd.notnull(df['video'])]
        print(df)
        dz = df.groupby('sequence')['rating'].std()
        print(dz)

        path = '{0}/{1}/'.format(settings.VideosDirPath, self.game)
        if not os.path.exists(path):
            os.makedirs(path)
        file_name = '{0}/sequences.csv'.format(path)
        df.to_csv(file_name, encoding='utf-8')
        summary_data = '{0}/summary.csv'.format(path)
        dz.to_csv(summary_data, encoding='utf-8')
        return
开发者ID:pashadude,项目名称:nogoodgamez2,代码行数:35,代码来源:VideoSequenceCreation.py

示例4: reach

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
def reach():
	#topic = str(request.args.get('topic'))
	topic = str(request.form['topic'])
	graph = Graph("http://ec2-52-205-15-39.compute-1.amazonaws.com:7474/db/data/")
	graph.run("MATCH (n:"+topic+") SET n.FollowerCount = toInt(n.FollowerCount)")
	reach_count_cursor = graph.run("MATCH (n:"+topic+") RETURN count(n)")
	preach_count_cursor = graph.run("MATCH (n:"+topic+") RETURN sum(n.FollowerCount)")
	for reach_count_record in reach_count_cursor:
		reach_count = reach_count_record[0]
	for preach_count_record in preach_count_cursor:
		preach_count = preach_count_record[0]
	#json_object = { "metric": ["Reach", "Potencial Reach"], "frequency": ["reach_count","reach_count"] }
	json_array = []
	json_array.append({'metric':'Reach', 'value':int(reach_count)})
	json_array.append({'metric':'PotencialReach','value':int(preach_count)})
	json_object = {'records':json_array}

	return jsonify(json_object)
开发者ID:Swebask,项目名称:Get-Your-Brand-On,代码行数:20,代码来源:views.py

示例5: graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
def graph():
	#topic = str(request.args.get('topic'))
	topic = str(request.form['topic'])
	graph = Graph("http://ec2-52-205-15-39.compute-1.amazonaws.com:7474/db/data/")
	node_results = graph.run("MATCH (n:brexit) where has(n.betweenness_centrality) RETURN n.ScreenName as ScreenName, n.TweetId as TweetId, n.FollowerCount as FollowerCount, n.betweenness_centrality as BetweennessCentrality;")
	linksMap = {}
	nodes = []
	links = []
	for index,node_result in enumerate(node_results):
	    linksMap[node_result['ScreenName']]=index
	    nodes.append({'tweetId': str(node_result['TweetId']), 'name' : str(node_result['ScreenName']), 'group' : int(node_result['FollowerCount'])%5,'nodeSize':int(node_result['BetweennessCentrality'])/25+4 })

	rels_results = graph.run("MATCH (a:brexit)-[r:FOLLOWEDBY]-(b:brexit) RETURN a.ScreenName, b.ScreenName")
	for rels_result in rels_results:
		#print(rels_result)
		links.append({'source':linksMap[rels_result['a.ScreenName'].encode('utf-8')],'target':linksMap[rels_result['b.ScreenName'].encode('utf-8')],'value':2})
	json_object = { "nodes": nodes,  "links": links }
	return jsonify(json_object)
开发者ID:Swebask,项目名称:Get-Your-Brand-On,代码行数:20,代码来源:views.py

示例6: get_requests

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
def get_requests(item_name, tier=1, enchantment=0, quality=0, after_ts=1000):
	graph = Graph(password='password')
	current_ts = datetime.timestamp(datetime.now())

	query = f'''
	MATCH (:Character)-[r:request]->(i:Item)<-[o:offer]-(:Character)
	WHERE i.Group = "{item_name}" 
	AND i.Tier = {tier}
	AND i.Enchantment = {enchantment}
	AND i.Quality = {quality}
	AND ({current_ts} - r.LastViewed) < {after_ts}
	AND ({current_ts} - o.LastViewed) < {after_ts}
	AND (r.UnitPriceSilver < o.UnitPriceSilver) 
	RETURN i, (r.UnitPriceSilver - o.UnitPriceSilver) as profit
	ORDER BY profit
	'''

	return graph.run(query)
开发者ID:Tyjch,项目名称:photon,代码行数:20,代码来源:ogm.py

示例7: get_profitable_trades

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
def get_profitable_trades(after_ts=100000):
	graph = Graph(password='password')
	current_ts = datetime.timestamp(datetime.now())

	query = f'''
	MATCH (:Character)-[r:request]->(i:Item)<-[o:offer]-(:Character)
	WHERE ({current_ts} - r.LastViewed) < {after_ts}
	AND ({current_ts} - o.LastViewed) < {after_ts}
	AND (r.UnitPriceSilver - o.UnitPriceSilver) > 0 
	RETURN i, r.UnitPriceSilver as sell_price, o.UnitPriceSilver as buy_price, (r.UnitPriceSilver - o.UnitPriceSilver) as profit
	ORDER BY profit
	'''

	response = graph.run(query)


	for r in response:
		data = r.data()
		item = data['i']

		buy_price  = data['buy_price']
		sell_price = data['sell_price']
		profit     = data['profit']

		item_name = item_dict[item['Group']]

		print()
		print('__' * 20)
		print('>>> ', item_name)
		print('T: ', item['Tier'])
		print('E: ', item['Enchantment'])
		print('Q: ', item['Quality'])
		print('Buy for:  $', str(buy_price)[:-4])
		print('Sell for: $', str(sell_price)[:-4])
		print('PROFIT =  $', str(profit)[:-4])
		print('__' * 20)
开发者ID:Tyjch,项目名称:photon,代码行数:38,代码来源:ogm.py

示例8: URL

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
import requests, re
from lxml import html
from py2neo import Graph, Node, Relationship

# find a numeric ID in a URL (without any other digits)
findid = re.compile(r"\d+")

# change the Neo4j password to yours
g = Graph(user="neo4j", password="Swift")

# reset the graph
# take care to use an underscore in ARTIST_OF
# or in queries you will need to use tic quotes ``
g.run('MATCH () -[r:ARTIST_OF] -> () DELETE r;')
g.run('MATCH (n:Artist) DELETE n;')
g.run('MATCH (m:Artwork) DELETE m;')

def ScrapeCollection(workID):
    page = requests.get('http://moma.org/collection/works/' + str(workID))
    tree = html.fromstring(page.content)

    # the title is a complex, potentially italicized field
    titles = tree.cssselect('.short-caption h1.object-tile--gothic')
    for title in titles:
        full_title = title.text.strip()
        break

    # the date is a string field which can be a year, range of years, or approximation
    dates = tree.cssselect('.short-caption h3')
    for date in dates:
        first_date = date.text.strip()
开发者ID:mapmeld,项目名称:graph,代码行数:33,代码来源:scrape-one.py

示例9: create_DrugFirm_node

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

def create_DrugFirm_node(file, g):
    query = '''
    USING PERIODIC COMMIT 500
    LOAD CSV WITH HEADERS FROM {file}
    AS line
    FIELDTERMINATOR '	'
    CREATE(df:DrugFirm {dunsNumber: line.DUNS_NUMBER, firmName: line.FIRM_NAME,
    address: line.ADDRESS, operations: line.OPERATIONS})
    RETURN id(df), df.firmName
    '''

    return g.run(query,file = file)


if __name__ == "__main__":
    pw = os.environ.get('NEO4J_PASS')
    g = Graph("http://localhost:7474/", password=pw)  ## readme need to document setting environment variable in pycharm
    tx = g.begin()

    index = '''
    CREATE INDEX ON: DrugFirm(firmName)'''
    g.run(index)
    print("Create index on DrugFirm(firmName)")


    file = 'file:///drls_reg.txt'
    df_node = create_DrugFirm_node(file, g)
    print("Finish loading DrugFirm")
开发者ID:neo4j-examples,项目名称:health-graph,代码行数:33,代码来源:load_drugfirm.py

示例10: BaseContext

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
class BaseContext(object):
    """
    Base CorpusContext class.  Inherit from this and extend to create
    more functionality.

    Parameters
    ----------
    args : arguments or :class:`~polyglotdb.config.CorpusConfig`
        If the first argument is not a CorpusConfig object, it is
        the name of the corpus
    kwargs : keyword arguments
        If a :class:`~polyglotdb.config.CorpusConfig` object is not specified, all arguments and
        keyword arguments are passed to a CorpusConfig object
    """
    def __init__(self, *args, **kwargs):
        if len(args) == 0:
            raise(CorpusConfigError('Need to specify a corpus name or CorpusConfig.'))
        if isinstance(args[0], CorpusConfig):
            self.config = args[0]
        else:
            self.config = CorpusConfig(*args, **kwargs)
        self.config.init()
        self.graph = Graph(**self.config.graph_connection_kwargs)
        self.corpus_name = self.config.corpus_name
        if self.corpus_name:
            self.init_sql()

        self.hierarchy = Hierarchy({})

        self.lexicon = Lexicon(self)
        self.census = Census(self)

        self._has_sound_files = None
        self._has_all_sound_files = None
        if getattr(sys, 'frozen', False):
            self.config.reaper_path = os.path.join(sys.path[-1], 'reaper')
        else:
            self.config.reaper_path = shutil.which('reaper')

        if sys.platform == 'win32':
            praat_exe = 'praatcon.exe'
        else:
            praat_exe = 'praat'

        if getattr(sys, 'frozen', False):
            self.config.praat_path = os.path.join(sys.path[-1], praat_exe)
        else:
            self.config.praat_path = shutil.which(praat_exe)

        self.config.query_behavior = 'speaker'

    def load_variables(self):
        """
        Loads variables into Hierarchy
        """
        try:
            with open(os.path.join(self.config.data_dir, 'variables'), 'rb') as f:
                var = pickle.load(f)
            self.hierarchy = var['hierarchy']
        except FileNotFoundError:
            if self.corpus_name:
                self.hierarchy = self.generate_hierarchy()
                self.save_variables()

    def save_variables(self):
        """ saves variables to hierarchy"""
        with open(os.path.join(self.config.data_dir, 'variables'), 'wb') as f:
            pickle.dump({'hierarchy': self.hierarchy}, f)

    def init_sql(self):
        """
        initializes sql connection
        """
        self.engine = create_engine(self.config.sql_connection_string)
        Session.configure(bind=self.engine)
        if not os.path.exists(self.config.db_path):
            Base.metadata.create_all(self.engine)

    def execute_cypher(self, statement, **parameters):
        """
        Executes a cypher query
        
        Parameters
        ----------
        statement : str
            the cypher statement
        parameters : dict
            keyword arguments to execute a cypher statement

        Returns
        -------
        query result : 
        or
        raises error

        """
        try:
            return self.graph.run(statement, **parameters)
        except py2neo.packages.httpstream.http.SocketError:
            raise(ConnectionError('PolyglotDB could not connect to the server specified.'))
#.........这里部分代码省略.........
开发者ID:esteng,项目名称:PolyglotDB,代码行数:103,代码来源:base.py

示例11: Graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
server = conf["protocol"]+"://"+conf["host"]+":"+str( conf["port"] )

logging.basicConfig(level=logging.ERROR)

numiter = 10000

graph = Graph(server)

label = "TAXID"

# Hashes for storing stuff
parentid={}
scientific_list={}
names_list={}

idxout = graph.run("CREATE CONSTRAINT ON (n:"+label+") ASSERT n.id IS UNIQUE")

def process_relationship( statements, graph ):
	
	tx = graph.begin()
	
	#print statements
	logging.info('proc sent')
	
	for statement in statements:
		#print statement
		start = graph.nodes.match(statement[0], id=int( statement[1] )).first()
		end = graph.nodes.match(statement[0], id=int( statement[2] )).first()
		rel = Relationship( start, statement[3], end )
		
		tx.create( rel )
开发者ID:toniher,项目名称:neo4j-biorelation,代码行数:33,代码来源:neo4j2-import-ncbi.py

示例12: Graph

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

if __name__ == "__main__":
    pw = os.environ.get('NEO4J_PASS')
    g = Graph("http://localhost:7474/", password=pw)  ## readme need to document setting environment variable in pycharm
    # g.delete_all()
    tx = g.begin()

    index1 = '''
    CREATE INDEX ON: Contribution(type)
    '''
    index2 = '''
    CREATE INDEX ON: Committee(name)
    '''
    g.run(index1)
    g.run(index2)

    # root =  os.getcwd()
    # path = os.path.join(root, "data")
    # disclosure_1st_path = os.path.join(path, "2013_MidYear_XML")
    # files = [f for f in os.listdir(disclosure_1st_path) if f.endswith('.xml')]
    # files = ['file:///Users/yaqi/Documents/health-graph/data/2013_MidYear_XML/700669542.xml']  # Return xml files

    def get_file_path(kind):
        root_dir = '/Users/yaqi/Documents/data/' + kind
        filenames = [f for f in os.listdir(root_dir) if f.endswith('.xml')]
        filepath = []
        for file in filenames:
            path = 'file://' + os.path.join(root_dir, file)
            filepath.append(path)
开发者ID:neo4j-examples,项目名称:health-graph,代码行数:32,代码来源:load_contribution.py

示例13: Graph

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

graph = Graph(password='neo4jneo4j')

results = graph.run(
    'MATCH (s:asn)-[r:TO]->(d:asn) '
    'RETURN s.name as source, r as relationship, d.name as dest '
    'LIMIT 100'
)

for source, relationship, dest in results:
    print('source: {} dest: {} relationship: {}'.format(source, dest, relationship))
开发者ID:wicaksana,项目名称:anycast-dns-monitoring-framework,代码行数:14,代码来源:py2neo_access_data_01.py

示例14: Graph

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
from string_converter import uniq_elem
from fuzzywuzzy import fuzz


if __name__ == "__main__":
    pw = os.environ.get('NEO4J_PASS')
    g = Graph("http://localhost:7474/", password=pw)
    tx = g.begin()

    idx1 = '''
    CREATE INDEX ON: Legislator(name)
    '''
    idx2 = '''
    CREATE INDEX ON: LegislatorInfo(wikipediaID)
    '''
    g.run(idx1)
    g.run(idx2)


    create_legislatorInfo = '''
    LOAD CSV WITH HEADERS
    FROM 'https://dl.dropboxusercontent.com/u/67572426/legislators-current.csv' AS line
    MERGE (legislator:LegislatorInfo { thomasID: line.thomasID })
    ON CREATE SET legislator = line
    ON MATCH SET legislator = line
    MERGE (s:State {code: line.state})
    CREATE UNIQUE (legislator)-[:REPRESENTS]->(s)
    MERGE (p:Party {name: line.currentParty})
    CREATE UNIQUE (legislator)-[:IS_MEMBER_OF]->(p)
    MERGE (b:Body {type: line.type})
    CREATE UNIQUE (legislator)-[:ELECTED_TO]->(b);
开发者ID:neo4j-examples,项目名称:health-graph,代码行数:33,代码来源:Load_legislatorInfo.py

示例15: authenticate

# 需要导入模块: from py2neo import Graph [as 别名]
# 或者: from py2neo.Graph import run [as 别名]
import traceback
import psycopg2 
import psycopg2.extras
import sys
from py2neo import Graph, Node, Relationship, watch, authenticate


http_port = 7474
bolt_port = 7687
host = "x.com.cn"

authenticate("%s:%s" % (host, http_port), "name", "password")
# connect to authenticated graph database
g = Graph("http://%s:%s/db/data/" % (host, http_port), bolt_port=bolt_port)
g.data('match (n) return count(*)')
g.run('match (n) return count(*)').dump()
now_datetime = datetime.datetime.now()

def getDBConnection():
    conn = psycopg2.connect(
        host="x.com.cn",
        port=432,
        user="uu",
        password="xx",
        dbname="xx",
        connect_timeout=10)
    return conn

watch('httpstream')

conn = getDBConnection()
开发者ID:XuChongBo,项目名称:pydemo,代码行数:33,代码来源:neo4j_import_nodes.py


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