999-samples

Back to All Tutorials list

Core API Samples

WARNING ALL THE BELOW ARE DEPRECATED TUTORIAL FILES

Below are all the functions available in the public core API. Private API and internal methods are not covered. See the raw JS files for code comments on these. For details on the Browser Widget UI libraries, see the Widget Api page.

Conventions used in this document

Any variable with _opt in the name is optional. You can either not provide a value or provide undefined. mljs will introspect other variables to correctly deduce the required function. E.g. if no docuri_opt provided by callback_opt should be - if docuri_opt is a function, mljs correctly sets callback_opt to this.

Function categories

Global functions

  • textToXML - Converts an escaped string to an XMLDocument.
  • xmlToJson - Converts an XMLDocument to a JSON object, with a flat structure.
  • xmlToJsonStrict - Converts and XMLDocument to a JSON object, preserving the exact document structure.

Driver configuration

Database Management

  • mljs.exists (aka mljs.test) - Check if a database exists AND it has a valid REST API endpoint
  • mljs.create - Create a REST API instance, and it's content database
  • mljs.destroy - Destroy a REST API instance, and it's content database

Document management

  • mljs.get - Fetch a document by uri (aka id)
  • mljs.metadata - Fetch a document's metadata by uri
  • mljs.save - Save or Update a document
  • mljs.saveAll - Save or Update a set of documents (FAST aware)
  • mljs.merge - Merge an existing JSON document with the provided information
  • mljs.delete (aka mljs.remove) - Delete a document

Search

ACID Transactions

REST API Extensions

Utility functions

  • mljs.ingestcsv - Ingest a CSV file (FAST aware)
  • mljs.fast - Wrap functions so they execute in parallel (see each function's docs)

Alphabetical function list for global functions

# window.textToXML(text)

Converts an escaped JSON string to an XMLDocument. Uses the Browser's built in parser.

var xmlString = "Biology \n 101\t   2014";
var xmlDoc = textToXML(xmlString);
var jsonDoc = xmlToJson(xmlDoc);
console.log(JSON.stringify(jsonDoc));
// prints: {mydoc: {reference: "Grades",class: "Biology 101",year: "2014"}}

# window.xmlToJson(text)

Converts an XMLDocument instance to a JSON object. Merges adjacent text. Sets object value to text if it only contains text. Trims whitespace. Strips namespace from objects. Uses a flat structure, rather than an @prefix for attributes. Not safe to use if an attribute and element under the same node can have the same name, or if multiple elements have the same name with different namespaces. Used internally to convert MarkLogic error messages (which are XML by default, as per a server setting).

var xmlString = "Biology \n 101\t   2014";
var xmlDoc = textToXML(xmlString);
var jsonDoc = xmlToJson(xmlDoc);
console.log(JSON.stringify(jsonDoc));
// prints: {mydoc: {reference: "Grades",class: "Biology 101",year: "2014"}}

# window.xmlToJsonStrict(text)

Converts an escaped JSON string to an XMLDocument. Uses the Browser's built in parser.

var xmlString = "Biology \n 101\t   2014";
var xmlDoc = textToXML(xmlString);
var jsonDoc = xmlToJsonStrict(xmlDoc);
console.log(JSON.stringify(jsonDoc));
// prints: {"ns:mydoc": {"@attributes": {reference: "Grades"},"ns:class": "#text": [ "Biology \n"," 101\t   "],"ns:year": "2014"}}

Alphabetical function list for mljs

# mljs.begin(name_opt,callback)

Begin a transaction. All altering functions subsequently called will be within this transaction boundary. Be aware that searches also execute within a transaction. Also, there is a transaction timeout on the server so it's not recommended to have longer running transactions across multiple requests.

var db = new mljs();
db.begin("mytrans", function(result) {
  db.save({title: "first"},"/docs/1", function (sr1) {
  db.save({title: "second"},"/docs/2",function (sr2) {
  db.commit(function (cr) {
    if (cr.inError()) {
      console.log("error: " + JSON.stringify(cr.error));
    } else {
      console.log("success");
    }
})})})});

Links: REST API


# mljs.collect(collection,fields_opt,callback_opt)

Returns a search api response contain a paged list of documents, with their content, and total, for all documents within a collection.

var db = new mljs(); // default options

// add three docs to the collection
var col = {collection: "testcol"};
var uris = ["/collections/1","/collections/2","/collections/3"];
db.save({name:"first"},uris[0],col,function(result) {
db.save({name:"second"},uris[1],col,function(result) {
db.save({name:"third"},uris[2],col,function(result) {

// get docs in collection
db.collect(col.collection,function(result) {
  console.log("Total result count: " + result.doc.total);
  // NB result.doc contains the JSON search result object from the REST API

});});});});

Links: REST API


# mljs.commit(callback)

Commits a transaction.

See example in mljs.begin above.

Links: REST API


# mljs.configure()

Configures the database driver to access a particular database. You can supply a subset of all options and they will be merged with the defaults (shown below for convenience).

var options = {
  host: "localhost", port: 9090, adminport: 8002,
  ssl: false, auth: "digest", username: "admin",password: "admin",
  database: "mljstest",
  searchoptions: {}, fastthreads: 10, fastparts: 100
};
var db = new mljs();
db.configure(options);
var options = {
  port: 5073
};
var db = new mljs();
db.configure(options);

Links: REST API


# mljs Constructor()

Creates an instance of the database driver with the default (vanilla local server) configuration

var db = new mljs();

# mljs.create(callback_opt)

Creates a database with the options within this mljs instance. To set the options, call configure before you call create.

var db = new mljs();
db.create(function(result) {
  console.log("Database created?: " + (!result.inError));
});

Links: REST API


# mljs.delete(docuri,callback_opt)

Deletes the document with the provided URI from the database.

var db = new mljs();
db.delete("/docs/1",function(result) {
  console.log("Document deleted?: " + (!result.inError));
});

Links: REST API


# mljs.destroy(callback_opt)

Destroys this content database and REST API instance.

var db = new mljs();
db.destroy(function(result) {
  console.log("Database and REST endpoint destroyed?: " + (!result.inError));
});

Links: REST API


# mljs.do(options_opt,content_opt,callback_opt)

Performs the specified REST API call. This is a wrapper around the internal mljs workings, so you get the benefits of all the authentication and connection maintenance being handled for you. This is intended for use by developers who need to execute their own custom resource handlers, or newly available REST API features before this driver has been updated.

var db = new mljs(); // default options

var options = {
  path: "/v1/search?q=squirrel&format=json",
  method: "GET"
};

db.do(options,function(result) {
  console.log("Number of results: " + result.doc.total);
});

Links: REST API


# mljs.exists(callback)

Checks whether this database exists AND has a REST API instance to access it.

var db = new mljs();
db.exists(function(result) {
  console.log("DB exists?: " + result.exists);
});

Links: REST API


# mljs.fast(callback_opt)

Specifies that all subsequent requests should execute in fast (parallel) mode. Only applies to utility functions that perform multiple REST calls.

Not yet implemented

var db = new mljs();
db.fast(function (result) {
  var jsonArr = [{title: "first"},{title: "second"}];
  var uriArr = ["/docs/1","/docs/2"];
  db.saveAll(jsonArr,uriArr,function(result) {
    console.log("All documents added in parallel");
  });
});

# mljs.get(docuri,options_opt,callback_opt)

Fetches the document at the specified URI. options_opt may be a JSON object containing the key transform which is passed as the transform parameter to the /v1/documents REST endpoint.

var db = new mljs();
db.get("/docs/1", function(result) {
  console.log("Doc JSON content: " + JSON.stringify(result.doc));
});

Links: REST API


# mljs.ingestcsv(csvdata,docid_opt,callback_opt)

Ingests a CSV file, chunking if necessary. This function is FAST parallelisation aware.

Not yet implemented

Links: FAST mode


# mljs.keyvalue(key,value,keytype_opt,callback_opt)

Performs a simple key-value search. Useful if you want a list of documents (typically JSON) with keys that match a particular value. Useful if you have, for example, categories.

var db = new mljs(); // default options

// add three docs to the collection
var col = {collection: "kvcol"};
var uris = ["/kv/1","/kv/2","/kv/3"];
db.save({name:"first whippet"},uris[0],col,function(result) {
db.save({name:"second squirrel"},uris[1],col,function(result) {
db.save({name:"third wolf"},uris[2],col,function(result) {

// search for name's value (exact match)
db.keyvalue("name","third wolf",function(result) {
  console.log("TEST: KEYVALUE results object: " + JSON.stringify(result));
})})})});

Links: REST API


# mljs.list(directory,callback_opt)

Returns all documents as a search api result set within a particular directory.

var db = new mljs();
var col = {collection: "testcol"};
var uris = ["/dir/1","/dir/2","/dir/3"];
db.save({name:"first"},uris[0],col,function(result) {
db.save({name:"second"},uris[1],col,function(result) {
db.save({name:"third"},uris[2],col,function(result) {

// get docs in directory
db.list("/dir",function(result) {
  console.log("TEST: list() results object: " + JSON.stringify(result));
})})})});

Links: REST API


# mljs.merge(json,docuri,callback_opt)

Utility method. Merges the specified JSON with the document at the specified URI. Currently performs a get followed by a save.

var db = new mljs();
var col = {collection: "mergecol"};
var uris = ["/merge/1"];
var json1 = {name: "first whippet"};
var json2 = {weight: "120lbs"};
db.save(json1,uris[0],col,function(result) {

// merge the weight into the same document as name
db.merge(json2,uris[0],function(result) {
db.get(uris[0],function(result) {
  console.log("TEST: MERGE: merged doc: " + JSON.stringify(result.doc));
})})});

Links: mljs.get | mljs.save


# mljs.metadata(docuri,callback_opt)

Returns all of a document's metadata. Includes all properties, collections, permissions, quality. Uses same mechanism as get().

var db = new mljs(); // default options
var uri = "/meta/1";
db.save({from: "test", to: "all", body: "wibble"},uri, {collection: "metatest"},function(result) {
// now fetch it's metadata (properties, collections, permissions)
db.metadata(uri, function(result) {
  console.log("TEST: METADATA: " + JSON.stringify(result));
})});

Links: REST API


# mljs.rollback(callback)

Abandons a currently open transaction.

var db = new mljs(); // default options

db.begin(function(result) {
var txid = result.txid;

// now create doc
var uri = "/trans/rollback/5";
var json = {title: "Transaction commit test doc"};
db.save(json,uri,function(result) {

// now abandon transaction
db.rollback(function(result) {

// see if the document doesn't exist (i.e. the transaction has been abandoned)
db.get(uri, function(result) {
  console.log("Document exists?: " + !result.inError);
})})})});

Links: REST API


# mljs.save(json,docuri_opt,props_opt,callback_opt)

Saves or updates a document. If no URI is specified, one is generated for you by using JavaScript's random number generator. Currently the props_opt JSON object only supports the collection parameter, and you can only specify one collection. This is in line with the REST API document POST call.

See get() above

Links: REST API


# mljs.saveAll(doc_array,uri_array_opt,callback_opt)

Helper method to save a set of documents in a single call. Actually performs multiple REST API calls. Is FAST parallelisation aware.

See fast() above

Links: FAST mode


# mljs.saveSearchOptions(name,searchoptions,callback_opt)

Persists a search options JSON object with the specified name. This can be referred to in any of the search methods (the options_opt variable) to control the results of a search operation.

Links: REST API


# mljs.search(query_opt,options_opt,start_opt,sprops_opt,callback)

Performs a free text search using the default built in grammar of MarkLogic. Returns a search result set. start_opt is a numeric containing the first id (1 based) of the first document in order to return as part of the result set (page). sprops_opt is a JSON object containing either a directory or collection parameter, or both, to be passed as parameters to the /v1/search REST endpoint.

var db = new mljs(); // default options

// add three docs to the collection
var col = {collection: "searchcol"};
var uris = ["/search/1","/search/2","/search/3"];
db.save({name:"first whippet"},uris[0],col,function(result) {
db.save({name:"second squirrel"},uris[1],col,function(result) {
db.save({name:"third wolf"},uris[2],col,function(result) {

// search
db.search("squirrel",function(result) {
  console.log("TEST: SEARCH results object: " + JSON.stringify(result));
})})})});

Links: REST API | Search Grammar


# mljs.searchCollection(collection_opt,query_opt,options_opt,callback)

Performs a free text search using the default built in grammar of MarkLogic. Restricts results to the given collection(s). Returns a search result set. Collection is a comma delimited string.

var db = new mljs(); // default options

// add three docs to the collection
var col = {collection: "searchcol"};
var uris = ["/search/1","/search/2","/search/3"];
db.save({name:"first whippet"},uris[0],col,function(result) {
db.save({name:"second squirrel"},uris[1],col,function(result) {
db.save({name:"third wolf"},uris[2],col,function(result) {

// search
db.searchCollection("searchcol","squirrel",function(result) {
  console.log("TEST: SEARCH results object: " + JSON.stringify(result));
})})})});

Links: REST API | Search Grammar


# mljs.setLogger()

Sets the Winston Logger used by this database driver.


var logger = new (winston.Logger)({
  transports: [
    new winston.transports.Console();
  ],
  exceptionHandlers: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'logs/test.log' })
  ]
});

var db = new mljs();
db.setLogger(logger);

db.save({name: "test json"},"/logger/1"); // now look at the console or logs/test.log

# mljs.structuredSearch(query_opt,options_opt,callback)

Performs a structured search using the REST API.

var db = new mljs(); // default options

// add three docs to the collection
var col = {collection: "ssearchcol"};
var query = {"query":
  {"term-query":
    {"text":
      ["rhino"]
    }
  }
};
var uris = ["/ssearch/1","/ssearch/2","/ssearch/3"];
db.save({name:"first elephant"},uris[0],col,function(result) {
db.save({name:"second rhino"},uris[1],col,function(result) {
db.save({name:"third penguin"},uris[2],col,function(result) {

// get docs in collection
db.structuredSearch(query,function(result) {
  console.log("TEST: STRUCTUREDSEARCH results object: " + JSON.stringify(result));
})})})});

Links: REST API | Structured Search


# mljs.subscribe(nodeurl,lat,lon,radiusmiles,callback_opt)

Uses Adam Fowler's (Me!) subscribe custom REST API resource to subscribe a node (RESTful web service URL) to a geospatial search. Uses the Alerting Framework to send matching documents - as they arrive - to the nodeurl REST endpoint provided.

Not yet implemented


# mljs.unsubscribe(nodeurl,callback_opt)

Unsubscribes a nodeurl from all alerts. Uses Adam Fowler's (Me!) custom subscribe REST API resource and the Alerting framework.

Not yet implemented


# mljs.values(query,tuplesname,optionsname,callback_opt)

Calls the /v1/values endpoint in order to lookup 2-way range index co-occurences (tested) or lexicon values (untested). Requires search options to have been previously saved. The specified tuple name must exist within those search options.

var db = new mljs(); // default options
var query = {
  query: {
    "collection-query": {
      "uri": ["movies"]
    }
  }
};
db.values(query,"movie-year-tuple","movie-search-options",function(result) {
  db.logger.debug("Movies Year Co-occurence JSON: " + stringify(result.doc));
});

Links: REST API


Back to All Tutorials list

MLJS - A JavaScript wrapper for the MarkLogic REST API
MarkLogic 2012-2014
Documentation generated by JSDoc 3.2.3-dev on Mon Jul 18 2016 09:14:13 GMT+0100 (BST) using the DocStrap template.