TigerGraph Cloud 使用,以及Python的链接操作

2022-04-15 00:00:00 数据 执行 就会 点击 就可以

点击start free


 

登录已有的账号 或者注册个新的


然后进入了cloud 主界面


然后点击 my solutions,我这里面已经创建了几个,才进入的时候应该什么都没有。点击create solution


这里可以选择tigergraph的版本,以及他已经有的模板,或者建立一个blank的solution。


next之后可以选择配置,默认的配置都是免费的,你也可以升级配置,只不过就需要给钱了,当然选择距离你比较近的Region是可以的,这改变不会花钱。


 

next之后这两个比较重要,一个是登录你solution的密码,还有个是域名,这两个之后都会用到。

当然免费的solution只能同时存在一个,新建一个免费的之后必须先终止该soluion才能新建第二个免费solution。

完成之后回到my solution界面,等待几分钟,可以在pengding tasks里面看到正在创建,


创建好了之后,就可以点击这个GraphStudio进入可视化管理。他默认用户名就是tigergraph,密码就是一开始设置的 。


 

进入之后点击Global View 进入具体的Graph。


这时候就可以看到模板solution的graph了。

接下来我会介绍怎么自己新建自己的Graph和插入数据


点击Global Views的 create a graph ,然后进入新的graph,在Design Schema中点击那个加号button新建Vertex 也就是 顶点,类似于neo4j中的node,右边可以规定该vertex的颜色属性之类的参数。


 

当建立多个vertex之后,可以点击圈中button,再依次点击想建立edge的两个vertex,这就相当于neo4j中的relastionship,右边就可以自定义该edge的type,以及具体属性,这里还可以设置该edge是有向边还是无向边(就是有无方向的指代)。需要注意的是,同一个type只能新建一次,


 

如果像这种情况,我还想让applicationlog 与message拥有have的edge怎么办呢,这时候就可以双击这个have的edge,就会出现右边的操作panel,就可以看到该type的edge的具体配置,点击加号,再选择你想链接的vertex,再点右上角的勾就可以了。


后重要的一步,schema定义好之后,点击圈中button,提交修改,虽然这时候切换其他tab他也会提醒你,但是以防万一,还是好自己点击提交。


这时候我们就需要导入数据模型,点击第二个tab,Map Data to Graph 。


点击圈中button,唤出上传的popup。我这里已经上传过,所以有很多文件,正常次进来应该是没有的,除非是使用的模板solution,点击加号上传你的csv, 包括vertex数据,以及edge数据(简言之就是节点数据以及关系数据)


我的vertex 以及edge 的csv结构就像上面的截图一样


上传之后,点击要添加的csv,就会出现这个,可以配置怎么解析这个csv,这里has header默认没有打勾,因为我的csv有header,所以打勾了,否则他会把header当成列的数据,确认无误之后就可以点击ADD了


添加完成之后,点击圈中button,来关联你的csv与vertex或者edge,点击button之后依次点击需要绑定的csv与vertex或edge,然后回出现右边的panel,这时候需要把csv中的属性,与vertex或者edge中的属性做匹配,依次点击相匹配的属性,例如点击左边的id 再点击右边的id


然后就会出现指向箭头显示我们所绑定的关系。然后就绑定每个csv与需要绑定的vertex或者edge


 

所有绑定完成之后就可以看到每个csv都有指向的vertex或者edge,这时候再点击左上角的提交button,和上一个design schema的操作一样,提交你的修改


 

然后进入Load Data tab,导入数据,然后点击圈中的button,然后点击continue来导入全部数据,等待一会就可以看到所有的csv都是finish了,右边可以看到Vertex 以及edge的统计数据以及每一个type的数量。

然后跳过Explore Graph 以及Build Graph Partterns。直接介绍后一个 GSQL查询。


我这里已经有几个query了,可以看到这些query有些右边的图标不一样,有些保存的图标,有些是箭头,保存图标代表只是保存个这个query,还不能使用,向上箭头代表该query已经被install了,只有install之后的query才能使用 。

点击加号来新建query,名字必须和圈中名字一致,这个就是填好名字之后自动生成的gsql模板。这个gsql使用C++编写的。tigergraph提供一些现成的algo,在GitHub可以找到,可以直接复制出来贴到这里面。

https://github.com/tigergraph/gsql-graph-algorithms

这些算法的doc我也贴出来了。

TigerGraph Graph Data Science Library - TigerGraph Documentation


等写完gsql之后点击第二个圈中button保存,之后可以点击第三个button来install这个query,或者点击个install全部的query 。


install完成之后 点击这个button,会出现一个pannel来输入参数,输入完参数之后滚动到下面点击Run Query,就可以执行这个gsql了。

有时候我们数据量比较大或者配置低了再加上algo比较复杂,一次查询时间会超出默认的timeout(60s),就会报错,这时候点击这里


admin > management > components > restpp


这里可以修改默认timeout时间,我改成了一小时。

接下来介绍下python来链接tigergraph并执行gsql进行查询。

首先安装需要的插件

pip install pyTigerGraph
k-Nearest Neighbors (Cross-Validation Version) - TigerGraph Documentation

接下来的demo就是python链接tigergraph执行了k-Nearest Neighbors (Cross-Validation Version) algo

import pyTigerGraph as tg


def createQueary(conn):
knn_sub = '''
CREATE QUERY tg_knn_cosine_cv_sub (VERTEX source, SET<STRING> e_type, SET<STRING> re_type, STRING v_label, STRING weight, INT max_k) RETURNS (ListAccum<INT>) {
/* This subquery returns a list of predicted label for a source vertex with respect to different k within a given range.
*/
TYPEDEF TUPLE <label INT, similarity FLOAT> Label_Score;
HeapAccum<Label_Score>(max_k, similarity DESC) @@top_labels_heap; # heap stores the (label, similarity) tuple, order by similarity score
SumAccum<FLOAT> @numerator, @@norm1, @norm2, @similarity;
MapAccum<INT, INT> @@count;
ListAccum<INT> @@predicted_label_lists; # list of predicted labels to return
INT max_count = 0;
INT predicted_label; # predicted label in each iteration
INT k;
# calculate similarity and find the top k nearest neighbors
start = {source};
subjects = SELECT t
FROM start:s -(e_type:e)-> :t
ACCUM t.@numerator = e.getAttr(weight, "INT"),
@@norm1 += pow(e.getAttr(weight, "INT"), 2);
neighbours = SELECT t
FROM subjects:s -(re_type:e)-> :t
WHERE t != source AND t.getAttr(v_label, "INT") != 0 # only consider the neighbors with known label (TODO: EXCLUDES COMMUNITY 0)
ACCUM t.@numerator += s.@numerator * e.getAttr(weight, "INT");
kNN = SELECT s
FROM neighbours:s -(e_type:e)-> :t
ACCUM s.@norm2 += pow(e.getAttr(weight, "INT"), 2)
POST-ACCUM @@top_labels_heap += Label_Score(s.getAttr(v_label, "INT"), s.@numerator/sqrt(@@norm1 * s.@norm2)); # store the label and similarity score in a heap
# iterate the heap and calculate label count for different k
k = 1;
FOREACH item IN @@top_labels_heap DO
@@count += (item.label -> 1); # count is a map, key is the label, value is the count of the label
IF @@count.get(item.label) > max_count THEN
max_count = @@count.get(item.label);
predicted_label = item.label;
END;
@@predicted_label_lists += predicted_label; # list of predicted labels
k = k+1;
END;

PRINT @@predicted_label_lists;
RETURN @@predicted_label_lists;
}
'''

print(conn.gsql(knn_sub + "\n INSTALL QUERY tg_knn_cosine_cv_sub"))

knn_cv = '''
CREATE QUERY tg_knn_cosine_cv (SET<STRING> v_type, SET<STRING> e_type, SET<STRING> re_type, STRING weight, STRING label, INT min_k, INT max_k) RETURNS (INT){
/* Leave-one-out cross validation for selecting optimal k.
The input is a range of k, output is the k with highest correct prediction rate.
Note: When one vertex has no neighbor with known label, the prediction is considered false
*/
ListAccum<FLOAT> @@correct_rate_list;
ListAccum<INT> @is_correct_list;
ListAccum<INT> @predicted_label_list;
SumAccum<FLOAT> @@total_score;
INT n, k, best_k=1;
FLOAT max_rate=0;

IF max_k < min_k OR max_k < 1 THEN // terminate if the range is invalid
RETURN 0;
END;
start = {v_type};

start = SELECT s
FROM start:s
WHERE s.getAttr(label, "INT") != 0 // get the vertices with known label (TODO: EXCLUDES COMMUNITY NUMBER 0)
ACCUM s.@predicted_label_list = tg_knn_cosine_cv_sub(s, e_type, re_type, label, weight, max_k) // get a list of predicted label wrt different k
POST-ACCUM FOREACH pred_label IN s.@predicted_label_list DO
IF s.getAttr(label, "INT") == pred_label THEN # *vStrAttrOld* means no neighbor with label
s.@is_correct_list += 1
ELSE
s.@is_correct_list += 0
END
END;

n = start.size();
k = min_k-1; # index starts from 0
WHILE k < max_k DO
@@total_score = 0;
start = SELECT s
FROM start:s
ACCUM IF s.@is_correct_list.size()==0 THEN
@@total_score += 0 # if there is no neighbor, it is considered incorrect prediction
ELSE IF k >= s.@is_correct_list.size() THEN
@@total_score += s.@is_correct_list.get(s.@is_correct_list.size()-1) # use all neighbors it has when it is not enough
ELSE
@@total_score += s.@is_correct_list.get(k)
END;
@@correct_rate_list += @@total_score / n;
IF @@total_score / n > max_rate THEN
max_rate = @@total_score / n; # store the max correct rate in max_rate
best_k = k+1;
END;
k = k+1;
END;
PRINT @@correct_rate_list;
PRINT best_k;
RETURN best_k;
}
'''

print(conn.gsql(knn_cv + "\n INSTALL QUERY tg_knn_cosine_cv"))



def connect():
host = 'https://xxxxxxxxxxxxxxx.i.tgcloud.io/'
username = 'tigergraph'
password = 'xxxxxxx'

conn = tg.TigerGraphConnection(host=host,
username=username,
password=password,
graphname='test')
conn.apiToken = conn.getToken(conn.createSecret())

createQueary(conn)
params = {
"v_type": "Prescriber",
"e_type": "referral",
"re_type": "reverse_referral",
"weight": "num_patient",
"label": "communityId",
"min_k": 1,
"max_k": 7
}
res = conn.runInstalledQuery("tg_knn_cosine_cv", params=params)
print(res)


def main():
connect()


if __name__ == '__main__':
main()
下面的code 就是python使用pyTigerGraph链接tigergraph的方法,host就是创建solution时候自己自定义的,密码也是。

之后就可以用得到的conn在执行gsql了。

host = 'https://xxxxxxxxxxxxxxx.i.tgcloud.io/'
username = 'tigergraph'
password = 'xxxxxxx'

conn = tg.TigerGraphConnection(host=host,
username=username,
password=password)
conn.apiToken = conn.getToken(conn.createSecret())
conn.gsql(..........)
conn.gsql(knn_sub + "\n INSTALL QUERY tg_knn_cosine_cv_sub")
我是把knn的algo直接copy进来了,和在UI中做的一样 。然后又换行执行的安装该algo。

params = {
"v_type": "Prescriber",
"e_type": "referral",
"re_type": "reverse_referral",
"weight": "num_patient",
"label": "communityId",
"min_k": 1,
"max_k": 7
}
res = conn.runInstalledQuery("tg_knn_cosine_cv", params=params)
print(res)
然后就可以传入参数执行该query,这里我用的是TigerGraph提供的Healthcare-analytics 模板中的数据执行的该algo


执行之后,可以看到不同的K值得分,佳的k值应为3

相关文章