我在试着从grakn中输出边缘。我可以通过Python客户机这样做:
edge_query = "match $c2c($c1, $c2) isa c2c; $c1 has id $id1; $c2 has id $id2;get $id1,$id2;"
with open(f"grakn.edgelist","w") as outfile:
with GraknClient(uri="localhost:48555") as client:
with client.session(keyspace=KEYSPACE) as session:
with session.transaction().read() as read_transaction:
answer_iterator = read_transaction.query(edge_query)
for answer in tqdm(answer_iterator):
id1 = answer.get("id1")
id2 = answer.get("id2")
outfile.write(f"{id1.value()} {id2.value()} \n")
编辑:对于每一个Relation
,我想要成对地导出实体。输出可以是一对Grakn ID。我可以忽略关系或实体的属性。
导出到边缘似乎是一项常见的任务。在Grakn中是否有更好的方法(更优雅、更快、更高效)来做到这一点?
发布于 2020-02-20 14:39:40
只要关系类型c2c
总是有两个角色播放器,就可以工作。但是,这将为每个$c1, $c2
生成两个边,这可能不是您想要的。
让我们来看看ids V123
和V456
的一对东西。如果它们满足$c2c($c1, $c2) isa c2c;
的$c1 = V123
和$c2 = V456
,那么它们也将满足与$c1 = V456
和$c2 = V123
相同的模式。Grakn将返回满足您的查询的所有$c1, $c2
组合,因此您将为这个c2c
关系返回两个答案。
假设这不是您想要的,如果$c1
和$c2
在关系c2c
中扮演不同的角色(可能意味着有指向边缘的方向),那么尝试更改查询,添加角色,以:
edge_query = "match $c2c(role1: $c1, role2: $c2) isa c2c; $c1 has id $id1; $c2 has id $id2; get $id1,$id2;"
如果它们都扮演着相同的角色(暗示没有方向的边),那么我们需要在逻辑上做一些不同的事情。或者将边缘存储为一组ids集,无需花费太多精力就可以删除重复的ids,或者考虑使用Python ConceptAPI,如下所示:
relation_query = "match $rc2c isa c2c;get;"
with open(f"grakn.edgelist","w") as outfile:
with GraknClient(uri="localhost:48555") as client:
with client.session(keyspace=KEYSPACE) as session:
with session.transaction().read() as read_transaction:
answer_iterator = read_transaction.query(relation_query)
for answer in answer_iterator:
relation_concept = answer.get("rc2c")
role_players_map = relation_concept.role_players_map()
role_player_ids = set()
for role, thing in role_players_map.items():
# Here you can do any logic regarding what things play which roles
for t in thing:
role_player_ids.add(t.id) # Note that you can retrieve a concept id from the concept object, you don't need to ask for it in the query
outfile.write(", ".join(role_player_ids) + "\n")
当然,我不知道你对最终的编辑者做了什么,但是为了完整,更像Grakn-esque的方法是将这种关系作为一个头等公民来处理,因为它代表着Grakn知识模型中的一个超边,在这种情况下,我们会把这种关系的角色看作边。这意味着,当我们有三元关系或N-值关系时,我们就不会陷入困境。我们可以通过更改查询来做到这一点:
match $c2c($c) isa c2c; get;
然后得到$c2c
和$c
的id。
https://stackoverflow.com/questions/60273290
复制相似问题