Querying a Database Source

This topic provides details about the structure to use when writing GDI queries to read or ingest data from database data sources. It also includes example queries that may be useful as a starting point for writing your own GDI queries.

Supported Databases

The GDI supports querying any database through a JDBC connection. AnzoGraph installations include JDBC drivers for the following databases:

  • Databricks
  • H2
  • IBM DB2
  • Microsoft SQL Server
  • MariaDB
  • Oracle
  • PostgreSQL
  • SAP Sybase (jTDS)
  • Snowflake

To extend the service to access other databases, additional JDBC drivers can be added to AnzoGraph. For information about acquiring additional JDBC drivers, contact your Cambridge Semantics Customer Success manager. For instructions on deploying other drivers, see Deploy Optional Drivers for Accessing Custom Database Sources.

Query Syntax

The following query syntax shows the structure of a GDI query for database sources. 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 ${targetGraph} { ] 
   triple_patterns
 [ } ]
}
[ ${usingSources} ]

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>(${targetGraph})

    { 
      ?data a s:DbSource ;
        s:url "string" ;
        s:username "string" ;
        s:password "string" ;
        [ s:token "string" ; ]
        [ s:driver "string" ; ]
        [ s:property [ s:name "string" ; s:value "string" ] ; ]
        [ s:timeout int ; ]
        [ s:maxConnections int ; ]
        [ s:batching boolean | int ; ]
        [ s:concurrency int | [ list_of_properties ] ; ]
        [ s:rate int | "string" ; ]
        [ s:partitionBy "string" | ?variable | s:auto ; ]
        [ s:paging [ pagination_options ; ] 
        [ 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:query "string" ; ]
        [ s:database "string" ; ]
        [ s:schema "string" ; ]
        [ s:table "string" ; ]
        [ s:count ?variable ; ]
        [ s:offset int ; ]
        [ s:orderBy "string" | ?variable ; ]
        [ 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 Data Type Description
PREFIX Clause N/A The PREFIX clause declares the standard and custom prefixes for GDI service queries. Generally, queries include the following prefixes (or a subset of them) plus any data-specific declarations:
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 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 Anzo (INSERT).
GRAPH ${targetGraph} N/A Include the GRAPH keyword and target graph parameter ${targetGraph} when writing an INSERT query to ingest data into a graphmart. Anzo automatically populates the query with the appropriate target URIs when the query runs.
${usingSources} N/A Include the source graph parameter ${usingSources} when writing a "topdown" query that passes values from the data that is in the graphmart to the data source. Anzo automatically populates the query with the appropriate FROM clauses when the query runs. When passing literal values to the remote source, you do not need to include the source graph parameter. The SERVICE Clause description below includes more information about passing input to data sources.
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 writing a CONSTRUCT query in a View Step, 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 the graphmart 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 (usually in a View Step), include the following SERVICE call: SERVICE <http://cambridgesemantics.com/services/DataToolkitView>(${targetGraph}). 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.
url string This property specifies the URL to use to access the database.

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 Using Query Contexts in Queries for more information. For example, the triple patterns below reference a Query Context and add a JDBC driver level connection property:

?data a s:DbSource ;
  s:url "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.url}}" ;
  s:username "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.user}}" ;
  s:password "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.password}}" ;
  s:property [ s:name "access" ; s:value "all" ] ;
username string This property lists the user name to use for the connection to the database.

If you want to group the username and password properties, you can wrap them with s:credentials [ ]. For example:

s:credentials [
  s:username "username" ;
  s:password "password" ;
] ;
password string
This property lists the password for the given username.
token string
For connections that require a bearer token, this property can be included to specify the token.
driver string
This property can be included to specify the JDBC driver to use.
property RDF list
This property can be included to list any JDBC driver-specific connection properties. To incorporate property, use the following syntax:
s:property [ s:name "custom_driver_property_name" ; s:value "custom_value" ]
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. 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.

partitionBy string, variable, object
The GDI attempts to partition queries automatically across the available cores (slices) in AnzoGraph. To determine how to partition the query, the GDI uses metadata from the source database. It looks for any column in an index, preferring the primary key column if it is interpolable. However, it only considers the first column in any index on the table. After determining the partition column, the GDI does a MIN/MAX on the column as well as a basic sizing query. To specify which column or columns the GDI should partition on, you can include the partitionBy property in the query. The property supports a list of source field names, bound variables, or the object s:auto, which forces the GDI to partition the data when the source does not define partitioning metadata.
paging RDF list
This property can be used to configure paging so that the GDI can access large amounts of data across a number of smaller requests. For details about the paging property, see Pagination Options.
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. As an alternative to including the selector property for identifying the target data, you could use the database, schema, and/or table properties.
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 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 Normalization Options.
query string If you want to access the source data by running an SQL query, you can include this property to specify the query string to run. The language does not have to be SQL if the source supports another language. However, some GDI features where the query is dynamically altered may not work with a non-SQL language. Including {{?variable}} substitutions is supported within s:query strings.

If you include s:query without also specifying table or partitionBy, the GDI may not partition the query and query execution may be less performant than if the partition column was specified. When using s:query, specifying the table in s:table and the column to partition the table on in s:partitionBy is a good practice, especially when querying large tables.

database string
This property can be used to specify the database to target in the source if the database is not listed in the s:url or s:selector strings.
schema string
This property can be included to specify the target schema to query. If you include s:schema "schema_name" without specifying s:table (described below) or s:query, all tables in the schema are queried.
table string
This property can be included to specify the target table or tables for the query.
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.
orderBy string, variable, list
You can include this property to order the result set by a field name, a bound variable, or a list of names or bound variables.
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 ?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 ?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 that is not already identified by the selector, database, schema, table, or query properties, then the binding is needed to map the new variable to that source column. For example, ?subject ("dbo.FILM.SUBJECT") binds the ?subject variable by navigating to the SUBJECT column in the FILM table in the dbo schema.

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:gMonthDay
  • xsd:gYearMonth
  • xsd:duration
  • xsd:dayTimeDuration
  • xsd:yearMonthDuration
  • xsd:gMonth
  • 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.

Query Examples

The example below selects data from the AdventureWorks2012 database. The s:selector property is used to specify the table (salesOrderHeader in the Sales schema) to target.

PREFIX s:   <http://cambridgesemantics.com/ontologies/DataToolkit#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

SELECT (COUNT(*) as ?count)
WHERE
{
   SERVICE <http://cambridgesemantics.com/services/DataToolkit>
{
      ?SalesOrderHeader a s:DbSource ;
         s:url "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.url}}" ;
         s:username "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.user}}" ;
         s:password "{{@db.eca4bfa83481f3638b93ab5fdf93ff9a.password}}" ;
         s:selector "Sales.SalesOrderHeader" ;
         ?SalesOrderID (xsd:int) ;
         ?RevisionNumber (xsd:int) ;
         ?OrderDate (xsd:dateTime) ;
         ?DueDate (xsd:dateTime) ;
         ?TerritoryID (xsd:int) ;
         ?TotalDue (xsd:decimal) .
      FILTER(?TerritoryID IN (1, 2, 3))
      FILTER(?TotalDue < 11.0 || ?TotalDue > 250)
  }
}

The example below ingests data from a database. To define the data to target, the query includes the s:query property to run an SQL query. The s:table and partitionBy properties are also included to aid the GDI in partitioning the query.

PREFIX s:   <http://cambridgesemantics.com/ontologies/DataToolkit#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ont: <http://cambridgesemantics.com/Layer/2f1e926b130a402db6fc10fa54199d49/Model#>

INSERT { 
   GRAPH ${targetGraph} {
      ?resource a ont:EmrPatient ;
      ont:EmrPatient.patientid ?PATIENTID ;
      ont:EmrPatient.gender ?GENDER ;
      ont:EmrPatient.language ?LANGUAGE ;
      ont:EmrPatient.patientfirstdocactivitydate ?PATIENTFIRSTDOCACTIVITYDATE .
  }
}
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:query "select * from emrdbsmall.emr_patient where emr_patient.PATIENTID < 500" ;
      s:partitionBy "PATIENTID" ;
      s:table "emrdbsmall.emr_patient" ;
      ?PATIENTID (xsd:int) ;
      ?GENDER (xsd:string) ;
      ?LANGUAGE (xsd:string) ;
      ?PATIENTFIRSTDOCACTIVITYDATE (xsd:dateTime "M/d/yyyy HH:mm:ss") .

   BIND(IRI("http://cambridgesemantics.com/Layer/2f1e926b130a402db6fc10fa54199d49/{{?PATIENTID}}") AS ?resource)
  }
}

Related Topics