Query 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 DB installations include JDBC drivers for the following databases:
- Databricks
- H2
- IBM DB2
- Microsoft SQL Server
- MariaDB
- Oracle
- PostgreSQL
- SAP Sybase (jTDS)
- Snowflake
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 <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: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: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 | 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. |
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 Use a Query Context for more information. For example, the triple patterns below reference a Query Context and add a JDBC driver level connection property:
|
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
|
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:
|
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:
|
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:
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 |
partitionBy | string, variable, object |
The GDI attempts to partition queries automatically across the available cores (slices) in AnzoGraph DB. 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. |
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 Model 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 |
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 |
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:
|
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 |
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 "{{@Somedb.url}}" ; s:username "{{@Somedb.user}}" ; s:password "{{@Somedb.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 <http://anzograph.com/emr> { ?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 "{{@Somedb.url}}" ; s:username "{{@Somedb.user}}" ; s:password "{{@Somedb.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) } }