World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Imported attributes get created, and a value we can store is kept (#64)
WaylandYang04c3f738e1ea
diff --git a/crates/utopia-ingest/src/ontology_rdf.rs b/crates/utopia-ingest/src/ontology_rdf.rsindex 383b76d3..a9c9cbe7 100644--- a/crates/utopia-ingest/src/ontology_rdf.rs+++ b/crates/utopia-ingest/src/ontology_rdf.rs@@ -261,7 +261,11 @@ pub fn project(bytes: &[u8], format: RdfFormat) -> anyhow::Result<OwlProjection>iri: iri.clone(),});}- for iri in obj_props.iter().chain(data_props.iter()) {+ // **并集去重,不是两个集合首尾相接**:词汇表常把同一个属性既声明为+ // rdf:Property 又声明为 owl:DatatypeProperty(FOAF 的 name、age、nick… 都这样),+ // 两个集合各收一次,chain 就会把它吐两遍。分类看 data_props 就够了。+ let all_props: BTreeSet<&String> = obj_props.iter().chain(data_props.iter()).collect();+ for iri in all_props {proj.properties.push(OwlProperty {key: key_from_iri(iri),label: pick_lang(labels.get(iri))@@ -328,10 +332,211 @@ pub fn key_from_iri(iri: &str) -> String {out.chars().take(40).collect()}+const XSD: &str = "http://www.w3.org/2001/XMLSchema#";+const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";++/// `rdfs:range` 映射到我们的四种 datatype 的结果。**三路,不是两路**。+#[derive(Debug, Clone, PartialEq)]+pub enum RangeMapping {+ /// 能映射到 `text` / `number` / `date` / `bool`+ Datatype(&'static str),+ /// 压根没写 range:词汇表没做任何声明,只知道是字面量。+ /// `text` 是诚实的超集(它接受任何字符串,从不拦),所以建、并在预览里列出+ Absent,+ /// 写了 range,值是**短的可读字面量**,但我们的四种类型表达不了它+ ///(`time` 没有年、`duration` 是时长不是时点)。按 `text` 建**并报告**:+ /// 只丢了排序语义,值还在;跳过则是这条知识彻底不会被捕获,那更糟+ Degraded(String),+ /// 写了 range,而**抽取器永远不可能从散文里读出这个值**:二进制块、+ /// XML 片段、XML 内部标识。跳过它保护不了任何数据(本来就不会有值),+ /// 省掉的是提示词——每个属性都是抽取提示词里的一行,每个文本块付一遍+ Unusable(String),+}++/// 数据属性的 `rdfs:range` → datatype。+///+/// 按**完整 IRI** 匹配而不是局部名:自定义词汇表完全可能有个叫 `date` 的类,+/// 按尾巴匹配会把它当成 `xsd:date`。+///+/// 多条 range 一律 [`RangeMapping::Degraded`]——RDFS 里那是**交集**语义+///("必须同时是两者"),几乎总是建模笔误,但规范如此,不猜。+pub fn map_range(ranges: &[String]) -> RangeMapping {+ match ranges {+ [] => RangeMapping::Absent,+ [one] => match datatype_of(one) {+ Some(dt) => RangeMapping::Datatype(dt),+ None if unusable(one) => RangeMapping::Unusable(one.clone()),+ None => RangeMapping::Degraded(one.clone()),+ },+ // 多条 range 是交集语义,不猜类型——但值仍是字面量,所以按 text 建+ many => RangeMapping::Degraded(many.join(" ∩ ")),+ }+}++/// 抽取器不可能从散文里读出来的那些:二进制块与 XML 内部管道。+///+/// 判据不是"这个值该不该存"——属性值本来就存在图谱里(走 `facts.object_value`,+/// 证据、时态、审阅全套)。判据是**会不会有值**:「门店每天 9:00 开门」里有+/// `09:00`,而一张 base64 平面图不会出现在散文里;就算文档里真有一段 base64,+/// 把它当成事实抽出来也是错的。+///+/// **其余一律降级成 text**——一个抽得出来的值,宁可类型糙一点也别让它没处可去。+fn unusable(iri: &str) -> bool {+ if let Some(local) = iri.strip_prefix(XSD) {+ return matches!(+ local,+ "base64Binary"+ | "hexBinary"+ | "QName"+ | "NOTATION"+ | "ID"+ | "IDREF"+ | "IDREFS"+ | "ENTITY"+ | "ENTITIES"+ );+ }+ if let Some(local) = iri.strip_prefix(RDF_NS) {+ return local == "XMLLiteral";+ }+ false+}++fn datatype_of(iri: &str) -> Option<&'static str> {+ if let Some(local) = iri.strip_prefix(XSD) {+ return match local {+ // 有界与无符号变体全部收进 number:区别在取值范围,不在语义+ "decimal" | "integer" | "int" | "long" | "short" | "byte" | "nonNegativeInteger"+ | "positiveInteger" | "nonPositiveInteger" | "negativeInteger" | "unsignedLong"+ | "unsignedInt" | "unsignedShort" | "unsignedByte" | "double" | "float" => {+ Some("number")+ }+ // 我们的日期格式本就是 YYYY[-MM[-DD]],逐级可省,所以 gYear / gYearMonth 装得下+ "date" | "dateTime" | "dateTimeStamp" | "gYear" | "gYearMonth" => Some("date"),+ "boolean" => Some("bool"),+ "string" | "normalizedString" | "token" | "language" | "Name" | "NCName"+ | "NMTOKEN" | "anyURI" => Some("text"),+ // time / gMonth / gDay / gMonthDay 缺年,duration 系列是时长不是时点 ——+ // 落到 None,再由 unusable() 分流:它们是可读字面量,降级成 text;+ // 二进制与 XML 内部标识才是真的不收+ _ => None,+ };+ }+ if let Some(local) = iri.strip_prefix(RDF_NS) {+ // XMLLiteral 是 XML 片段,不收+ return matches!(local, "PlainLiteral" | "langString").then_some("text");+ }+ if let Some(local) = iri.strip_prefix(RDFS) {+ return (local == "Literal").then_some("text");+ }+ if let Some(local) = iri.strip_prefix(OWL) {+ return matches!(local, "real" | "rational").then_some("number");+ }+ None+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn range_maps_every_numeric_variant() {+ for local in [+ "decimal",+ "integer",+ "int",+ "long",+ "short",+ "byte",+ "nonNegativeInteger",+ "positiveInteger",+ "nonPositiveInteger",+ "negativeInteger",+ "unsignedLong",+ "unsignedInt",+ "unsignedShort",+ "unsignedByte",+ "double",+ "float",+ ] {+ assert_eq!(+ map_range(&[format!("{XSD}{local}")]),+ RangeMapping::Datatype("number"),+ "{local}"+ );+ }+ // owl:real / owl:rational 也在 OWL 2 的 datatype map 里+ assert_eq!(+ map_range(&[format!("{OWL}rational")]),+ RangeMapping::Datatype("number")+ );+ }++ /// 我们的日期格式是 YYYY[-MM[-DD]],逐级可省,所以只缺低位的 g 类型装得下+ #[test]+ fn partial_dates_fit_only_when_the_year_is_there() {+ for local in ["date", "dateTime", "dateTimeStamp", "gYear", "gYearMonth"] {+ assert_eq!(+ map_range(&[format!("{XSD}{local}")]),+ RangeMapping::Datatype("date"),+ "{local}"+ );+ }+ // 缺年的进不了 date —— 但它们是可读字面量,降级成 text 而不是丢掉+ for local in ["gMonth", "gDay", "gMonthDay", "time"] {+ assert!(+ matches!(+ map_range(&[format!("{XSD}{local}")]),+ RangeMapping::Degraded(_)+ ),+ "{local} 该降级成 text,不该丢"+ );+ }+ }++ /// 分界不是"能不能精确映射",而是**"这个取值该不该进图谱"**。+ /// 存得下的一律留下来——类型糙一点,好过这条知识彻底不被捕获。+ #[test]+ fn a_value_we_can_store_is_kept_even_when_we_cannot_type_it() {+ // 没写 range:没有声明可丢,text 是诚实的超集+ assert_eq!(map_range(&[]), RangeMapping::Absent);+ // 写了但表达不了:时长是可读字面量,降级成 text 并报告+ assert!(matches!(+ map_range(&[format!("{XSD}duration")]),+ RangeMapping::Degraded(_)+ ));+ // 取值本就不该进图谱:二进制块与 XML 片段,这才是真的跳过+ assert!(matches!(+ map_range(&[format!("{XSD}base64Binary")]),+ RangeMapping::Unusable(_)+ ));+ assert!(matches!(+ map_range(&[format!("{RDF_NS}XMLLiteral")]),+ RangeMapping::Unusable(_)+ ));+ }++ /// 多条 range 在 RDFS 里是**交集**("必须同时是两者"),不是并集。+ /// 几乎总是建模笔误,但规范如此 —— 不猜。+ #[test]+ fn several_ranges_are_an_intersection_we_refuse_to_guess() {+ let m = map_range(&[format!("{XSD}string"), format!("{XSD}integer")]);+ match m {+ // 交集不猜类型,但值仍是字面量,所以按 text 落下来+ RangeMapping::Degraded(s) => assert!(s.contains('∩')),+ other => panic!("多条 range 不该被精确映射: {other:?}"),+ }+ }++ /// 按完整 IRI 匹配:自定义词汇表里叫 date 的**类**不是 xsd:date+ #[test]+ fn a_class_that_happens_to_be_called_date_is_not_a_date() {+ assert!(matches!(+ map_range(&["http://acme.example/hr#date".into()]),+ RangeMapping::Degraded(_)+ ));+ }+const TTL: &str = r#"@prefix owl: <http://www.w3.org/2002/07/owl#> .@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rsindex 45841471..ffead1c4 100644--- a/crates/utopia-server/src/owl_import.rs+++ b/crates/utopia-server/src/owl_import.rs@@ -6,7 +6,7 @@//! 匹配按 **IRI** 不按 key:上游改一次 `rdfs:label`,派生出的 key 就变了,//! 按 key 匹配会把同一个类当新类建出来,实体全留在孤儿上(见 0001 P2)。-use std::collections::HashMap;+use std::collections::{BTreeMap, HashMap, HashSet};use utopia_core::AppResult;use utopia_ingest::ontology_rdf::{self, OwlProjection, RdfFormat};@@ -26,6 +26,34 @@ pub enum Disposition {KeyTaken,}+/// 一个属性在这次导入里会不会被建出来,以及为什么。+///+/// **预览必须说得出为什么**。上一版只报了"解析到 54 个属性",读者无从判断+/// 那是"都会建"还是"一个都不建"——而实际上是后者。+#[derive(Debug, Clone, PartialEq, serde::Serialize)]+#[serde(rename_all = "snake_case", tag = "outcome", content = "detail")]+pub enum AttrNote {+ /// 会建,用这个 datatype+ Datatype(&'static str),+ /// 会建成 text:没写 range,词汇表没做声明,text 是诚实的超集+ NoRange,+ /// 会建成 text:range 是可读字面量但我们表达不了它的类型(`xsd:time` 等)。+ /// 报出原 IRI,人可以改成更合适的类型;但值先落下来,不能因为类型糙就丢知识+ DegradedToText(String),+ /// 不建:抽取器不可能从散文里读出这种值(二进制、XML 片段、XML 内部标识)。+ /// 建了也永远填不上,只会给每个文本块的提示词多一行死噪音+ UnusableRange(String),+ /// 不建:没写 domain。属性必须挂在一个类上,这是 store 层的硬约束+ NoDomain,+ /// 不建:多个 domain,等 domain 关联表(0001 P2c)+ MultipleDomains(usize),+ /// 不建:domain 指向的类**在这个文件里,但被跳过了**(多半是 key 撞车)。+ /// 与 UnknownDomain 分开报,因为处置不同:这个能通过给现有的类改名解开+ DomainSkipped(String),+ /// 不建:domain 指向一个这个文件里压根没有的类(外部词汇表)+ UnknownDomain(String),+}+#[derive(Debug, Clone, serde::Serialize)]pub struct PlannedItem {pub iri: String,@@ -38,6 +66,9 @@ pub struct PlannedItem {pub functional: bool,#[serde(skip_serializing_if = "Option::is_none")]pub conflict_with: Option<String>,+ /// 属性专用:会以什么 datatype 建,或为什么建不了+ #[serde(skip_serializing_if = "Option::is_none")]+ pub attr: Option<AttrNote>,}/// 一次导入的完整计划。预览返回它,落库也执行它。@@ -58,6 +89,73 @@ pub struct ImportPlan {pub functional_relations: usize,}+/// 属性的去向。**domain 先判**:没有 domain 的属性根本建不出来,+/// 这时它的 range 是什么已经不重要了。+fn attr_note(+ p: &ontology_rdf::OwlProperty,+ resolvable: &HashSet<&str>,+ in_file: &HashSet<&str>,+) -> AttrNote {+ match p.domains.as_slice() {+ [] => return AttrNote::NoDomain,+ [one] => {+ if !resolvable.contains(one.as_str()) {+ return if in_file.contains(one.as_str()) {+ AttrNote::DomainSkipped(one.clone())+ } else {+ AttrNote::UnknownDomain(one.clone())+ };+ }+ }+ many => return AttrNote::MultipleDomains(many.len()),+ }+ match ontology_rdf::map_range(&p.ranges) {+ ontology_rdf::RangeMapping::Datatype(dt) => AttrNote::Datatype(dt),+ ontology_rdf::RangeMapping::Absent => AttrNote::NoRange,+ ontology_rdf::RangeMapping::Degraded(iri) => AttrNote::DegradedToText(iri),+ ontology_rdf::RangeMapping::Unusable(iri) => AttrNote::UnusableRange(iri),+ }+}++/// 属性会不会被建出来,以及用什么 datatype。落库与统计共用它,+/// 免得"预览说会建"和"实际建了"两处各判一次而分叉。+fn attr_datatype(note: &AttrNote) -> Option<&'static str> {+ match note {+ AttrNote::Datatype(dt) => Some(dt),+ // 没写 range,或写了但类型表达不了:值仍是字面量,+ // text 是拦不住任何东西的诚实超集+ AttrNote::NoRange | AttrNote::DegradedToText(_) => Some("text"),+ _ => None,+ }+}++impl ImportPlan {+ /// 建不出来的属性,按原因分组计数。**预览里报总数是不够的**——+ /// "54 个属性"读不出那是都会建还是一个都不建,而实际上取决于原因。+ pub fn attr_skips(&self) -> BTreeMap<&str, usize> {+ let mut out: BTreeMap<&str, usize> = BTreeMap::new();+ for a in &self.attributes {+ if a.disposition == Disposition::KeyTaken {+ *out.entry("key_taken").or_default() += 1;+ continue;+ }+ let reason = match a.attr.as_ref() {+ Some(AttrNote::Datatype(_))+ | Some(AttrNote::NoRange)+ | Some(AttrNote::DegradedToText(_)) => continue,+ Some(AttrNote::UnusableRange(_)) => "unusable_range",+ Some(AttrNote::NoDomain) => "no_domain",+ Some(AttrNote::MultipleDomains(_)) => "multiple_domains",+ Some(AttrNote::DomainSkipped(_)) => "domain_skipped",+ Some(AttrNote::UnknownDomain(_)) => "unknown_domain",+ None => continue,+ };+ *out.entry(reason).or_default() += 1;+ }+ out+ }+}+/// 解析文件并对着现有本体算出计划。不写任何东西。pub async fn plan(state: &AppState,@@ -88,9 +186,19 @@ pub async fn plan(.collect();let r_by_key: HashMap<&str, &_> = rtypes.iter().map(|t| (t.key.as_str(), t)).collect();+ // 这次结束后能解析出 id 的类 IRI:文件里新建或更新的,加上库里已有同 IRI 的。+ // key 撞车被跳过的**不在其列**——它不会被建出来,挂在它上面的属性也就无处可挂+ // 本次导入内部也会撞 key:不同 IRI 派生出同一个短标签+ //(FOAF 的 familyName 与 family_name 都成了 family_name)。+ // 只对着库里查是不够的——那样第二个在预览里显示"会新建",+ // 落库时被 ON CONFLICT 悄悄丢掉,预览就说了假话+ let mut claimed: HashMap<&str, &str> = HashMap::new();+let mut classes = Vec::new();for c in &proj.classes {- let (disposition, conflict_with) = if e_by_iri.contains_key(c.iri.as_str()) {+ let (disposition, conflict_with) = if let Some(prev) = claimed.get(c.key.as_str()) {+ (Disposition::KeyTaken, Some((*prev).to_string()))+ } else if e_by_iri.contains_key(c.iri.as_str()) {(Disposition::Update, None)} else if let Some(existing) = e_by_key.get(c.key.as_str()) {// key 撞了但 IRI 不同:这是两个不同的东西争一个短标签。@@ -101,6 +209,9 @@ pub async fn plan(} else {(Disposition::Create, None)};+ if disposition != Disposition::KeyTaken {+ claimed.insert(c.key.as_str(), c.iri.as_str());+ }classes.push(PlannedItem {iri: c.iri.clone(),key: c.key.clone(),@@ -109,20 +220,35 @@ pub async fn plan(disposition,functional: false,conflict_with,+ attr: None,});}+ // 文件里出现过的类(含被跳过的)——用来区分它被跳过了与它压根不在这个文件里+ let in_file: HashSet<&str> = proj.classes.iter().map(|c| c.iri.as_str()).collect();+ let resolvable: HashSet<&str> = classes+ .iter()+ .filter(|c| c.disposition != Disposition::KeyTaken)+ .map(|c| c.iri.as_str())+ .chain(e_by_iri.keys().copied())+ .collect();+let mut relations = Vec::new();let mut attributes = Vec::new();for p in &proj.properties {- let (disposition, conflict_with) = if r_by_iri.contains_key(p.iri.as_str()) {+ let (disposition, conflict_with) = if let Some(prev) = claimed.get(p.key.as_str()) {+ (Disposition::KeyTaken, Some((*prev).to_string()))+ } else if r_by_iri.contains_key(p.iri.as_str()) {(Disposition::Update, None)} else if let Some(existing) = r_by_key.get(p.key.as_str()) {(Disposition::KeyTaken, existing.iri.clone())} else {(Disposition::Create, None)};- let item = PlannedItem {+ if disposition != Disposition::KeyTaken {+ claimed.insert(p.key.as_str(), p.iri.as_str());+ }+ let mut item = PlannedItem {iri: p.iri.clone(),key: p.key.clone(),label: p.label.clone(),@@ -130,8 +256,10 @@ pub async fn plan(disposition,functional: p.functional,conflict_with,+ attr: None,};if p.is_datatype {+ item.attr = Some(attr_note(p, &resolvable, &in_file));attributes.push(item);} else {relations.push(item);@@ -158,8 +286,9 @@ pub async fn plan(Ok((plan, proj, format))}-/// 执行计划。**属性暂不落库**:它们需要 domain 才能存(store 层强制),-/// 而 domain 要等类先建好并解析 IRI → id,那是下一层的事。+/// 执行计划。属性在类之后落库——它们要挂在 domain 上,而 domain 要等+/// 类先建好并解析 IRI → id(就是下面那个 `id_of`)。+/// 多 domain 的仍然跳过,那要等 domain 关联表(0001 P2c)。pub async fn apply(state: &AppState,kb_id: Uuid,@@ -233,12 +362,55 @@ pub async fn apply(}}+ // 属性:类建完、id_of 填好之后才轮到它们。计划里已经算出了每个属性的去向,+ // **这里只执行,不重新判断**——两处各判一次就会分叉,而分叉意味着+ // 预览说的和实际做的不是一回事+ let by_prop_iri: HashMap<&str, &_> = proj+ .properties+ .iter()+ .map(|p| (p.iri.as_str(), p))+ .collect();+ let mut created_attrs = 0usize;+ for item in &plan.attributes {+ if item.disposition == Disposition::KeyTaken {+ continue;+ }+ let (Some(note), Some(p)) = (item.attr.as_ref(), by_prop_iri.get(item.iri.as_str())) else {+ continue;+ };+ let (Some(dt), Some(domain_iri)) = (attr_datatype(note), p.domains.first()) else {+ continue;+ };+ let Some(&domain_id) = id_of.get(domain_iri) else {+ // 计划阶段判为可解析,落库时却没有 id:类被跳过或更新失败。+ // 计划已经报告过它,这里安静略过而不是造一个挂空的属性+ continue;+ };+ if utopia_store::ontology::create_attribute_with_iri(+ &state.pool,+ kb_id,+ &p.key,+ &p.label,+ &p.description,+ &p.iri,+ domain_id,+ dt,+ )+ .await?+ .is_some()+ {+ created_attrs += 1;+ }+ }+let summary = serde_json::json!({"classes_created": created_classes,"classes_updated": updated_classes,"classes_key_taken": plan.classes.iter().filter(|c| c.disposition == Disposition::KeyTaken).count(),"relations_seen": plan.relations.len(),"attributes_seen": plan.attributes.len(),+ "attributes_created": created_attrs,+ "attributes_skipped": plan.attr_skips(),"classes_without_description": plan.classes_without_description,"functional_relations": plan.functional_relations,"unprojected": plan.unprojected.iter().take(30).collect::<Vec<_>>(),diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex b23ffe60..1cdf2da1 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -469,6 +469,49 @@ pub async fn update_type_from_import(}/// 设父类。自环与已是该父类的情形静默跳过。+/// 从导入建一个属性(`kind='attribute'`),带 IRI。+///+/// 与 [`create_relation_type`] 的区别只在多了 `iri` 与 key 冲突的处置:+/// 导入按 IRI 认身份,key 撞了是"两个不同的东西争一个短标签",+/// 由调用方在计划阶段报告并跳过,到这里不该再撞——所以冲突时返回 None+/// 而不是覆盖,让调用方把它计进"跳过"。+///+/// `temporal` 固定 `state`:属性是随时间变化的取值(薪资、人数),+/// 新值闭合旧值正是我们要的。OWL 里没有对应概念,猜 event 或 eternal 都更差。+#[allow(clippy::too_many_arguments)]+pub async fn create_attribute_with_iri(+ pool: &PgPool,+ kb_id: Uuid,+ key: &str,+ label: &str,+ description: &str,+ iri: &str,+ domain_type_id: Uuid,+ datatype: &str,+) -> AppResult<Option<Uuid>> {+ validate_key(key)?;+ let id = Uuid::now_v7();+ let row: Option<(Uuid,)> = sqlx::query_as(+ "INSERT INTO relation_types+ (id, kb_id, key, label, temporal, functional, inverse_functional,+ description, kind, domain_type_id, datatype, iri)+ VALUES ($1, $2, $3, $4, 'state', FALSE, FALSE, $5, 'attribute', $6, $7, $8)+ ON CONFLICT (kb_id, key) DO NOTHING+ RETURNING id",+ )+ .bind(id)+ .bind(kb_id)+ .bind(key)+ .bind(label)+ .bind(description)+ .bind(domain_type_id)+ .bind(datatype)+ .bind(iri)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(id,)| id))+}+pub async fn set_parent(pool: &PgPool, kb_id: Uuid, child: Uuid, parent: Uuid) -> AppResult<()> {if child == parent {return Ok(());diff --git a/docs/decisions/0001-ontology-import-and-governance.md b/docs/decisions/0001-ontology-import-and-governance.mdindex f0877d8c..98e0292e 100644--- a/docs/decisions/0001-ontology-import-and-governance.md+++ b/docs/decisions/0001-ontology-import-and-governance.md@@ -230,19 +230,50 @@ v2: http://acme.com/hr#Employee rdfs:label "Staff Member" → key = staff_membe|---|---|| range 能映射 | 照映射建。number 收 `decimal` `integer` 及其全部有界/无符号变体、`double` `float`、`owl:real` `owl:rational`;date 收 `date` `dateTime` `dateTimeStamp` `gYear` `gYearMonth`(我们的日期格式本就是 `YYYY[-MM[-DD]]`,逐级可省);bool 收 `boolean`;text 收 `string` 及其派生、`anyURI`、`rdf:langString`、`rdfs:Literal` || **没写 range** | 建成 `text`,在预览里列出。词汇表没做声明,我们只知道是字面量,`text` 是诚实的超集 |- | range 存在但映射不了 | **跳过并报告**:`time` `gMonth` `gDay` `gMonthDay`(缺年)、`duration` 系列(时长不是时点)、`hexBinary` `base64Binary`、`rdf:XMLLiteral`、`QName` 等 XML 内部标识、带 `withRestrictions` 的自定义类型,以及多条 `rdfs:range`(同 domain 的交集陷阱) |-- > **修订**:初稿把「不猜成 text」的理由写成「类型错的属性会让取值在写入时被- > `attr_datatype` 挡掉」。查 `normalize_attr_value` 后这条不成立——**`text` 接受任何- > 字符串,从不拦**,会拦的是 number/date/bool。真正的理由是另一条:**range 存在**- > 意味着词汇表做了一个明确声明,悄悄降级成 text 是把那个声明扔掉且不留痕迹;- > 而 range 缺席时没有声明可扔,宽松默认就是对的。区别在有没有东西被丢掉,- > 不在会不会被拦。+ | range 存在但**类型**表达不了 | 建成 `text` **并报告**:`time` `gMonth` `gDay` `gMonthDay`(缺年)、`duration` 系列(时长不是时点)、多条 `rdfs:range`(交集陷阱:不猜类型,但值仍是字面量)、以及任何我们不认识的类型 IRI |+ | 抽取器**不可能从散文里读出**这种值 | **跳过并报告**:`base64Binary` `hexBinary`(二进制块)、`rdf:XMLLiteral`(XML 片段)、`QName` `ID` `IDREF` `ENTITY`(XML 内部管道) |++ > **两次修订,第二次推翻了第一次。**+ >+ > 初稿说「不猜成 text,因为类型错的属性会让取值被 `attr_datatype` 挡掉」。+ > 查 `normalize_attr_value` 后不成立——**`text` 接受任何字符串,从不拦**,+ > 会拦的是 number / date / bool。+ >+ > 于是改成「range 存在就是词汇表做了声明,降级成 text 会把它扔掉且不留痕迹」。+ > **这条也站不住**:预览就在报告它,何来「不留痕迹」。而跳过的代价是属性根本+ > 不存在,抽取器不会被告知它,那条知识**彻底不会被捕获**——这正是本仓库反复+ > 当成最坏结果的那种失败。+ >+ > 正确的分界不是「能不能精确映射」,也不是「该不该进图谱」——属性值本来就在图谱里。+ > 是**「抽取器有没有可能从散文里读出这个值」**。「门店每天 9:00 开门」里有+ > `09:00`,所以 `xsd:time` 的属性填得上,按 text 存只丢排序语义,值还在。+ > 一张 base64 平面图不会出现在散文里,所以那个属性建了也永远是空的。+ >+ > 跳过它保护的不是数据(本来就不会有值),是**提示词**:每个属性都是抽取+ > 提示词里的一行,每个文本块付一遍,永远填不上的那些就是逐块付费的死噪音。- **domain 指向没被导入的类**(外部词汇表里的类):跳过 + 计入预览,不静默。- **多个 `rdfs:domain`**:存不下。这一条才真的要等关联表。所以顺序是:**先落单域属性**(P2b 的产物已经够用),多域的随关联表一起。+> **顺带查明的一件事:属性抽取这条路此前是死的。**+>+> 代码是全的——提示词里有属性段与规则 10,`ExtractedFact` 有 `value`,+> `normalize_attr_value` 按 datatype 校验,值落 `facts.object_value`,证据/时态/审阅全套复用。+> 但**内置本体一个属性都没有**,所以 `attr_lines` 一直是空的,整段属性提示词从未出现过。+> 除非有人手工建属性,这条路从落地起就没被执行过。+>+> OWL 导入开始建属性,它就变成活的了。端到端验过一遍(三个 datatype 各一个):+>+> ```+> floor_area {"value": 860} number,不是字符串+> opened_on {"value": "2024-09-01"} date+> opens_at {"value": "10:00"} text(降级的 xsd:time)+> ```+>+> 证据、置信度、界面渲染都对,零丢弃信号。**`opens_at` 那两条在旧的跳过规则下+> 根本不会存在**——这是存得下就别丢那个决定的直接证据。+#### 二、关联表:多值 domain/range```sql