首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在不使用客户端API的情况下从Grakn导出edgelist

如何在不使用客户端API的情况下从Grakn导出edgelist
EN

Stack Overflow用户
提问于 2020-02-18 03:20:01
回答 1查看 76关注 0票数 1

我在试着从grakn中输出边缘。我可以通过Python客户机这样做:

代码语言:javascript
运行
复制
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中是否有更好的方法(更优雅、更快、更高效)来做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-20 14:39:40

只要关系类型c2c总是有两个角色播放器,就可以工作。但是,这将为每个$c1, $c2生成两个边,这可能不是您想要的。

让我们来看看ids V123V456的一对东西。如果它们满足$c2c($c1, $c2) isa c2c;$c1 = V123$c2 = V456,那么它们也将满足与$c1 = V456$c2 = V123相同的模式。Grakn将返回满足您的查询的所有$c1, $c2组合,因此您将为这个c2c关系返回两个答案。

假设这不是您想要的,如果$c1$c2在关系c2c中扮演不同的角色(可能意味着有指向边缘的方向),那么尝试更改查询,添加角色,以:

代码语言:javascript
运行
复制
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,如下所示:

代码语言:javascript
运行
复制
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-值关系时,我们就不会陷入困境。我们可以通过更改查询来做到这一点:

代码语言:javascript
运行
复制
match $c2c($c) isa c2c; get;

然后得到$c2c$c的id。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60273290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档