У меня есть данные RDF, и я хочу сформировать запрос SPARQL для извлечения записей, соответствующих определенному имени организма.
Просто к вашему сведению, я использовал RDF4J для создания записей RDF с использованием доступных данных JSONLD. У меня проблема с получением записей, которые соответствуют любому конкретному набору PropertyValue. Пример: все записи, имеющие организм как Equus caballus, или все записи, имеющие идентификатор представления как GSB-7331.
Любая помощь горячо приветствуется.
Записи данных такие:
@prefix schema: <http://schema.org/> .
@prefix obo: <http://purl.obolibrary.org/obo/> .
@prefix ebi-bsd: <https://www.ebi.ac.uk/biosamples/> .
@prefix biosamples: <http://identifiers.org/biosample/> .
biosamples:SAMEA104496657 a schema:DataRecord ;
schema:dateCreated "0002-10-15T00:00:00Z"^^schema:Date ;
schema:dateModified "2019-07-23T18:33:14.867Z"^^schema:Date ;
schema:identifier "SAMEA104496657" ;
schema:isPartOf ebi-bsd:samples ;
schema:mainEntity _:b0 .
ebi-bsd:samples a schema:Dataset .
_:b0 a schema:Sample , obo:OBI_0000747 ;
schema:additionalProperty _:b1 , _:b2 , _:b3 , _:b4 ;
schema:description "Blood samples N123" ;
schema:identifier "SAMEA104496657" ;
schema:name "N123" ;
schema:sameAs biosamples:SAMEA104496657 .
_:b1 a schema:PropertyValue ;
schema:name "organism" ;
schema:value "Equus caballus" ;
schema:valueReference obo:NCBITaxon_9796 .
obo:NCBITaxon_9796 a schema:DefinedTerm .
_:b2 a schema:PropertyValue ;
schema:name "submission description" ;
schema:value "ELOAD_294_samples" .
_:b3 a schema:PropertyValue ;
schema:name "submission identifier" ;
schema:value "GSB-7331" .
_:b4 a schema:PropertyValue ;
schema:name "submission title" ;
schema:value "ELOAD_294" .
@prefix schema: <http://schema.org/> .
@prefix obo: <http://purl.obolibrary.org/obo/> .
@prefix ebi-bsd: <https://www.ebi.ac.uk/biosamples/> .
@prefix biosamples: <http://identifiers.org/biosample/> .
biosamples:SAMEA104625758 a schema:DataRecord ;
schema:dateCreated "0014-06-07T00:00:00Z"^^schema:Date ;
schema:dateModified "2019-08-06T17:46:01.812Z"^^schema:Date ;
schema:identifier "SAMEA104625758" ;
schema:isPartOf ebi-bsd:samples ;
schema:mainEntity _:b0 .
ebi-bsd:samples a schema:Dataset .
_:b0 a schema:Sample , obo:OBI_0000747 ;
schema:additionalProperty _:b1 , _:b2 , _:b3 ;
schema:description "Colorectal Cancer Tumor Sequenced Samaple;
schema:identifier "SAMEA104625758" ;
schema:name "P-0009062-T01-IM5" ;
schema:sameAs biosamples:SAMEA104625758 ;
schema:subjectOf "http://www.ebi.ac.uk/ena/data/view/SAMEA104625758" .
:b1 a schema:PropertyValue ;
schema:name "common name" ;
schema:value "Human" ;
schema:valueReference obo:NCBITaxon_9606 .
obo:NCBITaxon_9606 a schema:DefinedTerm .
_:b2 a schema:PropertyValue ;
schema:name "organism" ;
schema:value "Homo sapiens" ;
schema:valueReference obo:NCBITaxon_9606 .
_:b3 a schema:PropertyValue ;
schema:name "scientific name" ;
schema:value "Homo sapiens" ;
schema:valueReference obo:NCBITaxon_9606 .
Код, который я использую для создания данных RDF TURTLE, приведен ниже. Я загружаю образцы данных в формате JSONLD с сайта https://www.ebi.ac.uk/biosamples/samples/SAMN03177689.ldjson
import org.apache.commons.io.FileUtils;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Scanner;
import java.util.concurrent.Callable;
public class BioSchemasRdfGenerator implements Callable<Void> {
private Logger log = LoggerFactory.getLogger(getClass());
private static File file;
private static long sampleCount = 0;
private final URL url;
public static void setFilePath(String filePath) {
file = new File(filePath);
}
BioSchemasRdfGenerator(final URL url) {
log.info("HANDLING " + url.toString() + " and the current sample count is: " + ++sampleCount);
this.url = url;
}
@Override
public Void call() throws Exception {
requestHTTPAndHandle(this.url);
return null;
}
private static void requestHTTPAndHandle(final URL url) throws Exception {
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int response;
try {
conn.setRequestMethod("GET");
conn.connect();
response = conn.getResponseCode();
if (response == 200) {
handleSuccessResponses(url);
}
} catch (final Exception e) {
throw new RuntimeException(e);
} finally {
conn.disconnect();
}
}
private static void handleSuccessResponses(final URL url) {
try (Scanner sc = new Scanner(url.openStream())) {
final StringBuilder sb = new StringBuilder();
while (sc.hasNext()) {
sb.append(sc.nextLine());
}
try (InputStream in = new ByteArrayInputStream(sb.toString().getBytes(StandardCharsets.UTF_8))) {
String dataAsRdf = readRdfToString(in);
write(dataAsRdf);
} catch (final Exception e) {
throw new RuntimeException(e);
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings(value = "deprecation")
private static void write(final String sampleData) throws Exception {
FileUtils.writeStringToFile(file, sampleData, true);
}
/**
* @param in a rdf input stream
* @return a string representation
*/
private static String readRdfToString(final InputStream in) {
return graphToString(readRdfToGraph(in));
}
/**
* @param inputStream an Input stream containing rdf data
* @return a Graph representing the rdf in the input stream
*/
private static Collection<Statement> readRdfToGraph(final InputStream inputStream) {
try {
final RDFParser rdfParser = Rio.createParser(RDFFormat.JSONLD);
final StatementCollector collector = new StatementCollector();
rdfParser.setRDFHandler(collector);
rdfParser.parse(inputStream, "");
return collector.getStatements();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
/**
* Transforms a graph to a string.
*
* @param myGraph a sesame rdf graph
* @return a rdf string
*/
private static String graphToString(final Collection<Statement> myGraph) {
final StringWriter out = new StringWriter();
final TurtleWriterCustom turtleWriterCustom = new TurtleWriterCustom(out);
return modifyIdentifier(writeRdfInTurtleFormat(myGraph, out, turtleWriterCustom));
}
private static String modifyIdentifier(String rdfString) {
if (rdfString != null)
rdfString = rdfString.replaceAll("biosample:", "");
return rdfString;
}
private static String writeRdfInTurtleFormat(Collection<Statement> myGraph, StringWriter out, TurtleWriterCustom writer) {
try {
writer.startRDF();
handleNamespaces(writer);
for (Statement st : myGraph) {
writer.handleStatement(st);
//below line is commented: for short RDF
//writer.writeValue(st.getObject(),O true);
}
writer.endRDF();
} catch (final RDFHandlerException e) {
throw new RuntimeException(e);
}
return out.getBuffer().toString();
}
private static void handleNamespaces(final TurtleWriterCustom writer) {
writer.handleNamespace("schema", "http://schema.org/");
writer.handleNamespace("obo", "http://purl.obolibrary.org/obo/");
writer.handleNamespace("ebi-bsd", "https://www.ebi.ac.uk/biosamples/");
writer.handleNamespace("biosamples", "http://identifiers.org/biosample/");
}
}
schema:mainEntity _:b0 .
— так что все данные объединены в узле_:b0
— я не знаю, как вы создали набор данных, но вы не можете повторно использовать объекты во время генерации, если они обозначают разные объекты. Вы можете добавить генерацию кода или сначала начать двойную проверку - person UninformedUser   schedule 27.02.2020