### Datahike Setup for Temporal Examples Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/time-variance This setup includes a simple schema for person data and initializes a temporal database connection. It defines a basic query for name and age. ```clojure (require '[datahike.api :as d]) ;; Simple schema for person data (def schema [{:db/ident :name :db/valueType :db.type/string :db/unique :db.unique/identity :db/index true :db/cardinality :db.cardinality/one} {:db/ident :age :db/valueType :db.type/long :db/cardinality :db.cardinality/one}]) (def cfg {:store {:backend :memory :id #uuid "550e8400-e29b-41d4-a716-446655440001"} :initial-tx schema}) (d/create-database cfg) (def conn (d/connect cfg)) ;; Query to find names and ages (def query '[:find ?n ?a :where [?e :name ?n] [?e :age ?a]]) ``` -------------------------------- ### Create In-Memory Datahike Database with Defaults Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/getting-started/configuration Quick start example to create an in-memory Datahike database using sensible defaults. Requires importing the datahike.api namespace. ```clojure (require '[datahike.api :as d]) (d/create-database) ``` -------------------------------- ### Keyword Syntax and Configuration Examples Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/javascript-api Illustrates the universal EDN conversion rules for keyword syntax in schema definition, data insertion, and configuration. Also shows examples of in-memory and file backend configurations. ```APIDOC ## Keyword Syntax The universal EDN conversion rules make keyword syntax simple and predictable: **Simple rule: Keys never need `:` , values that should be keywords need `:`** ```javascript // ✅ Schema definition const schema = [{ 'db/ident': ':name', // Key auto-keywordized, value is keyword 'db/valueType': ':db.type/string', // Both become keywords 'db/cardinality': ':db.cardinality/one' }]; // ✅ Data insertion const data = [ { name: 'Alice', age: 30 } // Keys auto-keywordized, values are literals ]; // ✅ Configuration const config = { store: { backend: ':memory', // ":memory" becomes :memory keyword id: 'test' }, 'schema-flexibility': ':read', // ":read" becomes :read keyword 'keep-history?': true // boolean passes through }; // ✅ Pull patterns (array of keyword strings) const pattern = [':name', ':age']; // Strings with : become keywords // ✅ Literal colon strings (rare) const data = [{ description: '\:starts-with-colon' // Escaped → ":starts-with-colon" (string) }]; ``` ### Backend Configuration ```javascript const crypto = require('crypto'); // In-memory backend (requires UUID) const memConfig = { store: { backend: ':memory', id: crypto.randomUUID() } }; // File backend (Node.js only) const fileConfig = { store: { backend: ':file', path: '/path/to/db' } }; ``` ``` -------------------------------- ### Complete Datahike Configuration Example Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/getting-started/configuration A comprehensive example demonstrating various configuration options for a Datahike database, including storage, schema flexibility, history, caching, and writer settings. ```clojure { :store {:backend :file :path "/var/datahike/production" :id #uuid "550e8400-e29b-41d4-a716-446655440000"} :name "production-db" :schema-flexibility :write :keep-history? true :attribute-refs? false :index :datahike.index/persistent-set :store-cache-size 10000 :search-cache-size 100000 :initial-tx [{:db/ident :user/email :db/valueType :db.type/string :db/unique :db.unique/identity :db/cardinality :db.cardinality/one}] :writer {:backend :datahike-server :url "http://writer.example.com:4444" :token "secure-token"} :branch :db} ``` -------------------------------- ### Start Benchmarks Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/reference/contributing Initiates the benchmark suite for Datahike. ```bash bb bench copy ``` -------------------------------- ### Backend Configuration Examples Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/javascript-api Provides examples for configuring the in-memory and file backends for Datahike. The in-memory backend requires a UUID, while the file backend specifies a path. ```javascript const crypto = require('crypto'); const memConfig = { store: { backend: ":memory", id: crypto.randomUUID() } }; const fileConfig = { store: { backend: ":file", path: '/path/to/db' } }; ``` -------------------------------- ### Example Database Configuration Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture This is an example of a resulting JSON configuration object for a Datahike database. ```json cfg = { "keep-history?": true, "search-cache-size": 10000, "index": [ "!kw", "datahike.index/persistent-set" ], "store": { "id": "wiggly-field-vole", "backend": [ "!kw", "memory" ] }, "store-cache-size": 1000, "attribute-refs?": false, "writer": { "backend": [ "!kw", "self" ] }, "crypto-hash?": false, "remote-peer": null, "schema-flexibility": [ "!kw", "read" ], "branch": [ "!kw", "db" ] } ``` -------------------------------- ### JavaScript API Installation Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/clojurescript-support Install the Datahike library for JavaScript/TypeScript applications using npm. ```bash npm install datahike@next ``` -------------------------------- ### TypeScript Setup and Usage Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/javascript-api Demonstrates how to set up and use Datahike with TypeScript, including importing the library, defining interfaces for configuration, and performing basic database operations with type checking. ```typescript import * as d from 'datahike'; interface Config { store: { backend: string; id?: string; path?: string; }; 'keep-history'?: boolean; 'schema-flexibility'?: string; } const config: Config = { store: { backend: ':memory', id: 'example' } }; async function example() { await d.createDatabase(config); const conn = await d.connect(config); const db = d.db(conn); // TypeScript will check types automatically } ``` -------------------------------- ### Example Norm File Organization Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/norms-database-migrations- Illustrates the recommended file organization for norms, using numeric prefixes for lexicographical ordering of migration files. ```clojure resources/migrations/ 001-initial-schema.edn 002-add-users.edn 003-data-migration.edn checksums.edn ``` -------------------------------- ### Setup Database and Define Schema Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/advanced/entity-specs Initializes a Datahike database with a specified schema and configuration, including memory storage and schema flexibility. ```clojure (require '[datahike.api :as d]) ;; setup database with schema and connection (def schema [{:db/ident :account/email :db/valueType :db.type/string :db/unique :db.unique/identity :db/cardinality :db.cardinality/one} {:db/ident :account/holder :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :account/balance :db/valueType :db.type/long :db/cardinality :db.cardinality/one}]) (def cfg {:store {:backend :memory :id #uuid "550e8400-e29b-41d4-a716-446655440000"} :schema-flexibility :write :keep-history? true :initial-tx schema}) (d/delete-database cfg) (d/create-database cfg) (def conn (d/connect cfg)) ``` -------------------------------- ### Datahike Browser Client Example Usage Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture Demonstrates creating a database, connecting, transacting schema and data, querying locally, and cleaning up. The TieredStore combines memory and IndexedDB, and the KabelWriter sends transactions to the server. ```clojure (defn example [] ;; go-try/ #{["Alice"] ["Bob"]} ;; Clean up (d/release conn) ( [['Alice']] ``` -------------------------------- ### Install Datahike JavaScript Package Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/readme Install the Datahike JavaScript package using npm. This is a beta version. ```bash npm install datahike@next ``` -------------------------------- ### Node.js File Backend Setup Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/clojurescript-support Use this for Node.js environments with file storage. Requires datahike.nodejs to register the :file backend. Operations return channels. ```clojure (ns my-app.core (:require [datahike.api :as d] [datahike.nodejs] ;; Registers :file backend [cljs.core.async :refer [ 2, as :db got merged from :foo and :db ;; check that the commit stored is the same db as conn (= (commit-as-db store (commit-id @conn)) (branch-as-db store :db) @conn) ;; => true (count ( 4 commits now on both branches (force-branch! @conn :foo2 #{:foo}) ;; put whatever DB value you have created in memory (delete-branch! conn :foo)) ``` -------------------------------- ### Create and Test Schema Migration Branch Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/versioning-beta- This example demonstrates creating a new branch for testing schema migrations, applying changes to the test branch, and then merging successful migrations back to the production branch. ```clojure (require '[datahike.api :as d] '[datahike.versioning :refer [branch! merge! delete-branch!]]) (let [cfg {:store {:backend :file :path "/var/db/production"} :keep-history? true :schema-flexibility :write} conn (d/connect cfg)] ;; Create migration test branch (branch! conn :db :migration-test) (let [test-conn (d/connect (assoc cfg :branch :migration-test))] ;; Try new schema (d/transact test-conn [{:db/ident :email :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/unique :db.unique/identity}]) ;; Test with sample data (d/transact test-conn [{:email "test@example.com"}]) ;; Verify migration worked, then merge to production (when (verify-migration test-conn) (merge! conn #{:migration-test} (migration-tx-data test-conn)) (delete-branch! conn :migration-test)))) ``` -------------------------------- ### JavaScript API Example Usage Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/readme Example of using the Datahike JavaScript API to create a database, connect, transact data, and query. Requires Node.js. ```javascript const d = require('datahike'); const crypto = require('crypto'); const config = { store: { backend: ':memory', id: crypto.randomUUID() }, 'schema-flexibility': ':read' }; await d.createDatabase(config); const conn = await d.connect(config); await d.transact(conn, [{ name: 'Alice' }]); const db = await d.db(conn); const results = await d.q('[:find ?n :where [?e :name ?n]]', db); console.log(results); // => [['Alice']] ``` -------------------------------- ### TypeScript Support Example Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/javascript-api Provides an example of how to use the Datahike JavaScript API with TypeScript, including interface definitions and basic asynchronous database operations. ```APIDOC ## TypeScript Support Full TypeScript definitions are automatically generated and included: ```typescript import * as d from 'datahike'; interface Config { store: { backend: string; id?: string; path?: string; }; 'keep-history'?: boolean; 'schema-flexibility'?: string; } const config: Config = { store: { backend: ':memory', id: 'example' } }; async function example() { await d.createDatabase(config); const conn = await d.connect(config); const db = d.db(conn); // TypeScript will check types automatically } ``` ``` -------------------------------- ### Datahike Server Setup with Kabel Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture Sets up a Datahike server using Kabel for WebSocket communication. Includes Fressian middleware for Datahike types and konserve-sync for replication. Use this for enabling real-time updates to connected clients. ```clojure (ns my-app.server (:require [datahike.api :as d] [datahike.kabel.handlers :as handlers] [datahike.kabel.fressian-handlers :as fh] [kabel.peer :as peer] [kabel.http-kit :refer [create-http-kit-handler!]] [konserve-sync.core :as sync] [is.simm.distributed-scope :refer [remote-middleware invoke-on-peer]] [superv.async :refer [S go-try #{["Alice" 25]} ;; update the entity (d/transact conn {:tx-data [{:db/id [:name "Alice"] :age 30}]}) ;; let's compare the current and the as-of value: (d/q query @conn) ;; => #{["Alice" 30]} (d/q query (d/as-of @conn first-date)) ;; => #{["Alice" 25]} ``` -------------------------------- ### Running Experiments with Datahike Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/versioning-beta- This example shows how to use branches for running experiments, such as testing new recommendation algorithms, without impacting live data. Set `keep-history?` to `false` if history is not needed for experiments. ```clojure ;; Test different recommendation algorithms without affecting live data (let [cfg {:store {:backend :file :path "/var/db/recommendations"} :keep-history? false} ;; Don't need history for experiments conn (d/connect cfg)] ;; Create experimental branch (branch! conn :db :experiment-new-algo) (let [exp-conn (d/connect (assoc cfg :branch :experiment-new-algo))] ;; Load experimental algorithm results (d/transact exp-conn experimental-recommendations) ;; Analyze results (let [metrics (analyze-recommendations @exp-conn)] (if (better-than-baseline? metrics) ;; Good results - merge to production (merge! conn #{:experiment-new-algo} experimental-recommendations) ;; Poor results - just delete the branch (delete-branch! conn :experiment-new-algo))))) ``` -------------------------------- ### Example ExceptionInfo Structure Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/advanced/logging-and-error-handling This demonstrates the structure of an `ExceptionInfo` thrown by `log/raise`. The data map typically includes an `:error` or `:type` key and contextual keys like `:value` or `:attribute`. ```clojure (ex-info "Attribute :foo is not defined in schema" {:attribute :foo :error :schema/missing}) ``` -------------------------------- ### Example Transaction Report Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture The detailed transaction report returned after successfully adding data. ```json [ "!datahike/TxReport", { "db-before": [ "!datahike/DB", { "store-id": [ [ [ "!kw", "memory" ], "wiggly-field-vole" ], [ "!kw", "db" ] ], "commit-id": [ "!uuid", "2c8f71f9-a3c6-4189-ba0c-e183cc29c672" ], "max-eid": 1, "max-tx": 536870913 } ], "db-after": [ "!datahike/DB", { "store-id": [ [ [ "!kw", "memory" ], "wiggly-field-vole" ], [ "!kw", "db" ] ], "commit-id": [ "!uuid", "6ebf8979-cdf0-41f4-b615-30ff81830b0c" ], "max-eid": 2, "max-tx": 536870914 } ], "tx-data": [ [ "!datahike/Datom", [ 536870914, [ "!kw", "db/txInstant" ], [ "!date", "1695952443102" ], 536870914, true ] ], [ "!datahike/Datom", [ 2, [ "!kw", "age" ], 42, 536870914, true ] ], [ "!datahike/Datom", [ 2, [ "!kw", "name" ], "Peter", 536870914, true ] ] ], "tempids": { "db/current-tx": 536870914 }, "tx-meta": { "db/txInstant": [ "!date", "1695952443102" ], "db/commitId": [ "!uuid", "6ebf8979-cdf0-41f4-b615-30ff81830b0c" ] } } ] ``` -------------------------------- ### Run Integration Tests Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/reference/contributing Executes integration tests. Ensure Docker is installed and running before executing this command. ```bash bb test integration copy ``` -------------------------------- ### Create Database with Attribute References Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/getting-started/configuration Example of creating a Datahike database with attribute references enabled and :schema-flexibility set to :write. It then demonstrates adding schema and data using keyword syntax, which is automatically translated. ```clojure ;; Create database with attribute references (def cfg {:store {:backend :memory :id #uuid "550e8400-e29b-41d4-a716-446655440000"} :attribute-refs? true :schema-flexibility :write}) (d/create-database cfg) (def conn (d/connect cfg)) ;; Use normal keyword syntax in transactions and queries (d/transact conn [{:db/ident :name :db/valueType :db.type/string :db/cardinality :db.cardinality/one}]) (d/transact conn [{:name "Alice"}]) ;; Queries use keywords as usual - translation happens automatically (d/q '[:find ?n :where [?e :name ?n]] @conn) ;; => #{["Alice"]} ;; But internally, datoms store integer attribute IDs for performance ``` -------------------------------- ### Query Data in Datahike Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/readme Illustrates how to query the Datahike database using Datalog syntax. This example retrieves entities along with their names and ages. The query is performed on the current state of the database. ```clojure ;; search the data (d/q '[:find ?e ?n ?a :where [?e :name ?n] [?e :age ?a]] @conn) ``` -------------------------------- ### Create and Connect to a Datahike Database Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/readme Demonstrates how to set up a Datahike database using the file system as storage. This includes defining the configuration, creating the database, and establishing a connection. Ensure the path exists and is writable. ```clojure (require '[datahike.api :as d]) ;; use the filesystem as storage medium (def cfg {:store {:backend :file :id #uuid "550e8400-e29b-41d4-a716-446655440000" :path "/tmp/example"}}) ;; create a database at this place, per default configuration we enforce a strict ;; schema and keep all historical data (d/create-database cfg) (def conn (d/connect cfg)) ``` -------------------------------- ### Install Datahike to Local Maven Repository Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/reference/contributing Installs the Datahike artifact to your local Maven repository, making it available for other projects. ```bash bb install copy ``` -------------------------------- ### Create Temporal Database and Add Data Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/time-variance Demonstrates setting up a temporal database with a schema, connecting to it, adding initial data, and performing a basic query. History must be enabled for purge operations. ```clojure (require '[datahike.api :as d]) ;; define simple schema (def schema [{:db/ident :name :db/valueType :db.type/string :db/unique :db.unique/identity :db/index true :db/cardinality :db.cardinality/one} {:db/ident :age :db/valueType :db.type/long :db/cardinality :db.cardinality/one}]) ;; create our temporal database (def cfg {:store {:backend :memory :id #uuid "550e8400-e29b-41d4-a716-446655440007"} :initial-tx schema}) (d/create-database cfg) (def conn (d/connect cfg)) ;; add data (d/transact conn {:tx-data [{:name "Alice" :age 25}]}) ;; define simple query for name and age (def query '[:find ?n ?a :where [?e :name ?n] [?e :age ?a]]) (d/q query @conn) ;; => #{["Alice" 25]} ``` -------------------------------- ### List Available Tasks Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/reference/contributing Run this command to see an overview of all available tasks in the project. ```bash bb tasks copy ``` -------------------------------- ### Custom File Logger Example Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/advanced/logging-and-error-handling A custom log function example that writes log events to a specified file, including timestamp, level, ID, and message. Requires `taoensso.trove` and `java.io.FileWriter`. ```clojure (require '[taoensso.trove :as trove]) (import '[java.io FileWriter]) (let [writer (FileWriter. "/var/log/datahike.log" true)] (trove/set-log-fn! (fn [ns coords level id lazy_] (when (>= (.indexOf [:trace :debug :info :warn :error] level) (.indexOf [:trace :debug :info :warn :error] :info)) (let [{:keys [msg data error]} (force lazy_)] (locking writer (.write writer (str (java.time.Instant/now) " " level " " id " " (or msg data) "\n")) (.flush writer))))))) ``` -------------------------------- ### Example Query Result Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture The result set returned from a database query. ```json ["!set",[["Peter",42]]] ``` -------------------------------- ### Compile Native Library and Test Executable Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/libdatahike-c-c- Build the native library and the C++ test executable using babashka and GraalVM Native Image. ```bash # Compile the native library bb ni-compile ``` ```bash # Compile the C++ test executable ./libdatahike/compile-cpp ``` -------------------------------- ### Example Database State Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture The JSON representation of the current database state. ```json db = [ "!datahike/DB", { "store-id": [ [ [ "!kw", "mem" ], "127.0.1.1", "wiggly-field-vole" ], [ "!kw", "db" ] ], "commit-id": [ "!uuid", "6ebf8979-cdf0-41f4-b615-30ff81830b0c" ], "max-eid": 2, "max-tx": 536870914 } ] ``` -------------------------------- ### Building Your Application Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/libdatahike-c-c- Instructions for compiling and running applications that use libdatahike. ```APIDOC ## Building Your Application When building applications that use libdatahike: ```bash # Compile your C++ code g++ -I./libdatahike/target -L./libdatahike/target -ldatahike -o your_app your_app.cpp # Run with library path LD_LIBRARY_PATH=./libdatahike/target ./your_app # or on MacOS DYLD_LIBRARY_PATH=./libdatahike/target ./your_app ``` ``` -------------------------------- ### Example Connection Result Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture The result of a successful connection to a Datahike database. ```json conn = ["!datahike/Connection",[[["!kw","memory"],"wiggly-field-vole"],["!kw","db"]]] ``` -------------------------------- ### Get Database State Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture Retrieves the current state of the Datahike database. ```APIDOC ## POST /db ### Description Retrieves the current state of the connected Datahike database. ### Method POST ### Endpoint /db ### Parameters #### Request Body - **conn** (array) - Required - The connection object obtained from `/connect`. ### Request Example ```json [ ["!datahike/Connection",[[["!kw","memory"],"wiggly-field-vole"],["!kw","db"]]] ] ``` ### Response #### Success Response (200) - **db** (object) - An object representing the current state of the database. ### Response Example ```json [ "!datahike/DB", { "store-id": [[["!kw", "mem"],"127.0.1.1","wiggly-field-vole"],["!kw", "db"]], "commit-id": "!uuid", "6ebf8979-cdf0-41f4-b615-30ff81830b0c", "max-eid": 2, "max-tx": 536870914 } ] ``` ``` -------------------------------- ### Building Libdatahike Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/platform-support/libdatahike-c-c- Instructions for building the native library and test executable. ```APIDOC ## Building To build the native library and test executable you need GraalVM-JDK installed with `native-compile`, babashka and Clojure. ```bash # Compile the native library bb ni-compile # Compile the C++ test executable ./libdatahike/compile-cpp ``` This will create: * `libdatahike/target/libdatahike.so` - The shared library * `libdatahike/target/test_cpp` - Test executable ``` -------------------------------- ### Connect to Database with JSON Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture Send the configuration object to the '/connect' endpoint to establish a connection. ```json [cfg] ``` -------------------------------- ### Get Database Value from Connection Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/reference/differences-to-datomic This function is a wrapper for Datomic compliance, allowing the database to be de-referenced from the connection. ```clojure (db conn) ``` ```clojure @conn ``` -------------------------------- ### Run Native-Image Test Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/reference/contributing Executes tests specifically for native-image compilation. Ensure `native-image` is installed and available in your PATH. ```bash bb test native-image copy ``` -------------------------------- ### Retrieve Database State with JSON Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/distributed-architecture Use the '/db' endpoint with the connection object to get the current state of the database. ```json [conn] ``` -------------------------------- ### Create and Connect to New Datahike Database Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/getting-started/storage-backends This snippet shows how to create a new Datahike database using a given configuration and then establish a connection to it. This is a prerequisite for importing data. ```clojure (d/create-database new-config) (def dest-conn (d/connect new-config)) ``` -------------------------------- ### Run Datahike Benchmarks Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/advanced/benchmarking Use this command to execute benchmarks. Specify the command as 'run' followed by options and output file paths. ```bash clj -M:benchmark CMD [OPTIONS] [FILEPATHS] ``` -------------------------------- ### Define Homogeneous Variable-Length Tuple Schema Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/getting-started/schema Define a homogeneous variable-length tuple where all elements share the same type. Example shows RGB color values. ```clojure ;; RGB color values (def schema [{:db/ident :color/rgb :db/valueType :db.type/tuple :db/tupleType :db.type/long :db/cardinality :db.cardinality/one}]) (d/transact conn {:tx-data schema}) (d/transact conn {:tx-data [{:color/rgb [255 128 0]}]}) ``` -------------------------------- ### Run Datahike Benchmarks with Options Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/advanced/benchmarking Execute benchmarks with specific options for function, database size, configuration, and output format. The LOG_LEVEL can be set to 'warn' to reduce output. ```bash LOG_LEVEL='warn' clj -M:benchmark run -f :connection -d '[1000]' -c file -t feature -o edn feature.edn ``` ```bash LOG_LEVEL='warn' clj -M:benchmark run -f :transaction -y '[:int]' -x '[10]' -c mem-set -o csv feature.csv ``` ```bash LOG_LEVEL='warn' clj -M:benchmark run -f :query -q :simple-query -i 10 ``` -------------------------------- ### Deprecated URI Scheme Configuration Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/getting-started/configuration Example of the old URI-style configuration format used prior to Datahike version 0.3.0. This format is still supported but deprecated. ```uri "datahike:memory://my-db?temporal-index=true&schema-on-read=true" ``` -------------------------------- ### Configure File Storage Backend Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/getting-started/storage-backends Use the file backend for managing databases with Unix tools like rsync or git. Each index fragment is stored as a file, enabling efficient incremental backups. ```clojure {:store {:backend :file :path "/var/lib/myapp/db"}} ``` -------------------------------- ### Optimal Bulk Import Configuration Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/garbage-collection Configure Datahike for maximum performance during bulk imports when no concurrent readers are expected. This setup prioritizes immediate recycling of addresses. ```clojure ;; Optimal bulk import configuration {:online-gc {:enabled? true :grace-period-ms 0 ;; Recycle immediately (no readers) :max-batch 10000} ;; Large batch (only for delete fallback) :crypto-hash? false ;; Required for recycling :branch :db} ;; Single branch only ;; Example bulk import (let [cfg {:store {:backend :file :path "/data/bulk-import"} :online-gc {:enabled? true :grace-period-ms 0} :crypto-hash? false} conn (d/connect cfg)] ;; Import millions of entities (doseq [batch entity-batches] (d/transact conn batch)) ;; Storage stays bounded - addresses are recycled (d/release conn)) ``` -------------------------------- ### Apply Database Migrations with ensure-norms! Source: https://cljdoc.org/d/org.replikativ/datahike/0.8.1672/doc/core-features/norms-database-migrations- Applies database migrations from a specified file or resource, or defaults to the 'migrations' resource. Ensures migrations are applied in lexicographical order. ```clojure (ensure-norms! conn) (ensure-norms! conn file-or-resource) ```