You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SHACL验证至多含一个取值的联合数据类型属性

用SHACL实现联合类型的互斥子属性约束

你提到的SHACL union约束确实用于数据类型或类的联合选择,和你需要的「子属性互斥(最多1个有值)」需求不匹配,这里提供两种可行的实现方案:

方案1:枚举互斥属性组合(适合属性少的场景)

直接用sh:or定义所有允许的情况——要么只有其中一个子属性有值,要么所有子属性都为空:

shape:DtuAfmetingVerkeersbordShape
    a sh:NodeShape ;
    sh:targetClass ont:DtuAfmetingVerkeersbord ;
    sh:or (
        # 仅允许rond属性存在
        [ sh:property [ sh:path ont:rond ; sh:maxCount 1 ] ]
        # 仅允许driehoekig属性存在
        [ sh:property [ sh:path ont:driehoekig ; sh:maxCount 1 ] ]
        # 可继续添加其他子属性的单属性约束
        [ sh:property [ sh:path ont:vierkant ; sh:maxCount 1 ] ]
        # 所有子属性都为空的情况(可选,若允许0个属性则保留)
        [ sh:property [ sh:path ont:rond ; sh:maxCount 0 ]
          sh:property [ sh:path ont:driehoekig ; sh:maxCount 0 ]
          sh:property [ sh:path ont:vierkant ; sh:maxCount 0 ] ]
    ) ;
    # 可选:关闭形状,防止添加未定义的子属性
    sh:closed true ;
    sh:ignoredProperties ( rdf:type ) .

方案2:SPARQL自定义约束(适合属性多或需扩展的场景)

通过SPARQL查询统计实例中已赋值的目标子属性数量,超过1则触发错误:

shape:DtuAfmetingVerkeersbordShape
    a sh:NodeShape ;
    sh:targetClass ont:DtuAfmetingVerkeersbord ;
    sh:sparql [
        sh:message "仅允许0个或1个子属性(rond/driehoekig/...)拥有取值" ;
        sh:select """
            SELECT $this
            WHERE {
                $this ?subProp ?value .
                # 枚举所有需要互斥的子属性
                FILTER (?subProp IN (ont:rond, ont:driehoekig, ont:vierkant))
            }
            GROUP BY $this
            HAVING (COUNT(DISTINCT ?subProp) > 1)
        """ ;
    ] ;
    sh:closed true ;
    sh:ignoredProperties ( rdf:type ) .

关联到Verkeersbord的afmeting属性

最后把上面的形状绑定到交通标识的尺寸属性上:

shape:VerkeersbordShape
    a sh:NodeShape ;
    sh:targetClass ont:Verkeersbord ;
    sh:property [
        sh:path ont:afmeting ;
        sh:node shape:DtuAfmetingVerkeersbordShape ;
    ] .

这样就能实现你要的验证:A.afmeting同时有rond和driehoekig值时,会被判定为无效。

内容的提问来源于stack exchange,提问作者David Vlaminck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:05:32