GraphDB Connectors

compared with
Current by Nikola Petrov
on May 12, 2015 14:47.

(show comment)
Key
This line was removed.
This word was removed. This word was added.
This line was added.

Changes (8)

View Page History
{note:title=Warning}
This is a special page that contains placeholders/special instructions for an external tool. On the basis of this page the following proper pages will be generated:
The GraphDB Connectors provide extremely fast keyword and faceted (aggregation) searches that are typically implemented by an external component or service, but have the additional benefit of staying automatically up-to-date with the GraphDB repository data.

* [Lucene GraphDB Connector]
* [Solr GraphDB Connector]
* [Elasticsearch GraphDB Connector]
The Connectors provide synchronisation at the entity level, where an entity is defined as having a unique identifier (URI) and a set of properties and property values. In terms of RDF, this corresponds to a set of triples that have the same subject. In addition to simple properties (defined by a single triple), the Connectors support property chains. A property chain is defined as a sequence of triples where each triple's object is the subject of the subsequent triple.

To generate the pages copy all wiki markup below the closing \{note\} and save it to a file. Then run:
This version of GraphDB comes with the following connector implementations:

{code} {children}
./generate-confluence-doc.pl lucene inputfile.txt outputlucene.txt
./generate-confluence-doc.pl solr inputfile.txt outputsolr.txt
./generate-confluence-doc.pl elasticsearch inputfile.txt outputelasticsearch.txt
{code}

This will produce two files, outputsolr.txt and outputlucene.txt. Paste each file as wiki markup into the respective page.
{note}

{toc:maxLevel=2}

h1. Overview

The GraphDB Connectors provide extremely fast normal and facet (aggregation) searches that are typically implemented by an external component or service such as $(implementation), but have the additional benefit to stay automatically up-to-date with the GraphDB repository data.

The Connectors provide synchronisation at the _entity_ level, where an entity is defined as having a unique identifier (a URI) and a set of properties and property values. In terms of RDF, this corresponds to a set of triples that have the same subject. In addition to simple properties (defined by a single triple), the Connectors support _property chains_. A property chain is defined as a sequence of triples where each triple's object is the subject of the following triple.

h1. Features

The main features of the GraphDB Connectors are:

* maintaining an index that is always in sync with the data stored in GraphDB
* multiple independent instances per repository
* the entities for synchronisation are defined by:
** a list of fields (on the $(implementation) side) and property chains (on the GraphDB side) whose values will be synchronised
**a list of rdf:type's of the entities for synchronisation
** a list of languages for synchronisation (the default is all languages)
** additional filtering by property and value
* full-text search using native $(implementation) queries
* snippet extraction: highlighting of search terms in the search result
* faceted search
* sorting by any preconfigured field
* paging of results using _offset_ and _limit_
$(only-lucene)* specifying Lucene analyzer to use (the default is Lucene's StandardAnalyzer)
$(only-lucene)* stripping HTML/XML tags in literals (default is to not strip markup)
$(only-lucene)* boosting an entity by the \[numeric\] value of one or more predicates
$(only-lucene)* custom scoring expressions at query time to evaluate score based on Lucene score and entity boost

Each feature is described in detail below.

h1. Sample data

All examples use the following sample data. It describes five fictitious wines: Yoyowine, Franvino, Noirette, Blanquito and Rozova, as well as the grape varieties needed to make these wines. The minimum needed ruleset level in GraphDB is RDFS.

{code}
@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 : <http://www.ontotext.com/example/wine#> .

:RedWine rdfs:subClassOf :Wine .
:WhiteWine rdfs:subClassOf :Wine .
:RoseWine rdfs:subClassOf :Wine .

:Merlo
rdf:type :Grape ;
rdfs:label "Merlo" .

:CabernetSauvignon
rdf:type :Grape ;
rdfs:label "Cabernet Sauvignon" .

:CabernetFranc
rdf:type :Grape ;
rdfs:label "Cabernet Franc" .

:PinotNoir
rdf:type :Grape ;
rdfs:label "Pinot Noir" .

:Chardonnay
rdf:type :Grape ;
rdfs:label "Chardonnay" .

:Yoyowine
rdf:type :RedWine ;
:madeFromGrape :CabernetSauvignon ;
:hasSugar "dry" ;
:hasYear "2013"^^xsd:integer .

:Franvino
rdf:type :RedWine ;
:madeFromGrape :Merlo ;
:madeFromGrape :CabernetFranc ;
:hasSugar "dry" ;
:hasYear "2012"^^xsd:integer .

:Noirette
rdf:type :RedWine ;
:madeFromGrape :PinotNoir ;
:hasSugar "medium" ;
:hasYear "2012"^^xsd:integer .

:Blanquito
rdf:type :WhiteWine ;
:madeFromGrape :Chardonnay ;
:hasSugar "dry" ;
:hasYear "2012"^^xsd:integer .

:Rozova
rdf:type :RoseWine ;
:madeFromGrape :PinotNoir ;
:hasSugar "medium" ;
:hasYear "2013"^^xsd:integer .
{code}

h1. Usage

All interactions with the $(implementation) GraphDB Connector shall be done through SPARQL queries.

There are three types of SPARQL queries:

* INSERT for creating and deleting connectors.
* SELECT for listing connectors and querying connector configuration parameters.
* INSERT/SELECT for storing and querying data as part of the normal GraphDB data workflow.

In general this corresponds to _INSERT adds or modifies data_ and _SELECT queries existing data_.

Each connector implementation defines its own URI prefix to distinguish it from other connectors. For the $(implementation) GraphDB Connector this is *$(prefix)*. Each command or predicate that is executed by the connector uses this prefix, e.g. <$(prefix)#createConnector> for creating a connector for $(implementation).

Individual instances of a connector are distinguished by unique names that are also URIs. They have their own prefix to avoid clashing with any of the command predicates. For $(implementation), the instance prefix is $(prefix-inst).

h2. Creating a connector

Creating a connector is should be done by sending a SPARQL query with the following configuration data:

* the name of the connector (e.g. my_index),
* classes to synchronise,
* properties to synchronise.

The configuration data must be provided as a JSON string representation and passed together with the create command.

{tip:title=What we recommend}
Use the GraphDB Connectors management interface provided by the GraphDB Workbench. It will let you create the configuration easily and then create the connector directly or copy the configuration and execute it elsewhere.
{tip}

The create command is triggered by a SPARQL *INSERT* with the *createConnector* predicate, e.g. this will create a connector called *my_index* that will synchronise the wines from the sample data above:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

INSERT DATA {
inst:my_index :createConnector '''
{
$(only-solr) "solrUrl": "http://localhost:8983/solr",
$(only-elasticsearch) "elasticsearchNode": "localhost:9300",
"types": [
"http://www.ontotext.com/example/wine#Wine"
],
"fields": [
{
"fieldName": "grape",
"propertyChain": [
"http://www.ontotext.com/example/wine#madeFromGrape",
"http://www.w3.org/2000/01/rdf-schema#label"
]
},
{
"fieldName": "sugar",
"propertyChain": [
"http://www.ontotext.com/example/wine#hasSugar"
],
"sort": true
},
{
"fieldName": "year",
"propertyChain": [
"http://www.ontotext.com/example/wine#hasYear"
]
}
]
}
''' .
}
{code}

Note that one of the fields has _"sort": true_. This is explained further under [Sorting|#sorting].

$(only-solr)The above command creates a new $(implementation) connector that connects to the $(implementation) instance accessible at port 8983 on the localhost as specified by the "solrUrl" key.
$(only-elasticsearch)The above command will create a new $(implementation) connector that will connect to the $(implementation) instance accessible at port 9500 on the localhost as specified by the "elasticsearchUrl" key.
$(only-lucene)The above command will create a new $(implementation) connector.

The "types" key defines the RDF type of the entities to synchronise and in the example it is only entities of the type <http://www.ontotext.com/example/wine#Wine> (and its subtypes). The "fields" key defines the mapping from RDF to $(implementation). The basic building block is the property chain, i.e. a sequence of RDF properties where the object of each property is the subject of the following property. In the example we map three bits of information - the wine's grape, sugar content, and year. Each chain is assigned a short and convenient field name: "grape", "sugar", and "year". The field names are later used in the queries.

Grape is an example of a property chain composed of more than one property. First we take the wine's madeFromGrape property, the object of which is an instance of type Grape, and then we take the rdfs:label of this instance. Sugar and year are both composed of a single property that links the value directly to the wine.


$(block-only-solr)
h4. Non managed schemas
Currently we don't expose a powerful interface to change the analyzers, stopwords on per field basis. The recommended way to do that for now is to manage the schema yourself and tell the connector to just sync the object values in the appropriate fields. Here is an example:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

INSERT DATA {
inst:my_index :createConnector '''
{
$(only-solr) "solrUrl": "http://localhost:8983/solr",
$(only-elasticsearch) "elasticsearchNode": "localhost:9200",
"types": [
"http://www.ontotext.com/example/wine#Wine"
],
"fields": [
{
"fieldName": "grape",
"propertyChain": [
"http://www.ontotext.com/example/wine#madeFromGrape",
"http://www.w3.org/2000/01/rdf-schema#label"
]
},
{
"fieldName": "sugar",
"propertyChain": [
"http://www.ontotext.com/example/wine#hasSugar"
],
"sort": true
},
{
"fieldName": "year",
"propertyChain": [
"http://www.ontotext.com/example/wine#hasYear"
]
}
],
"manageExternalIndex": "false"
}
''' .
}
{code}

this will create the same connector as above but expects fields with the specified fieldnames to be already present in the core!

{warning}
Currently the connector chain tracking information is stored in $(implementation) - this will lead to a requirement for additional fields in the core's schema so you are responsible for adding those. The recommended way to handle this is to:
* create the connector on a testing environment
* copy the generated schema
* change the schema as needed and deploy it in production
{warning}
$(block-only-solr)


$(block-only-elasticsearch)
h4. Non managed schemas
Currently we don't expose a powerful interface to change the analyzers, stopwords on per field basis. The recommended way to do that for now is to manage the mapping for the index + type yourself and tell the connector to just sync the object values in the appropriate fields. Here is an example:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

INSERT DATA {
inst:my_index :createConnector '''
{
$(only-solr) "solrUrl": "http://localhost:8983/solr",
$(only-elasticsearch) "elasticsearchNode": "localhost:9200",
"types": [
"http://www.ontotext.com/example/wine#Wine"
],
"fields": [
{
"fieldName": "grape",
"propertyChain": [
"http://www.ontotext.com/example/wine#madeFromGrape",
"http://www.w3.org/2000/01/rdf-schema#label"
]
},
{
"fieldName": "sugar",
"propertyChain": [
"http://www.ontotext.com/example/wine#hasSugar"
],
"sort": true
},
{
"fieldName": "year",
"propertyChain": [
"http://www.ontotext.com/example/wine#hasYear"
]
}
],
"manageExternalIndex": "false"
}
''' .
}
{code}

this will create the same connector as above but expects fields with the specified fieldnames to be already present in the index's mapping!

{warning}
Currently the connector chain tracking information is stored in $(implementation) - this will lead to a requirement for additional fields in the index's mapping so you are responsible for adding those. The recommended way to handle this is to:
* create the connector on a testing environment
* copy the generated mapping
* change the schema as mapping and deploy it in production
{warning}
$(block-only-elasticsearch)

h2. Dropping a connector

Dropping a connector removes all references to its external store from GraphDB as well as the SOLR core associated with it. Dropping a connector is achieved through a SPARQL INSERT query with the following parameter:

* Name of the connector

The drop command is triggered by a SPARQL *INSERT* with the *dropConnector* predicate, e.g. this will remove the connector *:my_index*:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

INSERT DATA {
inst:my_index :dropConnector "" .
}
{code}

h2. Listing available connectors

Listing connectors returns all previously created connectors. It is a *SELECT* query with the *listConnectors* predicate:

{code}
PREFIX : <$(prefix)>

SELECT ?cntUri ?cntStr {
?cntUri :listConnectors ?cntStr .
}
{code}

*?cntUri* will be bound to the prefixed URI of the connector that was used during creation, e.g. <$(prefix-inst)my_index>, while *?cntStr* will be bound to a string, representing the part after the prefix, e.g. "my_index".

h2. Status check

The internal state of each connector can be queried using a *SELECT* query and the *connectorStatus* predicate:

{code}
PREFIX : <$(prefix)>

SELECT ?cntUri ?cntStatus {
?cntUri :connectorStatus ?cntStatus .
}
{code}

*?cntUri* will be bound to the connector prefixed URI, while *?cntStatus* will be bound to a string representation of the status of the connector represented by this URI. The status is key-value based.

h2. Adding, updating and deleting data

From the user's point of view all synchronisation will happen transparently without using any additional predicates or naming a specific store explicitly, i.e. the user should simply execute standard SPARQL INSERT/DELETE queries. This is achieved by intercepting all changes in the plugin and determining which abstract documents need to be updated.

h2. Querying data

Once a connector has been created it will be possible to query data from it through SPARQL. For each matching abstract document, the connector returns the document's subject. In its simplest form querying is achieved by using a *SELECT* and providing the $(implementation) query as the object of the *:query* predicate:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity {
?search a inst:my_index ;
:query "grape:cabernet" ;
:entities ?entity .
}
{code}

The result will bind ?entity to the two wines made from grapes that have "cabernet" in their name, namely :Yoyowine and :Franvino.

Note that you must use the field names you chose when you created the connector. It is perfectly valid to have field names identical to the property URIs but then you responsible for escaping any special characters according to what $(implementation) expects.

First we get an instance of the requested connector by using the RDF notation "X a Y" (= X rdf:type Y), where X is a variable and Y is a connector. X will be bound to an instance of this connector. Then we assign a query to that instance by using the system predicate *:query*. Finally we request the matching entities through the *:entities* predicate.

It is also possible to provide per query search options by using one or more option predicates. The option predicates are described in details below.

$(block-only-solr)
h4. Raw queries

If you want to access a query parameter from solr that is not exposed with special predicate, you can do it with our raw query mechanism. Basically instead of providing a full text query in the :query part, you just specify the parameters from the solr endpoint. Let's say you want to sort the facets returned in a different order as described in [facet.sort|https://wiki.apache.org/solr/SimpleFacetParameters#facet.sort]. Here is an example query that will do that for you:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity {
?search a inst:my_index ;
:query '''
{
"facet":"true",
"indent":"true",
"facet.sort":"index",
"q":"*:*",
"wt":"json"
}
''' ;
:entities ?entity .
}
{code}

You can get those parameter when you do your query from the admin interface in solr, or from the response payload(they are included). We also support the query parameters from the select endpoint in solr if you prefer that. Here is an example:

{code}

PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity {
?search a inst:my_index ;
:query '''q=*%3A*&wt=json&indent=true&facet=true&facet.sort=index''' ;
:entities ?entity .
}
{code}

note that you have to specify *_q=_* as the first parameter because we use it for detection of the raw query.

$(block-only-solr)

$(block-only-elasticsearch)
h4. Raw queries

If you want to access a query parameter from elasticsearch that isn't exposed with special predicate, you can do it with our raw query mechanism. Basically instead of providing a full text query in the :query part, you just specify the elasticsearch query body. Let's say you want to boost some parts of your full text query as described [here|http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/_boosting_query_clauses.html]. Here is an example query that will do that for you:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity {
?search a inst:my_index ;
:query '''
{
{
"bool" : {
"should" : [ {
"query_string" : {
"query" : "<full-text-query-not-boosted>"
}
}, {
"query_string" : {
"query" : "<full-text-query-boosted>",
"boost" : 4.0
}
} ]
}
}
}
''' ;
:entities ?entity .
}
{code}

$(block-only-elasticsearch)

h3. Combining $(implementation) results with GraphDB data

The bound ?entity can be used in other SPARQL triples in order to build complex queries that fetch additional data from GraphDB. For example to see the actual grapes in the matching wines as well as the year they were made:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>
PREFIX wine: <http://www.ontotext.com/example/wine#>

SELECT ?entity ?grape ?year {
?search a inst:my_index ;
:query "grape:cabernet" ;
:entities ?entity .
?entity wine:madeFromGrape ?grape .
?entity wine:hasYear ?year
}
{code}

The result will look like this:

|| ?entity || ?grape || ?sugar ||
| :Yoyowine | :CabernetSauvignon | 2013 |
| :Franvino | :Merlo | 2012 |
| :Franvino | :CabernetFranc | 2012 |

Note that :Franvino is returned twice because it is made from two different grapes, both of which are returned.

h3. Entity match score

It is possible to access the match score returned by $(implementation) with the *:score* predicate. As each entity has its own score, the predicate must come at the entity level. For example:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity ?score {
?search a inst:my_index ;
:query "grape:cabernet" ;
:entities ?entity .
?entity :score ?score
}
{code}

The result will look like this but the actual score might be different as it depends on the specific $(implementation) version:

|| ?entity || ?score ||
| :Yoyowine | 0.9442660212516785 |
| :Franvino | 0.7554128170013428 |

h2. Faceting

Consider the sample wine data and the my_index connector described previously. We can use the same connector to query facets too:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?facetName ?facetValue ?facetCount WHERE {
# note empty query is allowed and will just match all documents, hence no :query
?r a inst:my_index ;
:facetFields "year,sugar" ;
:facets _:f .
_:f :facetName ?facetName .
_:f :facetValue ?facetValue .
_:f :facetCount ?facetCount .
}
{code}

It is important to specify the fields we want to facet by using the *facetFields* predicate. Its value must be a simple comma-delimited list of field names. In order to get the faceted results, we have to use the *facets* predicate and as each facet has three components (name, value and count), the facets predicate binds a blank node, which in turn can be used to access the individual values for each component through the predicates *facetName*, *facetValue*, and *facetCount*.

The resulting bindings will look like in the table below:

|| facetName || facetValue || facetCount ||
| year | 2012 | 3 |
| year | 2013 | 2 |
| sugar | dry | 3 |
| sugar | medium | 2 |

We can easily see that there are three wines produced in 2012 and two in 2013. We also see that three of the wines are dry, while two are medium. However, it is not necessarily true that the three wines produced in 2012 are the same as the three dry wines as each facet is computed independently.

{anchor:sorting}
h2. Sorting

It is possible to sort the entities returned by a connector query according to one or more fields. In order to be able to use a certain field for sorting, you have to specify this at the time of creating the connector instance. Sorting is achieved by the *orderBy* predicate the value of which must be a comma-delimited list of fields. Each field may be prefixed with a minus to indicate sorting in descending order. For example:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity {
?search a inst:my_index ;
:query "year:2013" ;
:orderBy "-sugar" ;
:entities ?entity .
}
{code}

The result will contain wines produced in 2013 sorted according to their sugar content in descending order:

|| entity ||
| Rozova |
| Yoyowine |

By default, entities are sorted according to their matching score in descending order.

Note that if you join the entity from the connector query to other triples stored in GraphDB, GraphDB might scramble the order. To remedy this, use ORDER BY from SPARQL.

h2. Limit and offset

Limit and offset are supported on the $(implementation) side of the query. This is achieved through the predicates *limit* and *offset*. Consider this example in which we specify an offset of 1 and a limit of 1:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity {
?search a inst:my_index ;
:query "sugar:dry" ;
:offset "1" ;
:limit "1" ;
:entities ?entity .
}
{code}

The result will contain a single wine, Franvino, as it would be second in the list if we executed the query without the limit and offset:

|| entity ||
| Yoyowine |
| *Franvino* |
| Blanquito |

Note that the specific order in which GraphDB returns the results, depends on both how $(implementation) returns the matches, unless you specified sorting.

h2. Snippet extraction

Snippet extraction is used to extract highlighted snippets of text that match the query. The snippets are accessed through the dedicated predicate *:snippets*, which binds a blank node that in in turn provides the actual snippets via the predicates *:snippetField* and *:snippetText*. The predicate :snippets must be attached to the entity, as each entity has a different set of snippets. For example, in a search for Cabernet:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?entity ?snippetField ?snippetText {
?search a inst:my_index ;
:query "grape:cabernet" ;
:entities ?entity .
?entity :snippets _:s .
_:s :snippetField ?snippetField ;
:snippetText ?snippetText .
}
{code}

The query will return the two wines made from Cabernet Sauvignon or Cabernet Franc grapes as well as the respective matching fields and snippets:

|| ?entity || ?snippetField || ?snippetText ||
| :Yoyowine | grape | <em>Cabernet</em> Sauvignon |
| :Franvino | grape | <em>Cabernet</em> Franc |

Note that the actual snippets might be somewhat different as this depends on the specific $(implementation) implementation.

It is possible to tweak how the snippets are collected/composed by using the following option predicates:

* *:snippetSize* sets the maximum size of the extracted text fragment, 250 by default.
* *:snippetSpanOpen* text to insert before the highlighted text, <em> by default.
* *:snippetSpanClose* text to insert after the highlighted text, </em> by default.

The option predicates are set on the connector instance, much like the :query predicate.

h2. Total hits

You can get the total number of hits by using the *:totalHits* predicate, e.g. for the connector :my_index and a query that would retrieve all wines made in 2012:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?totalHits {
?r a inst:my_index ;
:query "year:2012" ;
:totalHits ?totalHits .
}
{code}

As there are three wines made in 2012, the value 3 (of type xdd:long) will be bound to ?totalHits.

h1. Creation parameters

The creation parameters define how a connector instance is created by the :createConnector predicate. There are some required parameters and some that are optional. All parameters are provided together in a JSON object, where the parameter names are the object keys. Parameter values may be simple JSON values such as a string or a boolean, or they can be lists or objects.

All of the creation parameters can also be set conveniently from the Create Connector user interface in the GraphDB Workbench without any knowledge of JSON.

h2. Compulsory parameters

The compulsory parameters must be present in every connector. They are responsible for the core behaviour.

$(block-only-solr)
h3. Solr instance to sync to: solrUrl (URL)

Since Solr is a third-party service, you have to specify the URL on which it is running. The format of the URL is of the form *http://hostname.domain:port/*. There is no default value.
$(block-only-solr)
$(block-only-elasticsearch)
h3. Elasticsearch instance to sync to: elasticsearchNode (string)

Since Elasticsearch is a third-party service, you have to specify the node where it is running. The format of the node value is of the form *hostname.domain:port*. There is no default value.
$(block-only-elasticsearch)

h3. Types of entities to sync: types (list of URI)

The RDF types of entities to sync are specified as a list of URIs. At least one type URI must be provided.

h3. What exactly to sync: fields (list of field object)

The fields define exactly what parts of each entity will be synchronised as well as the specific details on the connector side. The field is the smallest synchronisation unit and it maps a property chain from GraphDB to a field in $(implementation). The fields are specified as a list of field objects. At least one field object must be provided. Each field object has further keys that specify details.

h4. Name of the field: fieldName (string)

The name of the field defines the mapping on the connector side. It is specified by the key fieldName with a string value. The field name is used at query time to refer to the field. There are few restrictions on the allowed characters in a field name but to avoid unnecessary escaping (which depends on how $(implementation) parses its queries) we recommend to keep the field names simple.

h4. Property chain to map: propertyChain (list of URI)

The property chain (propertyChain) defines the mapping on the GraphDB side. A property chain is defined as a sequence of triples where the entity URI is the subject of the first triple, its object is the subject of the next triple and so on. In this model, a property chain with a single element corresponds to a direct property defined by a single triple. Property chains are specified as a list of URIs and at least one URI must be provided. If you need to store the entity URI in the connector, you may map it by defining a property chain with a single special URI: $self. Only one field per connector may use the $self notation.

h4. The default value: defaultValue (string)

The default value (defaultValue) provides means for specifying a default value for the field when the property chain has no matching values in GraphDB. It has no default value. Currently only literals are supported.

h4. Indexing the field: index (boolean)

Fields are indexed by default but that can be changed by using the Boolean option "index". True by default. Fields that are not indexed will be unavailable for queries but may still be used for faceting or sorting, if these are enabled.

h4. Synchronising for faceting: facet (boolean)

Fields are synchronised for faceting by default but that can be changed by using the Boolean option "facet". True by default. Fields that are not synchronised for faceting will not be available for faceted search.

h4. Synchronising for sorting: sort (boolean)

Fields are not synchronised for sorting by default but that can be changed by using the Boolean option "sort". False by default. Fields that are not synchronised for sorting will not be available for ordering the results.

h4. Skipping the analyser: syncAsIs (boolean)

When literal fields are indexed in $(implementation), they will be analysed according to the analyser settings. Should you require that a given field is not analysed you may use syncAsIs. False by default.

h2. Optional parameters

$(block-only-lucene)
h3. Lucene Analyzer

The $(implementation) Connector supports custom Analyzer implementations. They may be specified via the _analyzer_ parameter whose value must be a fully qualified name of a class that extends org.apache.lucene.analysis.Analyzer. The class must have either a default constructor or a constructor with exactly one parameter of type org.apache.lucene.util.Version. For example, these two classes would be valid implementations:

{code}
package com.ontotext.example;

import org.apache.lucene.analysis.Analyzer;

public class FancyAnalyzer extends Analyzer {
public FancyAnalyzer() {
...
}
...
}
{code}

{code}
package com.ontotext.example;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.util.Version;

public class SmartAnalyzer extends Analyzer {
public SmartAnalyzer(Version luceneVersion) {
...
}
...
}
{code}

FancyAnalyzer and SmartAnalyzer could then be used by specifying their fully qualified names, for example:

{code}
...
"analyzer": "com.ontotext.example.SmartAnalyzer",
...
{code}
$(block-only-lucene)

h3. Literals in what language: languages (list of string)

RDF data is often multilingual but you may want to map only some of the languages represented in the literal values. This can be done by specifying a list of language codes.

h3. Entity filtering: entityFilter (string)

The _entityFilter_ parameter is used to fine-tune the set of entities and/or individual values for the configured fields, based on the field value. Entities and field values will be synchronised to $(implementation) if, and only if, they pass the filter. The entity filter is similar to a FILTER() inside a SPARQL query but not exactly the same. Each configured field can be referred to in the entity filter by prefixing it with a "?", much like referring to a variable in SPARQL. Several operators are supported:

|| Operator || Meaning || Example ||
| ?var in (_value1_, _value2_, ...) | Tests if the field _var_'s value is one of the specified values. Values that do not match will be treated as if they were not present in the repository. | ?status in ("active", "new") |
| ?var not in (_value1_, _value2_, ...) | The negated version of the in-operator. | ?status not in ("archived") |
| bound(?var) | Tests if the field _var_ has a valid value. This can be used to make the field compulsory. | bound(?name) |
| _expr1_ \|\| _expr2_ | Logical disjunction of expressions _expr1_ and _expr2_. | bound(?name) \|\| bound(?company) |
| _expr1_ && _expr2_ | Logical conjunction of expressions _expr1_ and _expr2_. | bound(?status) && ?status in ("active", "new") |
| !_expr_ | Logical negation of expression _expr_. | !bound(?company) |
| ( expr ) | Grouping of expressions | (bound(?name) \|\| bound(?company)) && bound(?address) |

The atomic operators _in_, _not in_ and _bound_ accept either an operand that is a field name variable as in the examples above, or a special construction composed of a field name variable followed by a URI. The URI will be used as a property of the particular field value bound to the field name variable, fetched from GraphDB and then its value will be used to evaluate the entity filter expression. It can be illustrated with this SPARQL snippet:

{code}
?fieldName <http://some.property#uri> ?evaluatedValue
{code}

Instead of using the values of ?fieldName, the values of ?evaluatedValue will be used.

In addition to full URIs within < > the filters support the shorthand form *type*, which stands for <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>.

Entity filters can be combined with default values in order to get more flexible behaviour.

A typical use-case for an entity filter is having soft deletes, i.e. instead of deleting an entity it is marked as deleted by the presence of a specific value for a given property.

h4. Basic entity filter example

For example, if we create a connector like this:
{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

INSERT DATA {
inst:my_index :createConnector '''
{
$(only-solr) "solrUrl": "http://localhost:8983/solr",
$(only-elasticsearch) "elasticsearchNode": "localhost:9200",
"types": ["http://www.ontotext.com/example#gadget"],
"fields": [
{
"fieldName": "name",
"propertyChain": ["http://www.ontotext.com/example#name"]
},
{
"fieldName": "city",
"propertyChain": ["http://www.ontotext.com/example#city"]
}
],
"entityFilter":"bound(?city) && ?city in (\\"London\\")"
}
''' .
}
{code}

and then insert some entities:

{code}
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <http://www.ontotext.com/example#> .

# the entity bellow will be synchronised because it has a matching value for city: ?city in ("London")
:alpha
rdf:type :gadget ;
:name "John Synced" ;
:city "London" .

# the entity below will not be synchronised because it is lacking the property completely: bound(?city)
:beta
rdf:type :gadget ;
:name "Peter Syncfree" .

# the entity below will not be synchronised - different city value:
# ?city in ("London") will remove the value "Liverpool" so bound(?city) will be false
:gamma
rdf:type :gadget ;
:name "Mary Syncless" ;
:city "Liverpool" .
{code}

We could create the following index to specify a default value for _city_:

{code}
...
{
"fieldName": "city",
"propertyChain": ["http://www.ontotext.com/example#city"],
"defaultValue": "London"
}
...
}
{code}

The default value will be used for entity:b as it has no value for city in the repository. As the value is "London", the entity will be synchronised.

h4. Advanced entity filter example

Sometimes data represented in RDF is not well suited to map directly to non-RDF. For example, if we have news articles and they can be tagged with different concepts (locations, persons, events, etc.), one possible way to model that is a single property :taggedWith. Consider the following RDF data:

{code}
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <http://www.ontotext.com/example2#> .

:Berlin
rdf:type :Location ;
rdfs:label "Berlin" .

:Mozart
rdf:type :Person ;
rdfs:label "Wolfgang Amadeus Mozart" .

:Einstein
rdf:type :Person ;
rdfs:label "Albert Einstein" .

:Cannes-FF
rdf:type :Event ;
rdfs:label "Cannes Film Festival" .

:Article1
rdf:type :Article ;
rdfs:comment "An article about a film about Einstein's life while he was a professor in Berlin." ;
:taggedWith :Berlin ;
:taggedWith :Einstein ;
:taggedWith :Cannes-FF .

:Article2
rdf:type :Article ;
rdfs:comment "An article about Berlin." ;
:taggedWith :Berlin .

:Article3
rdf:type :Article ;
rdfs:comment "An article about Mozart's life." ;
:taggedWith :Mozart .

:Article4
rdf:type :Article ;
rdfs:comment "An article about classical music in Berlin." ;
:taggedWith :Berlin ;
:taggedWith :Mozart .

:Article5
rdf:type :Article ;
rdfs:comment "A boring article that has no tags." .

:Article6
rdf:type :Article ;
rdfs:comment "An article about the Cannes Film Festival in 2013." ;
:taggedWith :Cannes-FF .
{code}

Now, if we want to map this data to $(implementation) such that the property *:taggedWith _x_* is mapped to separate fields *taggedWithPerson* and *taggedWithLocation* according to the type of _x_ (we are not interested in events), we can map :taggedWith twice to different fields and then use an entity filter to get the desired values:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

INSERT DATA {
inst:my_index :createConnector '''
{
$(only-solr) "solrUrl": "http://localhost:8983/solr",
$(only-elasticsearch) "elasticsearchNode": "localhost:9200",
"types": ["http://www.ontotext.com/example2#Article"],
"fields": [
{
"fieldName": "comment",
"propertyChain": ["http://www.w3.org/2000/01/rdf-schema#comment"]
},
{
"fieldName": "taggedWithPerson",
"propertyChain": ["http://www.ontotext.com/example2#taggedWith"]
},
{
"fieldName": "taggedWithLocation",
"propertyChain": ["http://www.ontotext.com/example2#taggedWith"]
}
],
"entityFilter": "?taggedWithPerson type in (<http://www.ontotext.com/example2#Person>) && ?taggedWithLocation type in (<http://www.ontotext.com/example2#Location>)"
}
''' .
}
{code}

Note: *type* is the short way to write <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>.

The six articles in the RDF data above will be mapped as such:

|| Article URI || Entity mapped? || Value in taggedWithPerson || Value in taggedWithLocation || Explanation ||
| :Article1 | yes | :Einstein | :Berlin | :taggedWith has the values :Einstein, :Berlin and :Cannes-FF. The filter leaves only the correct values in the respective fields. The value :Cannes-FF is ignored as it does not match the filter. |
| :Article2 | yes | | :Berlin | :taggedWith has the value :Berlin. After the filter is applied, only taggedWithLocation is populated. |
| :Article3 | yes | :Mozart | | :taggedWith has the value :Mozart. After the filter is applied, only taggedWithPerson is populated |
| :Article4 | yes | :Mozart | :Berlin | :taggedWith has the values :Berlin and :Mozart. The filter leaves only the correct values in the respective fields. |
| :Article5 | yes | | | :taggedWith has no values. The filter is not relevant. |
| :Article6 | yes | | | :taggedWith has the value :Cannes-FF. The filter removes it as it does not match. |

This can be checked by issuing a faceted search for taggedWithLocation and taggedWithPerson:

{code}
PREFIX : <$(prefix)>
PREFIX inst: <$(prefix-inst)>

SELECT ?facetName ?facetValue ?facetCount {
?search a inst:my_index ;
:facetFields "taggedWithLocation,taggedWithPerson" ;
:facets _:f .
_:f :facetName ?facetName ;
:facetValue ?facetValue ;
:facetCount ?facetCount .
}
{code}

If the filter was applied you should get only :Berlin for taggedWithLocation and only :Einstein and :Mozart for taggedWithPerson:

|| ?facetName || ?facetValue || ?facetCount ||
| taggedWithLocation | http://www.ontotext.com/example2#Berlin | 3 |
| taggedWithPerson | http://www.ontotext.com/example2#Mozart | 2 |
| taggedWithPerson| http://www.ontotext.com/example2#Einstein | 1 |

h1. Overview of connector predicates

The following diagram shows a summary of all predicates that can administer (create, drop, check status) connector instances or issue queries and retrieve results. It can be used as a quick reference of what a particular predicate needs to be attached to. For example, to retrieve entities you need to use :entities on a search instance and to retrieve snippets you need to use :snippets on an entity. Variables that are bound as a result of query are shown in green, blank helper nodes are shown in blue, literals in red, and URIs in orange. The predicates are represented by labelled arrows.

{plantuml}
left to right direction

skinparam activity {
BackgroundColor<<BNode>> #D1E0FF
BackgroundColor<<Var>> #D1FFD1
BackgroundColor<<URI>> #FFCC80
BackgroundColor #FFE3E3
}

partition "Instance level" {
"instance URI" <<URI>> -->[:createConnector] "JSON params"
"instance URI" -->[:dropConnector] "dummy value"
"instance URI" -->[:repairConnector] "dummy value"
"instance URI" -->[:connectorStatus] "?status" <<Var>>
"_:search" <<BNode>> -->[rdf:type] "instance URI"
}

partition "Search level: query and options" {
"_:search" -->[:query] "query value"
"_:search" -->[:limit] "limit value"
"_:search" -->[:offset] "offset value"
"_:search" -->[:orderBy] "order by expression"
"_:search" -->[:facetFields] "field name list"
"_:search" -->[:snippetSize] "snippet size value"
"_:search" -->[:snippetSpanOpen] "string"
"_:search" -->[:snippetSpanClose] "string"
}

partition "Search level: results"
"_:search" -->[:entities] "?entity" <<Var>>
"_:search" -->[:facets] "_:facet" <<BNode>>
"_:search" -->[:totalHits] "?totalHits" <<Var>>
}

partition "Entity level" {
"?entity" -->[:score] "?score" <<Var>>
"?entity" -->[:snippets] "_:snippet" <<BNode>>
}

partition "Snippet level" {
"_:snippet" -->[:snippetField] "?snippetField" <<Var>>
"_:snippet" -->[:snippetText] "?snippetText" <<Var>>
}

partition "Facet level" {
"_:facet" -->[:facetName] "?facetName" <<Var>>
"_:facet" -->[:facetValue] "?facetValue" <<Var>>
"_:facet" -->[:facetCount] "?facetCount" <<Var>>
}


{plantuml}


$(block-only-solr)
h1. Solr specifics

h2. Solr schema generation

When data is added to the index for the first time, the connector will create the appropriate schema fields in the core based on the values in the synchronised fields. Here is a mapping from RDF types to Solr field types. For this to work properly, we assume you are using the schemaless Solr home from the examples in the Solr distribution. It contains the mapped Solr field types and it is declared as managed, which allows the connector to add fields.

|| RDF type || Solr type ||
| URI | string |
| xsd:boolean | booleans |
| xsd:double | tdoubles |
| xsd:float | tfloats |
| xsd:long | tlongs |
| xsd:int | tints |
| xsd:dateTime | tdates |
| other literal values with language set to "en" like "foo"@en | text_en |
| other literal values with no language set | text_general |

h2. Solr deployment

h6. Solr extension

In order to be able to create new Solr cores on the fly you have to use the custom admin handler provided with the Solr Connector. The admin handler has to be added to Solr:

You have two ways to get solr-extension jar:
* Through maven(if you have access to our internal repository). The artifact has the following maven configuration:
{code}
<dependency>
<groupId>com.ontotext.graphdb.plugins</groupId>
<artifactId>solr-core-admin-handler</artifactId>
<version>${connectors.version}</version>
</dependency>
{code}
* If you only have the zip distribution you can find the solr-extension jar in the tools subdirectory


Now copy the jar in <solr-home> and tell Solr to scan the jar and use our custom handler instead of the default one. Add the following lines to the root *solr* tag in solr.xml in <solr-home>:
{code}
<str name="adminHandler">com.ontotext.solr.handler.admin.GraphDBConnectorAdminHandler</str>
<str name="sharedLib">${sharedLib:}</str>
{code}

{note}
Note that this is a limitation of Solr and you are not required to use the custom handler. If you don't want to deploy it, then you will be responsible for creating the Solr core yourself.
{note}

h6. Solr schema setup

To use the connector, the core's schema from which we are going to copy the configuration(most of the time named collection1) should be configured properly:

* allow schema modifications(it should be [managed and mutable|https://cwiki.apache.org/confluence/display/solr/Managed+Schema+Definition+in+SolrConfig])
* the id should be configured to be a long. Include the following in the core's schema.xml from which you are going to copy new cores
{code}
<field name="id" type="long" indexed="true" stored="true" required="true" multiValued="false"/>
{code}

h6. Further configurations

The GraphDB distribution also provides a complete <solr-home> that you can extract at a convenient place and then use it to run Solr.

$(block-only-solr)

h1. Caveats

h2. Order of control

Even though SPARQL per se is not sensitive to the order of triple patterns, the connectors expect to receive certain predicates before others so that queries can be executed properly. In particular, predicates that specify the query or query options need to come before any predicates that fetch results.

The diagram in [#Overview of connector predicates] provides a quick overview of the predicates.

$(block-only-solr)
$(block-only-elasticsearch)

h2. Using a connector with a GraphDB cluster

The $(implementation) connector in this release is beta and does not fully support synchronisation in a GraphDB cluster. In essence, each worker in the cluster will try to synchronise the changes to the same $(implementation) URI. There are two possible scenarios:

h3. Multiple undesired synchronisations to a single $(implementation) instance

In this scenario, each worker will see the same instance at the provided $(implementation) URI (because the URI is unique within the network that connects the workers together. Typically these are URIs that contain normal IP addresses or hostnames that resolve to one and the same IP address on all the workers. Whenever a worker receives updates, it connects to the $(implementation) and synchronise the data there. The process is identical for all workers and thus each update on the $(implementation) side is executed as many times as the number of workers in the cluster. This should only impact update performance but should not lead to any inconsistency errors.

h3. Multiple synchronisations to multiple $(implementation) instances

The user can also provide a URI that is not unique within the cluster, e.g. URIs based on the localhost or URIs with hostnames that resolve to different IPs on each cluster. In other words, each worker will see a different instance of $(implementation) and thus when the worker sends an update to the $(implementation) instance there will be no redundant operations.
$(block-only-elasticsearch)
$(block-only-solr)

h1. Migrating from Lucene4 plugin

You can easily migrate your existing [lucene4 plugin|https://confluence.ontotext.com/display/EM/Lucene4+OWLIM+Plug-in] setup to the new connectors interface.

h3. Create index queries

We provide an automated migration tool for your create index queries. The tool is distributed with GraphDB 6.0 onward and can be found in the tools subdirectory. Here is how to use it:

{code}
java -jar migration.jar --file <input-file> <output-file>
{code}
where *input-file* is your old sparql file and *output-file* is the new sparql file

you can find possible options with
{code}
java -jar migration.jar --help
{code}

h3. Select queries using the index
We changed the syntax for the search queries to be able to match our needs for new features and better design. Here is an example query using the lucene4 plugin:

{code}
PREFIX luc4:<http://www.ontotext.com/owlim/lucene4#>
SELECT ?c ?snippet WHERE {
?c rdf:type <http://data.ontotext.com/ontologies/ontology1/Type1> .

?c luc4:content ("gold" "limit=10;snippet.size=200") .
?c luc4:snippet ?snippet .
?c luc4:score ?score .
}
{code}

and here is it's connectors variant:

{code}
PREFIX conn:<http://www.ontotext.com/connectors/lucene#>
PREFIX inst:<http://www.ontotext.com/connectors/lucene/instance#>

SELECT ?c ?snippet WHERE {
[] a inst:content ;
conn:query "gold" ;
conn:limit "10" ;
conn:snippetSize "200" ;
conn:entities ?entity

?entity conn:snippets ?s .
?s conn:snippetText ?snippet .
}
{code}

note the following changes:

* We are using special predicates for everything - no more key value options in a string
* The query is actually an instance of the index
* snippets belong to the entity
* snippets are now first class objects - you can also get the field of the match
* indexes are now an instance of another namespace. This allows you to create indexes with the name "entities" for example.

Look at [#Overview of connector predicates] for more info on the new syntax and how everything is linked together.