2015-04-27 27 views

回答

4

甲變量綁定到一些值,以便爲了有匹配。 可選是個例外。在那裏你可以得到一個匹配,它是可選一個特定的模式匹配。如果你想爲一個匹配的可選變量,你必須使用可選

從技術上講,您可以避免使用可選的聯合與可能發生的不同部分匹配。在這個意義上,你不會使用可選的,但它會是更加複雜:

@prefix : <urn:ex:>. 

:a :hasName "Person A". 

:b :hasAge 32 . 

:c :hasName "Person C" ; 
    :hasAge 71 . 
prefix : <urn:ex:> 

select * where { 
    #-- ?age but no name 
    { ?person :hasAge ?age 
    filter not exists { ?person :hasName ?name }} 
    union 
    #-- ?name but no age 
    { ?person :hasName ?name 
    filter not exists { ?person :hasAge ?age }} 
    union 
    #-- ?name and ?age 
    { ?person :hasName ?name ; :hasAge ?age } 
} 
----------------------------- 
| person | age | name  | 
============================= 
| :a  |  | "Person A" | 
| :b  | 32 |   | 
| :c  | 71 | "Person C" | 
----------------------------- 
2

您可以通過使用一個構造查詢實現這一目標。使用帶簡單BGP的CONSTRUCT來檢索完整數據集的相關子集,然後對結果進行後處理。

例如,假設你有一組有關人員,其中有姓名,電子郵件地址,電話號碼記錄,但沒有這些屬性的一定都是充滿了每個人。

然後你可以只是做檢索所有屬性Person類型的資源的查詢。這裏是(使用Sesame API)在Java中的例子:

// query to retrieve all properties of things of type Person 
String queryString = "CONSTRUCT WHERE {?s a <urn:Person>; ?p ?o }"; 
GraphQuery query = conn.prepareGraphQuery(SPARQL, queryString); 
Model result = QueryResults.asModel(query.evaluate()); 

您現在有一個包含所有可用的人數據的查詢結果。處理可能缺失的值現在只是處理結果的問題。例如:

for (Resource person: result.subjects()) { 
    Literal name = result.filter(person, FOAF.NAME, null).objectLiteral(); 
    if (name == null) { 
     System.out.println("name is missing!"); 
    } 
    else { 
     ... 
    } 
}