Getting Started with GDI Queries

This topic provides details about the structure to use when writing GDI queries. It focuses on the properties that are common to all types of data sources. It also includes example queries that demonstrate the data integration capabilities for different types of sources.

Rather than manually writing complex queries, you can use the GDI to automatically generate graphs and ontologies by including a few key statements in a relatively simple query. For information, see Generating a Knowledge Graph.

GDI Query Syntax

The following query syntax shows the structure of a GDI query. The clauses, patterns, and placeholders that are links are described below.

# PREFIX Clause
PREFIX s:     <http://cambridgesemantics.com/ontologies/DataToolkit#>
PREFIX rdf:   <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs:  <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd:   <http://www.w3.org/2001/XMLSchema#>
PREFIX owl:   <http://www.w3.org/2002/07/owl#>
PREFIX anzo:  <http://openanzo.org/ontologies/2008/07/Anzo#>
PREFIX zowl:  <http://openanzo.org/ontologies/2009/05/AnzoOwl#>
PREFIX dc:    <http://purl.org/dc/elements/1.1/>

# Result Clause
{ 
   [ GRAPH <target_graph> { ] 
   triple_patterns
 [ } ]
}
[ FROM Clause ]
WHERE
{
   # SERVICE Clause: Include the following service call when reading or inserting data.
    SERVICE [ TOPDOWN ] <http://cambridgesemantics.com/services/DataToolkit>

   # View SERVICE Clause: Or use the service call below when constructing a view.
    SERVICE <http://cambridgesemantics.com/services/DataToolkitView>(<target_graph>)

    { 
      ?data a s:source_type ; 
# Based on the source_type, additional connection and input parameters are
# available. The options below are valid for all sources. For source-related
# options, see the GDI Property Reference. 
        s:url "string" ;
        [ s:username "string" ; ]
        [ s:password "string" ; ]
        [ s:timeout int ; ]
        [ s:maxConnections int ; ]
        [ s:batching boolean | int ; ]
        [ s:concurrency int | [ list_of_properties ] ; ]
        [ s:rate int | "string" ; ]
        [ s:locale "string" ; ]
        [ s:sampling int ; ]
        [ s:selector "string" | [ list ] ; ]
        [ s:model "string" ; ]
        [ s:key ("string") ; ]
        [ s:reference [ s:model "string" ; s:using ("string") ]
        [ s:formats [ datatype_formatting_options ] ; ]
        [ s:normalize boolean | [ normalization_rules ] ; ]
        [ s:count ?variable ; ]
        [ s:offset int ; ]
        [ s:limit int ; ]
        # Mapping variables
        ?mapping_variable ( [ "binding" ] [ datatype ] [ "datetime_format" ] ) ;
        ... ;
        .
     # Additional clauses such as BIND, VALUES, FILTER
   }
}

For readability, the parameters below exclude the base URI <http://cambridgesemantics.com/ontologies/DataToolkit#> as well as the s: prefix. As shown in the examples, however, the s: prefix or full property URI does need to be included in queries.

Option Type Description
PREFIX Clause N/A
The PREFIX clause declares the standard and custom prefixes for GDI service queries. Generally, queries include the prefixes from the query template (or a subset of them) plus any data-specific declarations.
Result Clause N/A The result clause defines the type of SPARQL query to run and the set of results to return, i.e., whether you want to read (SELECT or CONSTRUCT) from the source or ingest the data into AnzoGraph DB (INSERT).
SERVICE Clause N/A
Include the SERVICE call SERVICE [ TOPDOWN ] <http://cambridgesemantics.com/services/DataToolkit> to invoke the GDI service when you are running a SELECT, INSERT, or CONSTRUCT query that is not creating a view. When creating a view, use the DataToolkitView service call, as described below in View SERVICE Clause.

Include the optional TOPDOWN keyword when you want to pass input values from AnzoGraph DB to the data source. When you include TOPDOWN in the service call, it indicates that the rest of the query produces values to send to the source. In this case, the GDI makes repeated calls to pass in each of the specified values and retrieve the data that is based on those values.

View SERVICE Clause N/A
When writing a CONSTRUCT query that creates a view of the data, include the following SERVICE call: SERVICE <http://cambridgesemantics.com/services/DataToolkitView>(<target_graph>). Using the DataToolkitView call optimizes query execution because it tells the GDI to inspect the query and determine which filters to push to the data source. It also limits the result set and retrieves only the data that is needed, i.e., the source data is fully mapped but all of the mapped data is not necessarily returned.
source_type object The ?data a s:source_type triple pattern specifies the type of data source that the query will run against. For example, ?data a s:DbSource, specifies that the source type is a database. The list below describes the available types:
  • DbSource to connect to any type of database.
  • FileSource for flat files. The supported file types are CSV and TSV, JSON, NDJSON, XML, Parquet, and SAS (SAS Transport XPT and SAS7BDAT formats). The GDI automatically determines the file type from the file extensions.
  • HttpSource to connect to HTTP endpoints.
  • ElasticSource to connect to Elasticsearch indexes on an Elasticsearch server.
  • KafkaSource to connect to Kafka streaming sources.
  • MetadataSource for metadata discovery.

Certain connection and input parameters are available based on the specified source type. For details about the options for your source, see GDI Property Reference.

url string
This property specifies the URL for the data source, such as the database URL, Elasticsearch URL, or HTTP endpoint URL. For file-based sources, the url property specifies the file system location of the source file or directory of files. When specifying a directory (such as s:url "/opt/shared-files/loads/"), the GDI loads all of the file formats it recognizes. To specify a directory but limit the number or type of files that are read, you can include the pattern and/or maxDepth properties described in FileSource Properties.

For security, it is a best practice to reference connection information (such as the url, username, and password) from a Query Context so that the sensitive details are abstracted from any requests. In addition, using a Query Context makes connection details reusable across queries. See Use a Query Context for more information. For example, the triple patterns below reference keys from a Query Context:

?data a s:DbSource ;
s:url "{{@Somedb.url}}" ;
s:username "{{@Somedb.user}}" ;
s:password "{{@Somedb.password}}" ;

username string
If authentication is required to access the source, include this property to specify the user name.
password string
This property lists the password for the given username.
timeout int
This property can be used to specify the timeout (in milliseconds) to use for requests against the source. For example, s:timeout 5000 configures a 5 second timeout.
maxConnections int
This property can be used to set a limit on the maximum number of active connections to the source. For example, s:maxConnections 16 sets the limit to 16 connections. When not specified, the default value is 10.
batching boolean or int
This property can be used to disable batching, or it can be used to change the default the batch size. By default, batching is set to 5000 (s:batching 5000). To disable batching, you can include s:batching false in the query. Typically users do not change the batching size. However, it can be useful to control the batch size when performing updates. To configure the size, include s:batching int in the query. For example, s:batching 3000.
concurrency int or RDF list
This property can be included to configure the maximum level of concurrency for the query. The value can be an integer, such as s:concurrency 8. If the value is an integer, it configures a maximum limit on the number of slices that can execute the query. For finer-grained control over the number of nodes and slices to use, concurrency can also be included as an object with limit, nodes, and/or executorsPerNode properties. For example, the following object configures a concurrency model that allows a maximum of 24 executors distributed across 4 nodes with 8 executors per node:

s:concurrency [ s:limit 24 ; s:nodes 4 ; s:executorsPerNode 8 ; ] ;

rate int or string
This property can be included to control the frequency with which a request is sent to the source. The limit applies to the number of requests a single slice can make. If you specify an integer for the rate, then the value is treated as the maximum number of requests to issue per minute. If you specify a string, you have more flexibility in configuring the rate. The sample values below show the types of values that are supported:

s:rate "90/minute" ; s:rate "90 per minute" ; s:rate "200000 every week" ; s:rate "10000 every 6 hours" ;

To enforce the rate limit, the GDI introduces a sleep between requests that is equal to the rate delay. The more executing slices, the longer the rate delay needs to be to enforce the limit in aggregate.

Given the example of s:rate "90/minute", the GDI would optimize the concurrency and only use 1 slice for execution with a rate delay of 666ms between requests. If s:rate "240/minute", the GDI would use 3 executors with a rate delay of 750ms between requests.

locale string
This property can be used to specify the locale to use when parsing locale-dependent data such as numbers, dates, and times.
sampling int
This property can be used to configure the number of records in the source to examine for data type inferencing.
selector string or RDF list
This property can be used as a binding component to identify the path to the source objects. For example, s:selector "Sales.SalesOrderHeader" targets the SalesOrderHeader table in the Sales schema. For more information about binding components and the selector property, see Using Binding Trees and Selector Paths.
model string
This property defines the class (or table) name for the type of data that is generated from the specified data source. For example, s:model "employees". Model is optional when querying a single source. If your query targets multiple sources, however, and you want to define resource templates (primary keys) and object properties (foreign keys), you must specify the model value for each source.
key string
This property can be used to define the primary key column for the source file or table. This column is leveraged in a resource template for the instances that are created from the source. For example, s:key ("EMPLOYEE_ID"). For more information about key, see Data Linking Options.
reference RDF list
This property can be used to specify a foreign key column. The reference property is an RDF list that includes the model property to list the target table and a using property that defines the foreign key column. For more information about reference, see Data Linking Options.
formats RDF list
To give users control over the data types that are used when coercing strings to other types, this property can be included in GDI queries to define the desired types. In addition, it can be used to describe the formats of date and time values in the source to ensure that they are recognized and parsed to the appropriate date, time, and/or dateTime values. For details about the formats property, see Data Type Formatting Options.
normalize boolean and/or RDF list
To give users control over the labels and URIs that are generated, the GDI offers several options for normalizing the model and/or the fields that are created from the specified data source(s). For details about the normalize property, see Model Normalization Options.
count variable
If you want to turn the query into a COUNT query, you can include this property with a ?variable to perform a count. For example, s:count ?count.
offset int
This property can be used to offset the data that is returned by a number of rows.
limit int
You can include this property to limit the number of results that are returned. s:limit maps to the SPARQL LIMIT clause.
mapping_variable variable
The mapping variables, in ?mapping_variable (["binding"] [datatype] ["datetime_format"]) format, define the triple patterns to output. When the specified ?variable matches the source column name, the GDI uses the variable as the source data selector. If you specify an alternate variable name, a binding needs to be specified to map the new variable to the source. You also have the option to transform the data using the datatype and datetime_format options.

The parentheses around the binding, data type, and format specifications are not required but are included in this document for readability.

binding string
The binding is a literal value that binds a ?mapping_variable to a source column. If you specify a ?variable that matches the source column name, then that variable name is the data selector and it is not necessary to specify a binding. If you specify an alternate variable name or there is a hierarchical path to the source column, then the binding is needed to map the new variable to that source column.

For example for a flat source like CSV, the following pattern simply binds the source column AIRLINE to the lowercase variable ?airline: ?airline ("AIRLINE"). For a database source, this example binds the ?subject variable by navigating to the SUBJECT column in the FILM table in the dbo schema: ?subject ("dbo.FILM.SUBJECT"). And for an HTTP source, this example binds the ?time variable to the time object under the minutely data path: ?time ("minutely.data.time").

For FileSource and HttpSource, periods (.), forward slashes (/), and brackets ([ ]) are parsed as path notation. Therefore, if a source column name includes any of those characters they must be escaped in the binding. Use two backslashes (\\) as an escape character. For example, if a column name is average/day, the variable and binding pattern could be written as ?averagePerDay ("average\\/day").

For DbSource, database, schema, and table names in bindings are parsed according to the specific rules for that database type. You do not need to escape characters in database names. However, database names with characters that do not match (_|A-Z|a-z)(_|A-Z|a-z|0-9)* should be quoted, such as ("'Adventure.Works'.Sales.'Daily.Totals'").

datatype URI
The datatype is the data type to convert the column to. If you do not specify a data type, the GDI infers the type. The GDI supports the following types:

xsd:int, xsd:long, xsd:float, xsd:double, xsd:boolean, xsd:time, xsd:dateTime, xsd:date, xsd:duration, xsd:dayTimeDuration, xsd:yearMonthDuration, xsd:gMonthDay, xsd:gMonth, xsd:gYearMonth, xsd:anyURI

datetime_format string
This option is used to specify the format to use for date and time data types. The GDI supports Java date and time formats. Specify days as "d," months as "M," and years as "y." For the time, specify "H" for hours, "m" for minutes, and "s" for seconds. For example, "yyyyMMdd HH:mm:ss" or "ddMMMyy" to display date values such as "01JAN19."

The GDI's default base year is 2000. If the source data has years with only two digits, such as 02-04-99, the GDI prepends 20 to the digits. The value 02-04-99 is parsed to 02-04-2099. To specify an alternate base year to use for two-digit values, you can include the notation ^nnnn (e.g., ^1900) in the format value. For example, to set the base year to 1900 instead of 2000, use a format value such as xsd:date "dd-MMM-yy^1900" or xsd:date "dd-MMM-yy^1990". When one of those values is specified, 02-04-99 is parsed to 02-04-1999.

GDI Query Examples

The query below reads data from a sample HTTP source that compiles worldwide weather statistics. The source has several models available for retrieving data that is current, daily, historical, etc. To target current data, the query includes s:selector "currently" as an input parameter. In addition, the query demonstrates the use of the "topdown" functionality, where the query sends values to the source to narrow the results. The query includes the TOPDOWN keyword in the GDI service call, and the VALUES clause specifies the latitude and longitude values for the cities to return data for. In addition, since this sample source requires parameters to be specified in the connection URL, the s:url value includes ?lat and ?long as parameters as part of the value.

PREFIX s:      <http://cambridgesemantics.com/ontologies/DataToolkit#>
PREFIX rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs:   <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd:    <http://www.w3.org/2001/XMLSchema#>
PREFIX owl:    <http://www.w3.org/2002/07/owl#>
PREFIX anzo:   <http://openanzo.org/ontologies/2008/07/Anzo#>
PREFIX zowl:   <http://openanzo.org/ontologies/2009/05/AnzoOwl#>
PREFIX dc:     <http://purl.org/dc/elements/1.1/>
PREFIX ex:     <http://example.org/ontologies/City#>

SELECT  
	?city ?state ?summary ?temp ?rainChance
	?humidity ?pressure ?windSpeed
WHERE
{
	SERVICE TOPDOWN <http://cambridgesemantics.com/services/DataToolkit>
    {
	  ?data a s:HttpSource ;
	  s:url "https://sampleEndpoint.com/forecast/{{?lat}},{{?long}}" ;
	  s:selector "currently" ;
	  ?lat ("latitude") ;
	  ?long ("longitude") ;
	  ?temp ("temperature") ;
	  ?rainChance ( "precipProbability" ) ;
	  ?humidity () ;
	  ?pressure () ;
	  ?windSpeed () .
    }
    VALUES( ?city ?state ?lat ?long )
    {
	  ( "Lakeway" "TX" 30.374563 -97.975892 )
	  ( "Boston" "MA" 42.358043 -71.060415 )
	  ( "Seattle" "WA" 47.590720 -122.307053 )
	  ( "Chicago" "IL" 41.837741 -87.823296 )
	  ( "Hilo" "HI" 19.702040 -155.090312 )
    }
}
ORDER BY ?city

The query returns the following results:

city    | state | summary       | temp  | rainChance | humidity | pressure | windSpeed
--------+-------+---------------+-------+------------+----------+----------+-----------
Boston  | MA    | Overcast      | 79.81 |          0 |      0.6 |   1018.7 |      7.71
Chicago | IL    | Clear         |  81.7 |          0 |     0.52 |   1021.1 |      5.13
Hilo    | HI    | Partly Cloudy |  72.6 |       0.13 |     0.79 |   1018.6 |      4.86
Lakeway | TX    | Partly Cloudy | 92.43 |          0 |     0.48 |   1013.3 |     10.85
Seattle | WA    | Mostly Cloudy | 61.82 |          0 |     0.76 |   1018.2 |      4.57
5 rows

The example below ingests data from a database source using an INSERT query.

PREFIX s:       <http://cambridgesemantics.com/ontologies/DataToolkit#>
PREFIX rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs:    <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd:     <http://www.w3.org/2001/XMLSchema#>
PREFIX owl:     <http://www.w3.org/2002/07/owl#>
PREFIX anzo:    <http://openanzo.org/ontologies/2008/07/Anzo#>
PREFIX zowl:    <http://openanzo.org/ontologies/2009/05/AnzoOwl#>
PREFIX dc:      <http://purl.org/dc/elements/1.1/>
PREFIX :        <http://example.com/ontologies/kl_hosp#>

INSERT
{
	GRAPH <http://anzograph.com/orders>
    {
	?InputEvent_cv a :InputEvent_cv ;
	    :row_id ?row_id ;
	    :subject_id ?subject_id ;
	    :hadm_id ?hadm_id ;
	    :icustay_id ?icustay_id ;
	    :charttime ?charttime ;
	    :itemid ?itemid ;
	    :amount ?amount ;
	    :amountuom ?amountuom ;
	    :rate ?rate ;
	    :rateuom ?rateuom ;
	    :storetime ?storetime ;
	    :cgid ?cgid ;
	    :orderid ?orderid ;
	    :linkorderid ?linkorderid ;
	    :stopped ?stopped ;
	    :newbottle ?newbottle ;
	    :originalamount ?originalamount ;
	    :originalamountuom ?originalamountuom ;
	    :originalroute ?originalroute ;
	    :originalrate ?originalrate ;
	    :originalrateuom ?originalrateuom ;
	    :originalsite ?originalsite .
    }
}
WHERE
{
	SERVICE <http://cambridgesemantics.com/services/DataToolkit>
    {
	?data a s:DbSource ;
	    s:url "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.url}}" ;
            s:username "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.user}}"
            s:password "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.password}}"
	    s:selector "kl_hosp_schema.inputevents_cv" ;
	    ?row_id (xsd:int) ;
	    ?subject_id (xsd:int) ;
	    ?hadm_id (xsd:int) ;
	    ?icustay_id (xsd:int) ;
	    ?charttime (xsd:dateTime) ;
	    ?itemid (xsd:int) ;
	    ?amount (xsd:float) ;
	    ?amountuom (xsd:string) ;
	    ?rate (xsd:float) ;
	    ?rateuom (xsd:string) ;
	    ?storetime (xsd:dateTime) ;
	    ?cgid (xsd:int) ;
	    ?orderid (xsd:int) ;
	    ?linkorderid (xsd:int) ;
	    ?stopped (xsd:string) ;
	    ?newbottle (xsd:int) ;
	    ?originalamount (xsd:float) ;
	    ?originalamountuom (xsd:string) ;
	    ?originalroute (xsd:string) ;
	    ?originalrate (xsd:float) ;
	    ?originalrateuom (xsd:string) ;
	    ?originalsite (xsd:string) ;
	BIND(IRI("http://example.com/inputevent_cv/{{?row_id}}") AS ?InputEvent_cv)
	BIND(IRI("http://example.com/patients/{{?subject_id}}") AS ?patient)
	BIND(IRI("http://example.com/admissions/{{?hadm_id}}") AS ?admission) 
    }
}

The following query ingests airport-related data from a CSV file.

PREFIX s:       <http://cambridgesemantics.com/ontologies/DataToolkit#>
PREFIX rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs:    <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd:     <http://www.w3.org/2001/XMLSchema#>
PREFIX owl:     <http://www.w3.org/2002/07/owl#>
PREFIX anzo:    <http://openanzo.org/ontologies/2008/07/Anzo#>
PREFIX zowl:    <http://openanzo.org/ontologies/2009/05/AnzoOwl#>
PREFIX dc:      <http://purl.org/dc/elements/1.1/>

INSERT 
{
  GRAPH <http://anzograph.com/airports>
  { 
   ?code a <http://anzograph.com/airport> ;
      <http://anzograph.com/airport/name> ?name ;
      <http://anzograph.com/airport/city> ?city ;
      <http://anzograph.com/airport/state> ?state ;
      <http://anzograph.com/airport/latitude> ?lat;
      <http://anzograph.com/airport/longitude> ?long.
  }
}
WHERE
{
	SERVICE <http://cambridgesemantics.com/services/DataToolkit>
    {
	?data a s:FileSource ;
          s:url "/opt/shared-files/airports.csv" ;
          ?iata_code ("IATA_CODE" xsd:string) ;
          ?name ("AIRPORT" xsd:string) ;
          ?city ("CITY" xsd:string) ;
          ?state ("STATE" xsd:string) ;
          ?lat ("LATITUDE" xsd:double) ;
          ?long ("LONGITUDE" xsd:double).
	BIND(IRI("http://anzograph.com/airport/{{?iata_code}}") as ?code)
    }
}

The query below creates a view of a database source.

PREFIX s:    <http://cambridgesemantics.com/ontologies/DataToolkit#>
PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd:  <http://www.w3.org/2001/XMLSchema#>
PREFIX owl:  <http://www.w3.org/2002/07/owl#>
PREFIX anzo: <http://openanzo.org/ontologies/2008/07/Anzo#>
PREFIX zowl: <http://openanzo.org/ontologies/2009/05/AnzoOwl#>
PREFIX dc:   <http://purl.org/dc/elements/1.1/>
PREFIX ont:  <http://cambridgesemantics.com/ont/autogen/Rh/MIMIC-III-Data_Source/mimic_iii_schema#>

CONSTRUCT 
{
   ?caregiversURI a ont:caregivers ;
      ont:caregivers_cgid ?cgid ;
      ont:caregivers_description ?description ;
      ont:caregivers_label ?label .
}
WHERE
{
   GRAPH ?g 
   {
      SERVICE <http://cambridgesemantics.com/services/DataToolkitView>(<http://anzograph.com/caregivers>) {
    {
        ?data a s:DbSource ;
          s:url "{{@mimicdb.url}}" ;
          s:username "{{@mimicdb.user}}"
          s:password "{{@mimicdb.password}}"
          s:selector "mimic_iii_schema.caregivers" ;
          ?row_id (xsd:int) ;
          ?cgid (xsd:int) ;
          ?label (xsd:string) ;
          ?description (xsd:string) .
      BIND(IRI("http://anzograph.com/class/caregivers/{{?row_id}}") AS ?caregiversURI) }
    }
  }
}