gpt4 book ai didi

graph-databases - GRAQL 中的递归查询?

转载 作者:行者123 更新时间:2023-12-05 04:58:56 24 4
gpt4 key购买 nike

有没有一种方法可以在 GRAQL 中定义递归查询,即匹配实体之间的确切谓词路径未知(例如,有多少实体)的模式?

SPARQL 在 1.1 版本中添加了对这些的支持。来自 Apache Jena Documentation 的示例:

# Find the types of :x, following subClassOf
SELECT *
{
:x rdf:type/rdfs:subClassOf* ?t
}

CYPHER 从一开始就允许它们。示例:

MATCH (alice:Person { name:"Alice" })-[:friend *1..2]->(friend:Person)
RETURN friend.name;

是否可以在 GRAQL 中做类似的事情?

最佳答案

可以使用 Grakn 的推理引擎在 Graql 中实现这一点。

Graql match 查询不支持循环查询语法(目前已在计划中),但您可以使用 rule 在 Grakn 中定义递归逻辑。要实现递归,应该有一个规则在其 when 中包含与在规则的 then 中推断出的类型相同的内容。

在 Graql 中,这个 friend 示例如下所示。此示例不使用递归,因为我们只寻找 1 跳或 2 跳循环。

首先你需要一个模式:

define

name sub attribute, value string;

person sub entity,
has name,
plays friend;

friend sub relation,
relates friend;

如果这是您的起始模式,您需要按如下方式扩展它以在新的 n-degree-friendship 关系中添加递归:

define

friend-of-a-friend isa relation,
relates connected-friend;

person sub entity,
plays connected-friend;

infer-friend-of-a-friend sub rule,
when {
(friend: $p1, friend: $p2) isa friendship;
(friend: $p2, friend: $p3) isa friendship;
}, then {
(connected-friend: $p1, connected-friend: $p3) isa friend-of-a-friend;
};

然后您可以查询由任意数量的friendship 关系连接的 friend :

match $p1 isa person, has name "John"; 
$p2 isa person, has name $n;
{ (connected-friend: $p1, connected-friend: $p2) isa friend-of-a-friend; }
or { (friend: $p1, friend: $p2) isa friendship; };
get $n;

这个 friend 示例不是递归的,但它可以扩展为递归的。 Grakn 目前不能支持的是循环次数。

我们可以在 subClassOf 示例中看到一个很好的递归示例:

define

class sub entity,
plays subclass,
plays superclass;

class-hierarchy sub relation,
relates subclass,
relates superclass;

class-hierarchy-is-recursive sub rule,
when {
(subclass: $c1, superclass: $c2) isa class-hierarchy;
(subclass: $c2, superclass: $c3) isa class-hierarchy;
}, then {
(subclass: $c1, superclass: $c3) isa class-hierarchy;
};

然后匹配找到x的所有子类:

match $x isa class; 
$y isa class;
(superclass: $x, subclass: $x) isa subclass;
get $y;

关于graph-databases - GRAQL 中的递归查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63778221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com