Skip to main content

Knowledge Base: JavaScript Engine

How RavenDB uses Jint

  • Execution context:
    Jint executes a JavaScript function on a single document at a time, with each execution running in isolation.
    Its processing context is limited to a single document, with no persistent execution state -
    even in patch operations, where it might appear to maintain continuity.

  • Performance considerations:
    Since initializing the Jint engine is resource-intensive,
    RavenDB caches Jint instances based on user-defined scripts to reuse them and enhance performance.

  • Execution limitations:

    • RavenDB limits the amount of statements that can be performed for each document processing.
      The default value is 10,000 and it can be set using the Patching.MaxStepsForScript configuration.
    • RavenDB limits the amount of cached Jint engines.
      The default value is 2,048 and it can be set using the Patching.MaxNumberOfCachedScripts configuration.
    • Recursive calls within scripts are limited to a depth of 64, a constant value that cannot be modified.

Predefined JavaScript functions

In addition to Jint's ECMAScript 5.1 implementation,
RavenDB provides the following set of predefined functions:

Document operations:

Method SignatureReturn typeDescription
id(document)stringReturns the ID of the specified document<sup>[ex]</sup>.
load(documentId)objectReturns the document with the given ID.
Used in patching or ETL scripts.
load(documentId, collectionName)objectReturns the document with the given ID.
Used in JavaScript indexes.
loadPath(document, pathString)objectReturns document(s) based on IDs found within the specified pathString in the given document.
The pathString can be in a simple Foo.Bar form, in which case a single document is returned. A path like Foo.Bars[].Buzz can return an array of documents.
getMetadata(document)objectReturns the metadata of the specified document, including properties like ChangeVector, ID, and LastModified.
lastModified(document)numberReturns the number of milliseconds elapsed since the last modification time (UTC) of the specified document.
include(documentId)TaskUsed in RQL queries to include the document with the specified ID with the results.
put(documentId, document, [optional]changeVectorString)TaskCreates or updates a document with the specified ID.
To generate a new document ID, you can use the "collectionPrefix/Server-Side ID" notation<sup>[ex]</sup>.
This function can also clone an existing document.
Note: attachments & counters will not be included in the clone<sup>[ex]</sup>. Used in patching.
del(documentId)voidDeletes the document with the specified ID.
Used in patching.
archived.archiveAt(document, dateString)voidSchedules the specified document to be archived at the specified dateString.
Used in patching.
archived.unarchive(document)voidUnarchives the specified document.
Used in patching.

Counter operations:

Method SignatureReturn typeDescription
counter(documentId, counterName)numberReturns the value of the specified counter for the given document ID<sup>[ex]</sup>.
counter(document, counterName)numberReturns the value of the specified counter for the given document<sup>[ex]</sup>.
incrementCounter(documentId, counterName, value)voidIncrements the specified counter for the given document ID.
If the counter does not exist, it is implicitly created with the provided value. Counter values can be negative, allowing both increment and decrement operations<sup>[ex]</sup>.
incrementCounter(document, counterName, value)voidIncrements the specified counter for the given document.
If the counter does not exist, it is implicitly created with the provided value. Counter values can be negative, allowing both increment and decrement operations<sup>[ex]</sup>.
deleteCounter(documentId, counterName)voidDelete the specified counter from the given document ID<sup>[ex]</sup>.
deleteCounter(document, counterName)voidDelete the specified counter from the given document<sup>[ex]</sup>.
counterRaw(documentId, counterName)objectReturns a dictionary containing the counter value for each database node. The overall counter value is the sum of all node values.
counterRaw(document, counterName)objectReturns a dictionary containing the counter value for each database node. The overall counter value is the sum of all node values.

Time series operations:

Method SignatureReturn typeDescription
timeseries (doc, name)objectReturns a handle to the specified time series associated with the document, enabling operations such as append, delete, and get.
timeseries.append (timestamp, values)voidAppends a new entry to the time series at the specified timestamp with the provided values.
timeseries.append (timestamp, values, tag)voidAppends a new entry to the time series at the specified timestamp with the provided values and an optional tag.
timeseries.delete (from, to)voidDeletes a range of entries from a time series.
timeseries.get (from, to)object[]Retrieves a range of time series entries.
timeseries.increment(timestamp, values)voidIncrements the values of an incremental time series entry at the specified timestamp.
timeseries.increment(values)voidIncrements the values of an incremental time series entry at the current time.
timeseries.increment(timestamp, value)voidIncrements a single value of an incremental time series entry at the specified timestamp.
timeseries.increment(value)voidIncrements a single value of an incremental time series entry at the current time.

Compare-exchange:

Method SignatureReturn typeDescription
cmpxchg(compareExchangeKey)objectReturns the value stored in a Compare Exchange item for the specified key.

String manipulation:

Method SignatureReturn typeDescription
String.prototype.startsWith(searchString, position)booleanReturns true if the specified string starts with searchString at the given position. position is optional and defaults to 0.
String.prototype.endsWith(searchString, position)booleanReturns true if the specified string end with searchString at the given position. position is optional and defaults to 0.
String.prototype.padStart(targetLength, padString)stringPads the string from the start with padString
(or whitespace by default) until it reaches targetLength.
String.prototype.padEnd(targetLength, padString)stringPads the string from the end with padString
(or whitespace by default) until it reaches targetLength.
String.prototype.format(arg1, arg2, arg3 ...)stringFormats the string by replacing occurrences of {[number]} with the corresponding argument based on a zero-based index.
startsWith(inputString, prefix)booleanReturns true if inputString starts with the specified prefix.
endsWith(inputString, suffix)booleanReturns true if inputString ends with the specified suffix.
regex(inputString, regex)booleanReturns true if inputString matches the specified regex pattern.

Arrays & objects:

Method SignatureReturn typeDescription
Array.prototype.find(function callback)Array's elementReturns the first element in the array for which the callback function returns true.
Object.map(input, function mapFunction, context)ArrayReturns an array containing the results of mapFunction applied to all properties of input (or items, if input is an array). The mapFunction signature is function(itemValue, itemKey).

Mathematical operations:

Method SignatureReturn typeDescription
Raven_Min(num1, num2)numberReturns the smaller of num1 and num2. If both params are of the same type (both numbers or both strings), a standard comparison is performed.
If they are of mixed types (one number and one string), the string is parsed as a double for comparison.
LazyNumberValue params resulting from method scalarToRawString are not supported.
Raven_Max(num1, num2)numberReturns the larger of num1 and num2. If both params are of the same type (both numbers or both strings), a standard comparison is performed.
If they are of mixed types (one number and one string), the string is parsed as a double for comparison.
LazyNumberValue params resulting from method scalarToRawString are not supported.

Conversion operations:

Method SignatureReturn typeDescription
scalarToRawString(document, lambdaToField)Raw field value.
LazyStringValue for strings,
LazyNumberValue for floating point numbers.
Returns the raw representation of a field. Useful for handling numbers that exceed the numeric or accuracy range of double (See Numbers in Jint), or for optimizing memory consumption when projecting large string values.
The returned value is immutable.
convertJsTimeToTimeSpanString(ticksNumber)stringReturns a human-readable TimeSpan representation of the specified ticksNumber.

Generating embeddings:

Method SignatureReturnDescription
embeddings.generate(object)nullThis method is designed to process a JSON object where each key represents a document field, and the value is a text-splitting method to process that field's content.
text.split(text, maxTokensPerChunk)string[]Splits a plain text string into multiple chunks based on the specified maximum token count.
text.splitLines(text, maxTokensPerChunk)string[]Splits a plain text string into individual lines based on line breaks and whitespace while ensuring that each line does not exceed the specified maximum token limit.
text.splitParagraphs(lines, maxTokensPerChunk)string[]Combines consecutive lines to form paragraphs while ensuring each paragraph is as complete as possible without exceeding the specified token limit.
markdown.splitLines(text, maxTokensPerChunk)string[]Splits markdown content into individual lines at line breaks while ensuring that each line remains within the specified token limit.
markdown.splitParagraphs(lines, maxTokensPerChunk)string[]Groups lines into coherent paragraphs at designated paragraph breaks while ensuring each paragraph remains within the specified token limit.
html.strip(htmlText, maxTokensPerChunk)string[]Removes HTML tags from the content and splits the resulting plain text into chunks based on a specified token limit.

Debugging:

Method SignatureReturnDescription
output(message) or console.log(message)voidPrints message to the debug output.
Used for debugging single document patches.