Skip to main content

Develop with FastTrack

MarkLogicContext

MarkLogicContext enables FastTrack applications to connect to the MarkLogic REST API. MarkLogicContext exposes methods for performing searches, retrieving documents, setting search constraints, and more. FastTrack UI widgets do not communicate with MarkLogic directly. Instead, widgets communicate by executing methods from MarkLogicContext.

MarkLogicContext saves the responses returned from MarkLogic in state variables. Data from MarkLogic can be displayed in FastTrack applications by accessing these state variables. MarkLogicContext methods also return HTTP responses, so the application can handle them directly (if desired).

MarkLogicContext leverages React context to make the methods and variables accessible throughout a FastTrack-enabled application.

MarkLogicProvider 

MarkLogicProvider is a React context provider that gives FastTrack widgets access to MarkLogicContext. After wrapping a React application component with MarkLogicProvider (see the example), all child widgets in the application can import MarkLogicContext and have access to MarkLogicContext methods and state. 

MarkLogicProvider props define the connection settings for the MarkLogic backend. In a three-tier application, set the props to the connection settings for the middle-tier server of the application. 

MarkLogicProvider API

Prop

Type

Description

scheme

string

HTTP scheme used when connecting to the backend. Default: "http".

host

string

Host used when connecting to the backend. Default: "localhost".

port

number

Port used when connecting to the backend. Default: 4000

options

string

Name of the installed MarkLogic query options used for searches.

auth

object

Authentication object.

auth.username

string

User name used to authenticate with the backend.

auth.password

string

Password used to authenticate with the backend.

paginationOptions

object

Pagination object.

paginationOptions.pageLength

number

Page length for searches. Default: 10.

requestInterceptor

function

Transformation function applied to all backend requests. For details, see the Axios documentation.

responseInterceptor

function

Transformation function applied to all backend responses. For details, see the Axios documentation.

searchTransform

string

Name of the transformation installed on MarkLogic to apply to search results.

documentTransform

string

Name of the transformation installed on MarkLogic to apply to retrieved documents.

MarkLogicProvider example
import { MarkLogicProvider } from "ml-fasttrack"
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <MarkLogicProvider
    scheme="http"
    host="localhost"
    port="4001"
    options="my-options"
    auth={{ username: "theUser", password: "p4ssw0rd" }}
    paginationOptions={{ pageLength: 20 }}
  >
    <App />
  </MarkLogicProvider>
);

MarkLogicContext methods

This section describes the MarkLogicContext methods.

setQtext(qtext)

This method sets the qtext search state property.

Argument 

Type 

Description 

qtext

string

A string query.

When qtext changes, MarkLogicContext executes a new /v1/search using the current context state and populates the searchResponse property with the response.

setQtext(qtext) example
context.setQtext("fast OR track");
setCollections(collections)

This method sets the collections state property. Collections allow documents to be organized into subsets. Searches can then be constrained by one or more collections. When collections changes, MarkLogicContext executes a new search using the current context state and populates the searchResponse property with the response.

Argument 

Type 

Description 

collections

string[]

An array of collections.

setCollections(collections) example
context.setCollections(["person", "organization"]);
setDirectories(directories)

This method sets the directories state property. Directories organize documents into subsets based on paths in URIs. Searches can be constrained by directories. When the directories state property changes, MarkLogicContext executes a new search using the current context state and populates the searchResponse property with the response.

Argument 

Type 

Description 

directories

string[]

An array of directories.

setDirectories(directories) example
context.setDirectories(["/pets/dogs", "/pets/cats"]);
setPageLength(length)

This method sets the number of results returned when executing postSearch().

Argument

Type

Description

length

number

Page length when executing postSearch(). Default: 10.

setPageLength(length) example
context.setPageLength(20);
postSearch(combinedQuery, startIndex)

This method executes a call to POST /v1/search. The call returns a Promise. The Promise is fulfilled with an HTTP response when it is successful. The searchResponse state variable is also populated with the response.

Argument 

Type 

Description 

combinedQuery

object

A combined query object. 

startIndex

number

The index of the first result to return (the first result is index 1). Default: 1.

postSeaech (CombinedQuery, startIndex) example

This example searches for documents containing the strings "fast" or "track". The example returns results, starting with the second result.

const combinedQuery = {  
  qtext: "fast OR track"
}
 
context.postSearch(combinedQuery, 2).then(response => {
  console.log(response);
})
getSuggestedSearch(partialQ, limit)

This method executes a call to GET /v1/suggest. The call returns a Promise. When the response is successful, the promise is fulfilled with an HTTP response. The suggestSearchResponse state variable is also populated with the response. For more details, see Generating Search Term Completion Suggestions.

Argument

Type

Description

partialQ

string

A partial query string.

limit

number

The maximum number of selections to return. Default: 10.

 

getSuggestedSearch(partialQ, limit) example
context.getSuggestedSearch("New", 5).then(response => {
  console.log(response);
})
getDocument(uri, parameters)

This method executes a call to GET /v1/documents. The method returns a Promise. When the call is successful, the promise is fulfilled with an HTTP response. The document content will be in the data property of the response object. The documentResponse state variable will also be populated with the response.

Argument

Type

Description

uri

string

URI of the document to retrieve.

parameters

object

Object of key/value pairs corresponding to URL parameters. For details, see GET /v1/documents.

getDocument(uri, parameters) example
const uri = "/person/1001.json";
 
context.getDocument(uri, {database: "my-app-db"}).then(response => {
  console.log(response);
})
getSparql(query, parameters)

The getSparql(query, parameters) method executes a call to GET /v1/graphs/sparql. The next action depends on the results of the call:

  • When the call is successful, a Promise is returned and the sparqlResponse state variable is populated with the response.

  • If the call is unsuccessful, an error is written to the console.

Argument

Type

Description

query

string

SPARQL query.

parameters

object

Object of key/value pairs corresponding to URL parameters. For details, see GET /v1/graphs/sparql.

getSparql(query, parameters) example
const sq = `SELECT *
  WHERE {
    ?s <http://xmlns.com/foaf/0.1/givenname/> ?o
  } LIMIT 10`;
 
context.getSparql(sq, {database: "ml-demo-app-content"}).then(response => {
  console.log(response);
})
postSparql(combinedQuery)

The postSparql(combinedQuery) method executes a call to POST /v1/graphs/sparql. The next action depends on the results of the call:

  • When the call is successful, a Promise is returned, and the sparqlResponse state variable is populated with the response.

  • If the call is unsuccessful, an error is written to the console.

Argument

Type

Description

combinedQuery

object

A combined query object that includes a sparql property.

postSparql (combinedQuery) example
const sq = `SELECT *
  WHERE {
    ?s <http://xmlns.com/foaf/0.1/givenname/> ?o
  } LIMIT 10`;
 
const combinedQuery = {  
  qtext: "fast OR track",
  sparql: sq
}
 
context.postSearch(combinedQuery).then(response => {
  console.log(response);
})
addStringFacetConstraint(constraint)

This method adds a constraint from the StringFacet widget to the context state. When a check box selection is made, this method receives the constraint object passed to the StringFacetonSelect event handler. Internally, this method sets a range-constraint-query.

Argument 

Type 

Description 

constraint

object

A string facet constraint object.

constraint.type

string

The facet type ("string").

constraint.name

string

The facet name.

constraint.value

string[]

An array of selected values for the facet.

constraint.operator

string

Optional constraint operator.

constraint.title

string

The constraint title.

addStringFacetConstraint(constraint) example
const handleFacetClick = (constraint) => {
  context.addStringFacetConstraint(constraint);
}
 
return (
  <StringFacet
    title="Status"
    name="status"
    data={context.searchResponse?.facets?.status}
    onSelect={handleFacetClick}
    reset={resetStringFacet}
  />
)
removeStringFacetConstraint(constraint)

This method removes a string facet constraint from the context state. The method receives the constraint object passed to the SelectedFacets removeStringFacet event handler when a selected facet is removed. Internally, this method removes a range-constraint-query.

Argument

Type

Description

constraint

object

A string facet constraint object.

constraint.type

string

The facet type ( "string").

constraint.name

string

The facet name.

constraint.value

string[]

An array of selected values for the facet.

constraint.operator

string

constraint.title

string

The constraint title.

removeStringFacetConstraint(constraint) example
return (  
  <SelectedFacets
    selectedFacetConfig={{
      string: {
        color: 'red',
        closable: true,
      }
    }}
    stringFacets={context.stringFacetConstraints}
    removeStringFacet={context.removeStringFacetConstraint}
  ></SelectedFacets>
)
addRangeFacetConstraint(constraint)

The addRangeFacetConstraint(constraint) method adds a range facet constraint to the context state. The method receives the constraint object passed to the DateRangePicker onSelect event handler or the NumberRangeFacet and BucketRangeFacet onChange event handlers. Internally, this method sets a range-constraint-query.

Argument

Type

Description

constraint

object

A string facet constraint object.

constraint.type

string

The facet type. The facet type is:

  • "date" for DateRangePicker constraints.

  • "number" for NumberRangeFacet constraints.

  • "string" for BucketRangeFacet constraints.

constraint.name

string

The facet name.

constraint.value

string[]

An array of selected values for the facet.

constraint.operator

string

Optional constraint operator.

constraint.title

string

The constraint title.

addRangeFacetConstraint(constraint) example
const handleValueRange = (constraint) => {
  context.addRangeFacetConstraint(constraint);
}
 
return (
  <NumberRangeFacet
    title="Salary"
    name="salary"
    data={context?.searchResponse?.facets?.salary}
    minValue={0}
    maxValue={100000}
    onChange={handleValueRange}
  />
)
removeRangeFacetConstraint(constraint)

The removeRangeFacetConstraint(constraint) method removes a range facet constraint from the context state. The method receives the constraint object passed to the SelectedFacets removeRangeFacet event handler when a selected facet is removed. Internally, this method removes a range-constraint-query.

Argument

Type

Description

constraint

object

A range facet constraint object.

constraint.type

string

The facet type, which is:

  • "date" for DateRangePicker constraints.

  • "number" for NumberRangeFacet constraints.

  • "string" for BucketRangeFacet constraints.

constraint.name

string

The facet name.

constraint.value

string[]

An array of selected values for the facet.

constraint.operator

string

Optional constraint operator.

constraint.title

string

The constraint title.

removeRangeFacetConstraint(constraint) example
return (  
  <SelectedFacets
    selectedFacetConfig={{
      string: {
        color: 'red',
        closable: true,
      }
    }}
    rangeFacets={context.rangeFacetConstraints}
    removeRangeFacet={context.removeRangeFacetConstraint}
  ></SelectedFacets>
)
addGeoConstraint(geoConstraint)

This method adds a geospatial constraint to the context state. The method receives a constraint object constructed from the coordinate array passed into the GeoMap onGeoSearch event handler. For more information, see addGeoConstraint(geoConstraint) example.

Argument

Type

Description

geoConstraint

object

A geospatial structured query constraint object. Object properties depend on the type of index settings and the query options defined for documents.

addGeoConstraint(geoConstraint) example
const handleGeoSearch = (polygonsCoordsArr) => {
  const query =
  {
    "type": "geo-elem-pair-query",
    "lat": "Latitude",
    "lon": "Longitude",
    "parent": "Location",
    "polygon": polygonsCoordsArr.map((coords) => {
      const pointObj = {
        "point": coords[0]?.map((ele) => {
          return {
            "latitude": parseFloat(ele[1]),
            "longitude": parseFloat(ele[0])
          }
        })
      }
      return pointObj
    })
  }
  context.addGeoConstraint(query);
}
  
return (      
  <GeoMap
    markers={context.searchResponse?.results}
    sketch={true}
    transformMarkers={transformMarkers}
    transformShapes={transformShapes}
    viewType="2D"
    useWeb={false}
    showGallery={false}
    showToggle={false}
    onClickMap={onClickMap}
    onGeoSearch={handleGeoSearch}
  /> )
patchComment(uri, config)

The patchComment(uri, config) method adds a comment to a document specified by a URI. This method works with the CommentBox onSubmit event handler. The event handler receives an object representing a comment as an argument.

Argument 

Type 

Description 

uri

string

URI of the document for the comment.

config

object

Comment configuration object.

config.content

object

Comment content object.

config.content.comment

string

Comment text.

config.content.username

string

User name of the commenter.

config.content.ts

string

Timestamp of the comment.

config.content.imgSrc

string

Image URL associated with the comment. For example, this could point to an image of the commenter.

config.context

string

An XPath expression that selects the node or property where the comment is inserted.

patchComment(uri, config) example
const onSubmitComment = async (comment) => {
  let res = await context.patchComment("/person/1001.json", { content: comment, context: '/person/comments' })
  if (res.success === true) {
    context.getDocument(selectedUri);
  } else {
    alert('Comment submission failed')
  }
}
 
<CommentBox
  label="Comments"
  inputPlaceholder="Add a comment"
  buttonLabel="Post"
  onSubmit={(comment) => onSubmitComment(comment)}
  username="joe-user"
  imgSrc="https://example.org/joe.jpg"
  profileImage={{
    alt: 'Avatar',
    path: 'https://example.org/joe.jpg'
  }}
/>
editComment(uri, id, config)

This method edits a comment with a given ID in a document specified by a URI. The method works with the CommentList onSaveComment event handler. The event handler receives the comment ID and an object representing the edited comment as arguments.

Argument

Type

Description

uri

string

URI of the document for the comment.

id

string

ID of the comment.

config

object

Comment configuration object.

config.content

object

Comment content object.

config.content.comment

string

Comment text.

config.content.username

string

User name of the commenter.

config.content.ts

string

Timestamp of the comment.

config.content.imgSrc

string

Image URL associated with the comment. For example, the URL of an image of the user.

config.context

string

An XPath expression that selects the node or property where the comment is edited.

editComment(uri, id, config) example
const onEditComment = async (id, comment) => {
  let res = await context.editComment("/person/1001.json", id, { content: comment, context: '/person/comments/comment' })
  if (res.success !== true) {
    alert('Comment failed to be edited')
  }
}
 
<CommentList
  data={context.documentResponse}
  config={{comments: {
    path: 'data.person.comments.comment'
  }}}
  username="joe-user"
  onSaveComment={(id, comment) => onEditComment(id, comment)}
  onDeleteComment={(id) => onDeleteComment(id)}
deleteComment(uri, id, context)

This method deletes a comment with a given ID in a document specified by a URI. Works with the CommentList onDeleteComment event handler. The event handler receives the ID of the comment to delete as an argument.

Argument

Type

Description

uri

string

URI of the document with the comment to delete.

id

string

ID of the comment to delete.

context

string

An XPath expression that selects the comment node or property to delete.

deleteComment(uri, id, context) example
const onDeleteComment = async (id) => {
  let res = await context.deleteComment("/person/1001.json", id, '/person/comments/comment')
  if (res.success !== true) {
    alert('Comment failed to be deleted')
  }
}
 
<CommentList
  data={context.documentResponse}
  config={{comments: {
    path: 'data.person.comments.comment'
  }}}
  username="joe-user"
  onSaveComment={(id, comment) => onEditComment(id, comment)}
  onDeleteComment={(id) => onDeleteComment(id)}
/>

MarkLogicContext state variables

This section contains information on the MarkLogicContext state variables.

searchResponse

This variable contains the result of the postSearch() method.

searchResponse example
useEffect(() => {
  context.postSearch({qtext: "Alabama OR Texas"});
}, []);
 
// searchResponse
 
{
    "snippet-format": "snippet",
    "total": 2,
    "start": 1,
    "page-length": 10,
    "results": [
        {
            "index": 1,
            "uri": "/person/1002.json",
            "path": "fn:doc(\"/person/1002.json\")",
            "score": 10240,
            "confidence": 0.5028362,
            "fitness": 0.5028362,
            "href": "/v1/documents?uri=%2Fperson%2F1002.json",
            "mimetype": "application/json",
            "format": "json",
            "matches": [
                {
                    "path": "fn:doc(\"/person/1002.json\")/envelope/address/text(\"state\")",
                    "match-text": [
                        {
                            "highlight": "Texas"
                        }
                    ]
                }
            ]
        },
        {
            "index": 2,
            "uri": "/person/1003.json",
            "path": "fn:doc(\"/person/1003.json\")",
            "score": 10240,
            "confidence": 0.5028362,
            "fitness": 0.5028362,
            "href": "/v1/documents?uri=%2Fperson%2F1003.json",
            "mimetype": "application/json",
            "format": "json",
            "matches": [
                {
                    "path": "fn:doc(\"/person/1003.json\")/envelope/address/text(\"state\")",
                    "match-text": [
                        {
                            "highlight": "Alabama"
                        }
                    ]
                }
            ]
        }
    ],
    "qtext": "Alabama OR Texas",
    "metrics": {
        "query-resolution-time": "PT0.005024S",
        "snippet-resolution-time": "PT0.000615S",
        "total-time": "PT0.315651S"
    }
}
sparqlResponse

Result of the getSparql() or postSparql() methods.

sparqlResponse example
useEffect(() => {
  context.getSparql(`
    SELECT *
    WHERE {
    ?s ?p ?o .
    ?s <http://xmlns.com/foaf/0.1/knows/> ?o
    } LIMIT 10
  `);
}, []);
 
// sparqlResponse
 
{
    "head": {
        "vars": [
            "s",
            "p",
            "o"
        ]
    },
    "results": {
        "bindings": [
            {
                "s": {
                    "type": "uri",
                    "value": "http://example.org/1001"
                },
                "p": {
                    "type": "uri",
                    "value": "http://xmlns.com/foaf/0.1/knows/"
                },
                "o": {
                    "type": "literal",
                    "value": "1002"
                }
            },
            {
                "s": {
                    "type": "uri",
                    "value": "http://example.org/1001"
                },
                "p": {
                    "type": "uri",
                    "value": "http://xmlns.com/foaf/0.1/knows/"
                },
                "o": {
                    "type": "literal",
                    "value": "1003"
                }
            },
            {
                "s": {
                    "type": "uri",
                    "value": "http://example.org/1002"
                },
                "p": {
                    "type": "uri",
                    "value": "http://xmlns.com/foaf/0.1/knows/"
                },
                "o": {
                    "type": "literal",
                    "value": "1001"
                }
            },
            {
                "s": {
                    "type": "uri",
                    "value": "http://example.org/1003"
                },
                "p": {
                    "type": "uri",
                    "value": "http://xmlns.com/foaf/0.1/knows/"
                },
                "o": {
                    "type": "literal",
                    "value": "1001"
                }
            }
        ]
    }
}
suggestedSearchResponse

This variable is the result of the getSuggestedSearch() method.

suggestedSearchResponse example
useEffect(() => {
  context.getSuggestedSearch("New", 5)
}, []);
 
// suggestedSearchResponse
 
{
    "suggestions": [
        "\"New Haven\"",
        "\"New York City\"",
        "Newark",
        "Newton"
    ]
}
stringFacetConstraints

Current string facet constraints of the context state. Constraints may be added with addStringFacetConstraint() and removed with removeStringFacetConstraint().

stringFacetConstraints example
useEffect(() => {
  context.addStringFacetConstraint([
    {
        "type": "string",
        "name": "status",
        "value": [
            "Active"
        ],
        "title": "Status"
    }
])
}, []);
 
// stringFacetConstraints
 
[
    {
        "type": "string",
        "name": "status",
        "value": [
            "Active"
        ],
        "title": "Status"
    }
]

 

rangeFacetConstraints

The rangeFacetConstraints state variable holds the current range facet constraints of the context state. Constraints may be added with addRangeFacetConstraint() and removed with removeRangeFacetConstraint().

rangeFacetConstraints example
useEffect(() => {
  context.addStringFacetConstraint([
    [
        {
            "type": "number",
            "name": "salary",
            "value": 50000,
            "operator": "GE",
            "title": "Salary"
        },
        {
            "type": "number",
            "name": "salary",
            "value": 100000,
            "operator": "LE",
            "title": "Salary"
        }
    ]
  ])
}, []);
 
// rangeFacetConstraints
 
[
    [
        {
            "type": "number",
            "name": "salary",
            "value": 50000,
            "operator": "GE",
            "title": "Salary"
        },
        {
            "type": "number",
            "name": "salary",
            "value": 100000,
            "operator": "LE",
            "title": "Salary"
        }
    ]
]