How to perform CRUD operations in Fauna

Fauna allows you to store documents and query them in a relational fashion. This section walks you through a basic example of creating, retrieving, updating, and deleting (CRUD) documents in Fauna, including working with collections. If you are new to Fauna, make sure to check out our Glossary for definitions.

Introduction

To demonstrate how to perform CRUD operations in Fauna, we are going to use the example of blog posts: creating blog posts, updating them with additional attributes, and querying for specific posts.

The steps are:

We have set up this example so you can follow along from start to finish. Feel free to skip straight to Create a post if you are just looking for examples of the create, retrieve, update, and delete process.

Requirements

This section walks you through setting up your environment, installing a driver, importing the driver, obtaining an admin key, and instantiating the client.

Supported runtimes

Before you install the driver, it’s important to ensure you’re running a compatible version of the language runtime and have satisfied other dependencies.

Install the driver

Import the driver

Obtain an admin key

To follow along, you need an admin key, which you can create using the Fauna Dashboard.

Instantiate an admin client

Create a database

Create a database called my_app in Fauna:

Copied!
({ name: 'my_app' })
{
  ref: ("my_app"),
  ts: 1624310594390000,
  name: 'my_app',
  global_id: 'yoat8d8erydyy'
}
Query metrics:
  •    bytesIn:   48

  •   bytesOut:  152

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:   19

  • writeBytes:  470

  •  queryTime: 45ms

  •    retries:    0

Create a server key to access the my_app database

Create a server key. The server key has unrestricted access to a single database; in this case, the server key allows access only to the my_app database that we just created.

Copied!
({
  database: ('my_app'),
  role: 'server',
})
{
  ref: ((), "302044146566169088"),
  ts: 1624310595010000,
  database: ("my_app"),
  role: 'server',
  secret: 'fnAEMRONDpACAMrMtkE9PJk2CjjqPBk71xnFs44W',
  hashed_secret: '$2a$05$8J9xjhMmc3LJSrS5bng95u1WSC2vYeuDRanwGOe1v5uqcAxaIYm4W'
}
Query metrics:
  •    bytesIn:   76

  •   bytesOut:  339

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:  151

  • writeBytes:  487

  •  queryTime: 41ms

  •    retries:    0

Save this key’s secret; it is only displayed once, and if you lose it, you would have to generate a new one. The key is used to perform all of the remaining database setup steps.

Your key will be different than the key you see displayed in the command output in this documentation. The key you saved just above will be different.

Instantiate a client that has server key privileges

Instantiate a client that uses the server key that we just set up, to perform the rest of the tasks in this tutorial. Be sure to copy the secret returned in the previous step and replace YOUR_FAUNADB_SERVER_SECRET with that value.

Create a collection

Fauna stores documents in the form of nested containers. A database contains collections, and collections contain documents. Each document belongs to a specific collection. So in order to create a document for a post, we need to first create a collection for posts.

Create a collection using the CreateCollection function with a param_object containing the name of the collection. We shall name our collection "Posts":

Copied!
({ name: 'Posts' })
{
  ref: ("Posts"),
  ts: 1624310595640000,
  history_days: 30,
  name: 'Posts'
}
Query metrics:
  •    bytesIn:   49

  •   bytesOut:  142

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:  804

  • writeBytes:  325

  •  queryTime: 29ms

  •    retries:    0

Create an index

Before we create any document, let’s ensure that we can easily access them. We do this by creating an index using the CreateIndex function. We create this index now to help make the examples clear; in production, you can create an index at any time.

The customary way to access documents within a collection is by specifying a criteria for one of the fields. To enable criteria-based searches, we need to first create an index using the path of the field within the document.

Create an index on the post’s title:

Copied!
({
  name: 'posts_by_title',
  source: ('Posts'),
  terms: [{ field: ['data', 'title'] }],
})
{
  ref: ("posts_by_title"),
  ts: 1624310596280000,
  active: true,
  serialized: true,
  name: 'posts_by_title',
  source: ("Posts"),
  terms: [ { field: [ 'data', 'title' ] } ],
  partitions: 1
}
Query metrics:
  •    bytesIn:   133

  •   bytesOut:   298

  • computeOps:     1

  •    readOps:     0

  •   writeOps:     1

  •  readBytes: 1,233

  • writeBytes:   424

  •  queryTime:  63ms

  •    retries:     0

It is also possible to specify the values of the document that should be returned when querying the index. We also create an index for a post’s tags:

Copied!
({
  name: 'posts_by_tags_with_title',
  source: ('Posts'),
  terms: [{ field: ['data', 'tags'] }],
  values: [{ field: ['data', 'title'] }],
})
{
  ref: ("posts_by_tags_with_title"),
  ts: 1624310596920000,
  active: true,
  serialized: true,
  name: 'posts_by_tags_with_title',
  source: ("Posts"),
  terms: [ { field: [ 'data', 'tags' ] } ],
  values: [ { field: [ 'data', 'title' ] } ],
  partitions: 1
}
Query metrics:
  •    bytesIn:   191

  •   bytesOut:   355

  • computeOps:     1

  •    readOps:     0

  •   writeOps:     1

  •  readBytes: 1,297

  • writeBytes:   483

  •  queryTime:  68ms

  •    retries:     0

Create a post

Posts are created by calling the Create function with the ref of the posts collection and a param_object that specifies the structure of the document to be created, as well as permissions for the document. The post’s data is included in the param_object's data field.

Copied!
(
  ('Posts'),
  { data: { title: 'What I had for breakfast ..' } },
)
{
  ref: (("Posts"), "302044149229552128"),
  ts: 1624310597570000,
  data: { title: 'What I had for breakfast ..' }
}
Query metrics:
  •    bytesIn:  113

  •   bytesOut:  206

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:    0

  • writeBytes:  402

  •  queryTime: 38ms

  •    retries:    0

The Create function returns the post document just created. As you can see in the output, the ref of the document is an automatically-generated identifier that is unique to the document within its database.

Using the Ref function, you can specify a document ID to use instead of the auto-generated number, but it must be a unique string-encoded 64-bit integer. For example:

Copied!
(
  (('Posts'), '1'),
  { data: { title: 'The first post' } },
)
{
  ref: (("Posts"), "1"),
  ts: 1624310598180000,
  data: { title: 'The first post' }
}
Query metrics:
  •    bytesIn:  117

  •   bytesOut:  176

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:   14

  • writeBytes:  352

  •  queryTime: 23ms

  •    retries:    0

Create several posts

It can quickly become tedious to repeat the Create function for multiple posts.

This is where Fauna’s transaction language really shines. Let’s use a Map function to create several posts at once:

Copied!
(
  [
    'My cat and other marvels',
    'Pondering during a commute',
    'Deep meanings in a latte',
  ],
  (
    'post_title',
    (
      ('Posts'),
      { data: { title: ('post_title') } },
    )
  ),
)
[
  {
    ref: (("Posts"), "302044150538174976"),
    ts: 1624310598800000,
    data: { title: 'My cat and other marvels' }
  },
  {
    ref: (("Posts"), "302044150538176000"),
    ts: 1624310598800000,
    data: { title: 'Pondering during a commute' }
  },
  {
    ref: (("Posts"), "302044150538177024"),
    ts: 1624310598800000,
    data: { title: 'Deep meanings in a latte' }
  }
]
Query metrics:
  •    bytesIn:   241

  •   bytesOut:   589

  • computeOps:     1

  •    readOps:     0

  •   writeOps:     3

  •  readBytes:     0

  • writeBytes: 1,185

  •  queryTime:  35ms

  •    retries:     0

Using the Map function, we can restructure the data as an array and wrap the Create in a lambda function, which then runs over each document in the collection. The anonymous lambda function specifies a variable post_title which is used as a placeholder in the parameters sent to the create function. This way, multiple documents in a collection can be created using a single query.

Retrieve posts

The easiest way to retrieve a document is by using its reference value:

Copied!
((('Posts'), '1'))
{
  ref: (("Posts"), "1"),
  ts: 1624310598180000,
  data: { title: 'The first post' }
}
Query metrics:
  •    bytesIn:   47

  •   bytesOut:  176

  • computeOps:    1

  •    readOps:    1

  •   writeOps:    0

  •  readBytes:   70

  • writeBytes:    0

  •  queryTime: 10ms

  •    retries:    0

You can query for posts with a specific title using the match function and the index we created earlier:

Copied!
(
  (('posts_by_title'), 'My cat and other marvels')
)
{
  ref: (("Posts"), "302044150538174976"),
  ts: 1624310598800000,
  data: { title: 'My cat and other marvels' }
}
Query metrics:
  •    bytesIn:   79

  •   bytesOut:  203

  • computeOps:    1

  •    readOps:    1

  •   writeOps:    0

  •  readBytes:  173

  • writeBytes:    0

  •  queryTime: 12ms

  •    retries:    0

The match function returns a logical set of elements, which can be combined with other sets with set-operations like join, intersect, subtract, etc.

Update posts

You can easily modify documents by supplying the new data along with the reference to the document. For example, we want to add tags to each of our blog posts:

Copied!
(
  (('Posts'), '1'),
  { data: { tags: ['welcome', 'short'] } },
)
{
  ref: (("Posts"), "1"),
  ts: 1624310600630000,
  data: { title: 'The first post', tags: [ 'welcome', 'short' ] }
}
Query metrics:
  •    bytesIn:  119

  •   bytesOut:  203

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:   70

  • writeBytes:  434

  •  queryTime: 29ms

  •    retries:    0

The Update function updates specific fields in a document. It preserves the old fields if they are not specified in params. In the case of nested values (known as objects, due to the JSON data format), the old and the new values are merged. If null is specified as a value for a field, it is removed.

Replace posts

The Replace function replaces the document’s data with the fields provided in params. Old fields not mentioned in params are removed.

Copied!
(
  (('Posts'), '1'),
  { data: { title: 'The replacement first post' } },
)
{
  ref: (("Posts"), "1"),
  ts: 1624310601250000,
  data: { title: 'The replacement first post' }
}
Query metrics:
  •    bytesIn:  130

  •   bytesOut:  188

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:  170

  • writeBytes:  780

  •  queryTime: 52ms

  •    retries:    0

Note that the title has been updated, but tags has been deleted.

Delete a post

Lastly, a post can be removed using the Delete function:

Copied!
((('Posts'), '1'))
{
  ref: (("Posts"), "1"),
  ts: 1624310601250000,
  data: { title: 'The replacement first post' }
}
Query metrics:
  •    bytesIn:   50

  •   bytesOut:  188

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:  298

  • writeBytes:  403

  •  queryTime: 24ms

  •    retries:    0

Once the post is deleted, attempting to retrieve the post results in an error:

Copied!
((("Posts"), "1"))
{
  errors: [
    {
      position: [],
      code: 'instance not found',
      description: 'Document not found.'
    }
  ]
}
Query metrics:
  •    bytesIn:   47

  •   bytesOut:   92

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    0

  •  readBytes:    0

  • writeBytes:    0

  •  queryTime: 10ms

  •    retries:    0

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!