Computed field definition

Computed fields are defined in the compute field of the Collection document definition:

A computed field dynamically derives the value of a field using a user-defined anonymous function. These fields are not persisted but derived when the field is read. Computed fields add flexibility to your data model because you can use them to do unit conversions, such as define a field that converts Celsius to Fahrenheit, or embed a join in your collection definition.

The computed field anonymous function is evaluated when a document is read. An optional type can also be provided as part of the function signature.

Computed fields can be indexed to search for documents using a computed value. Be aware that there are constraints on the kind of computed fields you can cover on an index. You can only index computed fields that are pure functions. You can’t index on a computed field that performs a read, for example.

Runtime errors in computed fields that are indexed aren’t reported. field that references another document in the computed function. Computed fields that result in runtime errors, including divide by zero, return null. If indexed, the index entry is null. Using type checking should prevent these kind of indexes from being defined.

See collection.compute for more detailed information.

Computed field definition:

{
    computed_fields: {
      "<fieldName>: {body: "<functionBody>"[, signature: "<type>"]}",
      . . .
    }
}

Property Type Description

fieldName

(required) Compute function name. The fieldName can be the same as a persisted field name. An optional type can be declared for the function.

functionBody

(required) The function body is an anonymous function that is evaluated when a document is read. An optional type can also be provided as part of the function signature.

The anonymous function takes a source Document as input, operates on the document values, and returns a computed value.

Computed fields with defined anonymous functions can transform existing fields, provide convenient access to complex relations, and index over derived data.

The anonymous function return value is the value of the computed field.

Examples

Define computed fields for a collection:

Collection.byName("Customer")!.update({
  computed_fields: {
    double: { body: "doc => doc.x * 2", signature: "Number" }
  }
})
{
  name: "Customer",
  coll: Collection,
  ts: Time("2024-01-27T20:20:53.770Z"),
  constraints: [],
  computed_fields: {
    double: {
      body: "doc => doc.x * 2",
      signature: "Number"
    }
  },
  indexes: {},
  history_days: 0
}

 

Notice that you can define an optional type in the function signature.

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!