public IEnumerable <IDataObject> BindDataObjects(SparqlResultSet sparqlResultSet, bool resultsAreOrdered = false) { if (sparqlResultSet == null) { throw new ArgumentNullException(nameof(sparqlResultSet)); } var resourceTriples = new Dictionary <string, List <Triple> >(); string lastLoadedSubject = null; switch (sparqlResultSet.Variables.Count()) { case 1: // Single column results set contains only data object IRIs foreach (var uriNode in sparqlResultSet.Select(row => row[0] as IUriNode).Where(uriNode => uriNode?.Uri != null)) { yield return(_storeContext.MakeDataObject(uriNode.Uri.ToString())); } break; case 3: // Columns are triples, s, p, o in that order foreach (var t in sparqlResultSet.Select(row => MakeTriple(row[0], row[1], row[2]))) { if (resourceTriples.ContainsKey(t.Subject)) { resourceTriples[t.Subject].Add(t); } else { resourceTriples[t.Subject] = new List <Triple> { t }; } if (resultsAreOrdered && lastLoadedSubject != null && !lastLoadedSubject.Equals(t.Subject)) { // Have collected all the triples we are going to see for the previously encountered subject, so emit its data object now yield return(MakeDataObject(lastLoadedSubject, resourceTriples[lastLoadedSubject])); } lastLoadedSubject = t.Subject; } if (resultsAreOrdered && lastLoadedSubject != null) { // Emit the final result yield return(MakeDataObject(lastLoadedSubject, resourceTriples[lastLoadedSubject])); } else { // We have batched up all of the triples and can now emit the separate data objects foreach (var entry in resourceTriples) { yield return(MakeDataObject(entry.Key, entry.Value)); } } break; default: throw new ArgumentException( $"Expected a result set with either 1 or 3 columns. Got a result set with {sparqlResultSet.Variables.Count()} columns", nameof(sparqlResultSet)); } }
public IList <string> GetInstantiableEntityTypes(string firstEntityType) { if (!firstEntityType.IsValidBaseUri()) { throw new InvalidFormatException(Constants.Messages.Identifier.IncorrectIdentifierFormat, firstEntityType); } SparqlParameterizedString queryString = new SparqlParameterizedString { CommandText = @"SELECT DISTINCT * @fromMetadataNamedGraph @fromEnterpriseCoreOntologyNamedGraph WHERE { ?class rdfs:subClassOf* @firstEntityType . ?class @dashAbstract false. } ORDER BY ?class" }; queryString.SetPlainLiteral("fromMetadataNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasMetadataGraph).JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromEnterpriseCoreOntologyNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasECOGraph).JoinAsFromNamedGraphs()); queryString.SetUri("firstEntityType", new Uri(firstEntityType)); queryString.SetUri("dashAbstract", new Uri(Constants.DASH.Abstract)); SparqlResultSet results = _tripleStoreRepository.QueryTripleStoreResultSet(queryString); var types = results .Select(r => r.GetNodeValuesFromSparqlResult("class")?.Value) .Where(r => !string.IsNullOrWhiteSpace(r)) .ToList(); return(types); }
public IEnumerable <Provenance> Get(string title) { using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin")) { SparqlResultSet provResults = dog.Query( "SELECT distinct ?provenanceLabel ?location ?dateAcquired ?ownerLabel ?dispayOrder WHERE {" + "?artwork a dbo:Artwork ." + "?artwork rdfs:label ?label . " + "?artwork :provenance ?provenance ." + "?provenance :dateAcquired ?dateAcquired ." + "?provenance rdfs:label ?provenanceLabel ." + "?provenance schema:location ?city ." + "?city rdfs:label ?location ." + "?provenance gvp:displayOrder ?dispayOrder." + "?provenance gvp:ulan2779_owned_by ?owner. " + "?owner rdfs:label ?ownerLabel. " + "FILTER regex(str(?label), \"" + title + "\") ." + "FILTER(LANG(?ownerLabel) = \"\" || LANGMATCHES(LANG(?ownerLabel), \"en\")) ." + "FILTER(lang(?location) = \"en\")} " + "ORDER BY ASC(xsd:integer(?dispayOrder))") as SparqlResultSet; var provenance = provResults? .Select(x => new Provenance(x)) .GroupBy(x => x.DispayOrder, (key, g) => g.OrderBy(e => e.DispayOrder).First()); return(provenance); } }
public IList <string> GetParentEntityTypes(string firstEntityType) { if (!firstEntityType.IsValidBaseUri()) { throw new InvalidFormatException(Constants.Messages.Identifier.IncorrectIdentifierFormat, firstEntityType); } SparqlParameterizedString queryString = new SparqlParameterizedString(); queryString.CommandText = @"SELECT * @fromMetadataNamedGraph @fromMetdataShaclNamedGraph @fromEnterpriseCoreOntologyNamedGraph WHERE { @value rdfs:subClassOf* ?type. }"; queryString.SetPlainLiteral("fromMetadataNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasMetadataGraph).JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromMetdataShaclNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasShaclConstraintsGraph).JoinAsFromNamedGraphs()); queryString.SetPlainLiteral("fromEnterpriseCoreOntologyNamedGraph", _metadataGraphConfigurationRepository.GetGraphs(Constants.MetadataGraphConfiguration.HasECOGraph).JoinAsFromNamedGraphs()); queryString.SetUri("value", new Uri(firstEntityType)); SparqlResultSet results = _tripleStoreRepository.QueryTripleStoreResultSet(queryString); if (results.IsEmpty) { return(null); } var resourceTypes = results.Select(result => result.GetNodeValuesFromSparqlResult("type").Value).ToList(); return(resourceTypes); }
private void GenerateCaptionedInformation(HtmlWriterContext context, String caption, SparqlResultSet results, String var) { if (results == null) { return; } this.GenerateCaptionedInformation(context, caption, results.Select(r => r[var]).Where(n => n != null)); }
public PartialViewResult _Index(QueryOntology queryOntology) { IGraph g = new Graph(); StreamReader file = new StreamReader("Config.json"); JsonSerializer serializer = new JsonSerializer(); var configurations = JsonConvert.DeserializeObject <Configuration>(file.ReadToEnd()); if (queryOntology.Ontology == 1) { g.LoadFromFile(configurations.InstagramPath); } else { g.LoadFromFile(configurations.MyHeritagePath); } try { Object results = g.ExecuteQuery(queryOntology.Query); //Object results = g.ExecuteQuery( "SELECT DISTINCT ?Concept WHERE {[] a ?Concept}"); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; var result = rset.Select(s => new ResultQueryList { Object = s.ToString(), Predicate = s.ToString(), Subject = s.ToString() }); return(PartialView(result)); } else if (results is IGraph) { IGraph resGraph = (IGraph)results; var result = resGraph.Triples.Select(s => new ResultQueryList { Object = s.Object.ToString(), Predicate = s.Predicate.ToString(), Subject = s.Subject.ToString() }); return(PartialView(result)); } else { Console.WriteLine("ERROR"); } } catch (RdfQueryException queryEx) { Console.WriteLine(queryEx.Message); } return(PartialView()); }
public ActionResult GraphML(int id) { List <RouteItem> routes = getAllRoutes(id); // Using Parliament nuget packages, map user-defined classes into ontology-aligned interfaces which all implement iResource interface // This allows us to work with IGraph objects IEnumerable <ProcedureRoute> IRoutes = routes.Select(r => r.GiveMeMappedObject()); RdfSerializer serializer = new RdfSerializer(); IGraph graph = serializer.Serialize(IRoutes, typeof(ProcedureRoute).Assembly.GetTypes()); SparqlQueryParser parser = new SparqlQueryParser(); // Nodes SparqlQuery q1 = parser.ParseFromString("PREFIX : <https://id.parliament.uk/schema/> SELECT ?step ?stepName WHERE {?step a :ProcedureStep; :procedureStepName ?stepName. }"); SparqlResultSet nodes = (SparqlResultSet)graph.ExecuteQuery(q1); // Edges SparqlQuery q2 = parser.ParseFromString("PREFIX : <https://id.parliament.uk/schema/> SELECT ?route ?fromStep ?toStep WHERE {?route a :ProcedureRoute; :procedureRouteIsFromProcedureStep ?fromStep; :procedureRouteIsToProcedureStep ?toStep.}"); SparqlResultSet edges = (SparqlResultSet)graph.ExecuteQuery(q2); // Create GraphML StringWriter sw = new Utf8StringWriter(); XmlWriterSettings xws = new XmlWriterSettings(); xws.OmitXmlDeclaration = false; xws.Indent = true; using (XmlWriter xw = XmlWriter.Create(sw, xws)) { XNamespace ns = "http://graphml.graphdrawing.org/xmlns"; XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; XNamespace xsiSchemaLocation = "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"; // For yEd, not essential to GraphML. But good for verification XNamespace y = "http://www.yworks.com/xml/graphml"; XDocument doc = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement(ns + "graphml", new XAttribute(XNamespace.Xmlns + "xsi", xsi), new XAttribute(xsi + "schemaLocation", xsiSchemaLocation), new XAttribute(XNamespace.Xmlns + "y", y), new XElement(ns + "key", new XAttribute("for", "node"), new XAttribute("id", "d0"), new XAttribute("yfiles.type", "nodegraphics")), new XElement(ns + "graph", new XAttribute("id", "G"), new XAttribute("edgedefault", "directed"), nodes.Select(n => new XElement(ns + "node", new XAttribute("id", n["step"]), new XElement(ns + "data", new XAttribute("name", n["stepName"]), new XAttribute("key", "d0"), new XElement(y + "ShapeNode", new XElement(y + "NodeLabel", new XAttribute("visible", "true"), new XAttribute("autoSizePolicy", "content"), new XText(n["stepName"].ToString())))))), edges.Select(e => new XElement(ns + "edge", new XAttribute("id", e["route"]), new XAttribute("source", e["fromStep"]), new XAttribute("target", e["toStep"]))) ))); doc.WriteTo(xw); } return(Content(sw.ToString(), "application/xml")); }
// GET api/<controller> public IEnumerable <Artist> Get() { using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin")) { SparqlResultSet artistsResults = dog.Query( "SELECT distinct ?label ?abstract WHERE {" + "?person rdf:type dbo:Artist ." + "?person rdfs:label ?label . " + "?person dbo:abstract ?abstract ." + "FILTER(lang(?abstract) = 'en') ." + "FILTER(lang(?label) = \"en\") }") as SparqlResultSet; var artists = artistsResults?.Select(x => new Artist(x)); return(artists); } }
public JsonResult _ExecuteSPARQL(QueryOntology queryOntology) { IGraph g = new Graph(); StreamReader file = new StreamReader("Config.json"); JsonSerializer serializer = new JsonSerializer(); var configurations = JsonConvert.DeserializeObject <Configuration>(file.ReadToEnd()); if (queryOntology.Ontology == 1) { g.LoadFromFile(configurations.InstagramPath); } else { g.LoadFromFile(configurations.MyHeritagePath); } try { Object results = g.ExecuteQuery(queryOntology.Query); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; var result = rset.Select(s => new ResultQueryList { Object = s.ToString(), Predicate = s.ToString(), Subject = s.ToString() }); return(Json(JsonConvert.SerializeObject(rset))); } else if (results is IGraph) { IGraph resGraph = (IGraph)results; return(Json(resGraph.Triples)); } else { return(Json(false)); } } catch (RdfQueryException queryEx) { return(Json(queryEx)); } }
// GET api/<controller>?artist="any" public IEnumerable <Artwork> Get(string artist) { using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin")) { SparqlResultSet artworkResults = dog.Query( "SELECT distinct ?label ?depiction ?abstract WHERE {" + "?artwork a dbo:Artwork ." + "?artwork rdfs:label ?label . " + "?artwork dbo:abstract ?abstract ." + "?artwork foaf:depiction ?depiction ." + "?artwork dbo:author ?author ." + "?author foaf:name ?authorLabel ." + "FILTER regex(str(?authorLabel), \"" + artist + "\")" + "FILTER(lang(?label) = \"en\") ." + "FILTER(lang(?abstract) = \"en\")}") as SparqlResultSet; var artworks = artworkResults?.Select(x => new Artwork(x)); return(artworks); } }
// GET api/<controller>/?artistName="any" public IEnumerable <Artwork> Get(string artistName) { using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin")) { SparqlResultSet artworksResults = dog.Query( "SELECT distinct ?label ?abstract?depiction ?labelArtwork WHERE {" + "?person rdf:type dbo:Artist ." + "?person rdfs:label ?label ." + "?artwork a dbo:Artwork ." + "?artwork foaf:depiction ?depiction ." + "?person dbo:abstract ?abstract ." + "?artwork dbo:author ?person ." + "?artwork rdfs:label ?labelArtwork . " + " FILTER(lang(?abstract) = 'en') ." + "FILTER(lang(?label) = 'en') ." + "FILTER regex(str(?labelArtwork), \"" + artistName + "\")" + "FILTER(lang(?labelArtwork) = 'en') }") as SparqlResultSet; var artworks = artworksResults?.Select(x => new Artwork(x)); return(artworks); } }
public static IEnumerable <string> GetIds(this SparqlResultSet results) { return(results?.Select(x => x[0].GetUri().GetUriIdentifier())); }
private void GenerateCaptionedInformation(HtmlWriterContext context, String caption, SparqlResultSet results, String var) { if (results == null) return; this.GenerateCaptionedInformation(context, caption, results.Select(r => r[var]).Where(n => n != null)); }
public IEnumerable<IDataObject> BindDataObjects(SparqlResultSet sparqlResultSet, bool resultsAreOrdered = false) { if (sparqlResultSet == null) throw new ArgumentNullException(nameof(sparqlResultSet)); var resourceTriples = new Dictionary<string, List<Triple>>(); string lastLoadedSubject = null; switch (sparqlResultSet.Variables.Count()) { case 1: // Single column results set contains only data object IRIs foreach (var uriNode in sparqlResultSet.Select(row => row[0] as IUriNode).Where(uriNode => uriNode?.Uri != null)) { yield return _storeContext.MakeDataObject(uriNode.Uri.ToString()); } break; case 3: // Columns are triples, s, p, o in that order foreach (var t in sparqlResultSet.Select(row=>MakeTriple(row[0], row[1], row[2]))) { if (resourceTriples.ContainsKey(t.Subject)) { resourceTriples[t.Subject].Add(t); } else { resourceTriples[t.Subject] = new List<Triple> {t}; } if (resultsAreOrdered && lastLoadedSubject != null && !lastLoadedSubject.Equals(t.Subject)) { // Have collected all the triples we are going to see for the previously encountered subject, so emit its data object now yield return MakeDataObject(lastLoadedSubject, resourceTriples[lastLoadedSubject]); } lastLoadedSubject = t.Subject; } if (resultsAreOrdered && lastLoadedSubject != null) { // Emit the final result yield return MakeDataObject(lastLoadedSubject, resourceTriples[lastLoadedSubject]); } else { // We have batched up all of the triples and can now emit the separate data objects foreach (var entry in resourceTriples) { yield return MakeDataObject(entry.Key, entry.Value); } } break; default: throw new ArgumentException( $"Expected a result set with either 1 or 3 columns. Got a result set with {sparqlResultSet.Variables.Count()} columns", nameof(sparqlResultSet)); } }