Getting Started with Clojure and XTDB


The fastest way to get started with XTDB is creating a new Luminus app through Leiningen. Just open your terminal and run:

$ lein new luminus xtdb-app +service +xtdb

I recomend you to use Git to version your code. But before init your repo and add all files, add the lines /.clj-kondo and /.lsp to your .gitignore file. It will prevent you from commiting temporary files.

##What is XTDB?

XTDB is a schemaless, non relational immutable database. This means that all data that you put into your database will not change until you evict (this is an operation) the data.

Imagine that you want to store this in your database:

{ "name": "Gustavo Stantos", "age": 27 }

But for any reason, the attribute "name" needs to change. The common way to do that is to change "name" storing the new value. But doing that, you lost the previous value. If, in the future, you need to answer a question like "what is the name value at certain time?". In "normal" databases, you simply can't answer this kind of question. At least if you don't store a transaction log.

XTDB embrace data changes storing all data using the time dimension. You can answer questions that use time as a variable.

##How to store data in the database?

To put data into the database you need to submit a transaction. Every transaction will wait in a queue to be processed. After processing the transaction, XTDB will index the changes then you will be able to query and retrieve the newest "version".

You can submit a new transaction using the submit-tx function, as shown in the example below:

(ns xtdb-app.db.core
    [xtdb.api :as xt]))

(defn- put-user!
  [node user]
  (let [user-doc (assoc user :xt/id (:user/id user)
                             :xtdb-app/type :user)]
      (xt/submit-tx node [[::xt/put user-doc]]))))

To submit a transaction you need a reference to a XTDB node, that is a snapshot of your entire database (yeah, crazy), and a operation. The current verstion allow you to submit five types of transactions:

  • ::xt/put: will insert data to the database
  • ::xt/delete: will delete data from the database (soft delete)
  • ::xt/evict:

📝 Edit this page