Search code examples
matchsparqlrdf

SPARQL: Choose one triple from multiple match?


I have a kind of interesting problem with SPARQL query. I am querying for a triple and I have multiple match - maybe 2. But I need the code to choose only one. It absolutely doesn't matter which one. For example: I am querying for a book for 5-years old and it founds 2 books in the database but I need to have only one saved in variable (doesn't matter which one). Is this even possible in SPARQL? Please let me know if you need any other information. Thank you all in advance for your time! The change in input database is the last thing I want to do.

EXAMPLE:

<Book rdf:ID = 0001>
<Book.Title>Title1</Book.Title>
<Book.For>5 years old</Book.For>
<Book.Date>2000</Book.Date>
</Book>

<Book rdf:ID = 0002>
<Book.Title>Title2</Book.Title>
<Book.For>5 years old</Book.For>
<Book.Date>2005</Book.Date>
</Book>
Construct {?NewDatabase Example_of_book_for_5_years_old ?Title .}
Where {?Example Book.For "5 years old" .
       ?Example Book.Title ?Title .
      };

Both books match the Where clause but I need only one to be in the new database output. Doesn't matter which one.


Solution

  • Not considering the apparent errors in your example query, the solution is to use SELECT instead of CONSTRUCT. The former allows you to limit the number of results.

    If you totally need a triple as result, you can use limited SELECT as a subquery

    To select only one triple from a CONSTRUCT query you can use the LIMIT clause just like with SELECT

    Construct { ?Example <urn:Book:Title> ?Title }
    Where {
       ?Example <urn:Book:For> "5 years old" .
       ?Example <urn:Book:Title> ?Title .
    } 
    limit 1
    

    This will select the first result (order undetermined).


    And no, the judging by the SPARQL Grammar, it is not possible to use the LIMIT clause with SPARQL Updates.