Chapter 10. Searching with the Optic API

The Optic API, introduced in MarkLogic 9, implements common relational operations over data extracted from documents. This chapter illustrates how to accomplish some common tasks, which should help in transitioning to MarkLogic from a relational background.

Paging Over Results


An Optic API query returns a large result set. Get a stable set of results a page at a time.


Applies to MarkLogic versions 9+ and higher

In its simplest form:

const op = require('/MarkLogic/optic');
const pageSize = ...;
const pageNumber = ...;

  .offsetLimit(op.param('offset'), pageSize)
  .result(null, {offset: pageSize * (pageNumber - 1)})

Expanded out to a main module, which allows the caller to specify the page and a timestamp, the recipe looks like this:

const op = require('/MarkLogic/optic');

const pageNumber =
  parseInt(xdmp.getRequestField('page', '1'), 10);
const pageSize = 1000;

let timestamp = xdmp.getRequestField('timestamp');
if (timestamp === null) {
  timestamp = xdmp.requestTimestamp();

const response = {
  timestamp: timestamp,
  page: pageNumber,
  results: xdmp.invokeFunction(
    function() {
      return op.fromTriples([...])
        .offsetLimit(op.param('offset'), pageSize)
        .result(null, {offset: pageSize * (pageNumber - 1)});
    { timestamp: timestamp }


Required Privilege

  • xdmp:timestamp


Sometimes your result set will be bigger than you want to return in a single request. Paging solves this problem ...

Get MarkLogic Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.