Skip to content
المشاريع

حول

SurrealDB SDK for Java

أدوات التطوير

كيف تُقاس هذه الأرقام

ما يمكنك فعله

  • A thread-safe native JAVA client for SurrealDB.
  • Simple API: see docs.
  • Support of 'memory' (embedded SurrealDB).
  • Support of remote connection to SurrealDB. The 3.x driver is built on SurrealDB 4.0 and works with 4.0.x servers; it is also tested against servers 3.1, 3.2 and 3.3. Stay on the 2.x driver line if you need the SurrealDB 3.x embedded engine or RocksDB.

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
٠
خلال 15 يومًا
٠
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

 

The official SurrealDB SDK for Java


     

     

surrealdb.java

The official SurrealDB SDK for Java.

Documentation

View the SDK documentation here.

Features

  • A thread-safe native JAVA client for SurrealDB.
  • Simple API: see docs.
  • Support of 'memory' (embedded SurrealDB).
  • Support of remote connection to SurrealDB. The 3.x driver is built on SurrealDB 4.0 and works with 4.0.x servers; it is also tested against servers 3.1, 3.2 and 3.3. Stay on the 2.x driver line if you need the SurrealDB 3.x embedded engine or RocksDB.
  • Embedded persistence with surrealkv://. SurrealDB 4.0 has no RocksDB engine: rocksdb:// is a deprecated alias of surrealkv:// that creates a SurrealKV store on a new directory. Databases written by driver 2.x do not open; see Migrating an embedded database from driver 2.x.
  • Mutable POJOs (Java 8+) and immutable record classes (JDK 16+) for create / select.
  • All geometry types (Point, LineString, Polygon, their multi-variants, and GeometryCollection) for reading and writing.
  • Sized number kinds (i8 ... u64, f16, f32) for reading and writing against SurrealDB 4.0.
  • Date, time, timestamp and interval kinds (LocalDate, LocalTime, LocalDateTime, Interval) for reading and writing against SurrealDB 4.0.
  • Live queries: subscribe to table changes with selectLive and terminate them by id with kill.
  • Supported on JAVA JDK 8, 11, 17, 21, 25.
  • Supported architectures:
    • Linux (ARM) aarch64
    • Linux (INTEL) x86_64
    • Windows (INTEL) x86_64
    • MacOS (ARM) aarch64
    • MacOS (INTEL) x86_64
    • Android (Linux ARM) aarch64
    • Android (Linux INTEL) x86_64
  • Zero dependencies

Minimum requirements

  • Java 8

How to install

Stable release

Released to Maven Central.

Gradle:

ext {
    surrealdbVersion = "3.0.0"
}

dependencies {
    implementation "com.surrealdb:surrealdb:${surrealdbVersion}"
}

Maven:

<dependency>
    <groupId>com.surrealdb</groupId>
    <artifactId>surrealdb</artifactId>
    <version>3.0.0</version>
</dependency>

Snapshot release

Snapshots of the next version are published to the Maven Central snapshots repository on every push to main while build.gradle has a -SNAPSHOT version. Use them to try out unreleased changes; replace X.Y.Z-SNAPSHOT below with that version. 3.0.0 is a regular release, so use the stable release above for it.

Gradle:

repositories {
    mavenCentral()
    maven {
        url = uri("https://central.sonatype.com/repository/maven-snapshots/")
        mavenContent { snapshotsOnly() }
    }
}

ext {
    surrealdbVersion = "X.Y.Z-SNAPSHOT"
}

dependencies {
    implementation "com.surrealdb:surrealdb:${surrealdbVersion}"
}

Maven:

<repositories>
    <repository>
        <id>central-snapshots</id>
        <url>https://central.sonatype.com/repository/maven-snapshots/</url>
        <releases><enabled>false</enabled></releases>
        <snapshots><enabled>true</enabled></snapshots>
    </repository>
</repositories>

<dependency>
    <groupId>com.surrealdb</groupId>
    <artifactId>surrealdb</artifactId>
    <version>X.Y.Z-SNAPSHOT</version>
</dependency>

Getting started

package org.example;

import com.surrealdb.Surreal;
import com.surrealdb.RecordId;

import java.util.Iterator;

public class Example {
    public static void main(String[] args) {
        try (final Surreal driver = new Surreal()) {
            // Connect to the instance
            driver.connect("memory");
            // namespace & database
            driver.useNs("test").useDb("test");
            // Create a person
            Person person = new Person("Founder & CEO", "Tobie", "Morgan Hitchcock", true);
            // Insert a record
            List<Person> tobie = driver.create(Person.class, "person", person);
            // Read records
            Iterator<Person> people = driver.select(Person.class, "person");
            // Print them out
            System.out.println("Tobie = " + tobie);
            System.out.println("people = " + people.next());
        }
    }

    static class Person {
        RecordId id;
        String title;
        String firstName;
        String lastName;
        boolean marketing;

        //  A default constructor is required
        public Person() {
        }

        public Person(String title, String firstName, String lastName, boolean marketing) {
            this.title = title;
            this.firstName = firstName;
            this.lastName = lastName;
            this.marketing = marketing;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "id='" + id + '\'' +
                    ", title='" + title + '\'' +
                    ", firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    ", marketing=" + marketing +
                    '}';
        }
    }
}

Geometry

All GeoJSON-style geometry types are supported — Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection — for both reading and writing. Coordinates use java.awt.geom.Point2D.Double, where x is the longitude and y is the latitude.

import com.surrealdb.Geometry;
import com.surrealdb.Surreal;
import com.surrealdb.Value;

import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

try (final Surreal driver = new Surreal()) {
    driver.connect("memory").useNs("test").useDb("test");

    // Build a geometry in Java and store it via a bound parameter
    Geometry route = Geometry.lineString(Arrays.asList(
            new Point2D.Double(-0.118, 51.51),
            new Point2D.Double(-0.121, 51.50)));
    Map<String, Object> params = new HashMap<>();
    params.put("route", route);
    driver.query("UPSERT path:1 SET route = $route", params);

    // Read it back
    Value value = driver.query("SELECT VALUE route FROM path:1").take(0).getArray().get(0);
    Geometry geom = value.getGeometry();
    System.out.println(geom.getType());        // LineString
    System.out.println(geom.getLineString());  // [Point2D.Double[...], Point2D.Double[...]]
}

Migrating an embedded database from driver 2.x

A surrealkv:// or rocksdb:// directory written by driver 2.x cannot be opened by driver 3.0: connect throws an InternalException and leaves the directory unchanged. The error suggests the environment variable SURREAL_EXPERIMENTAL_UPGRADE_FROM_3X, which has no effect in the embedded SDK. Export the data with driver 2.2.0 and import it with 3.0 instead:

// With driver 2.2.0
try (final Surreal old = new Surreal()) {
    old.connect("surrealkv:///data/old").useNs("test").useDb("test");
    old.exportSql("/data/backup.surql");
}

// With driver 3.0, into a new directory
try (final Surreal db = new Surreal()) {
    db.connect("surrealkv:///data/new").useNs("test").useDb("test");
    db.importSql("/data/backup.surql");
}

Export and import work on one namespace and database at a time, so repeat the steps for each one. The same steps work for a 2.x rocksdb:// directory (open it with rocksdb:// in driver 2.2.0); in driver 3.0, rocksdb:// is only a deprecated alias of surrealkv://.

Sized numbers (SurrealDB 4.0)

SurrealDB 4.0 adds the sized number kinds i8, u8, i16, u16, i32, u32, u64, f16 and f32 next to int (i64), float (f64) and decimal.

Reading: isLong()/getLong() work for every integer kind whose value fits a long, and isDouble()/getDouble() work for every floating-point kind. A u64 above Long.MAX_VALUE is never reported as a long (it would wrap); use isBigInteger()/getBigInteger(). getNumberType() returns the exact kind as a NumberType.

Pick the Java type of a POJO field by the range of the kind: u8 fits a short or int, u16 an int, u32 a long, and u64 a long (up to Long.MAX_VALUE) or a BigInteger. A value that does not fit the field throws a SurrealException that names the value and the field type, instead of wrapping into a wrong number.

Writing: Java byte, short, int, long, float and double still map to int and float, so existing schemas and 3.x servers behave as before. Opt in to a sized kind explicitly with ValueMut.createI8, createU8, createI16, createU16, createI32, createU32, createU64, createF16 and createF32.

Decimals: a Java BigDecimal (and a BigInteger beyond 63 bits) is written as a decimal, as in driver 2.x: a 96-bit mantissa and a scale of at most 28, with the digits beyond that rounded and a larger value rejected with a SurrealException. To keep a value that does not fit, write the SurrealDB 4.0 arbitrary-precision kind explicitly with ValueMut.createBigDecimalKind (up to 147455 digits; a TYPE decimal field does not accept it, and a 3.x server has no such kind).

Results keep their kind on the embedded engine and over a remote connection to a 4.0 server. Values you send are different: the embedded engine keeps the kind of a bound ValueMut, but over a remote connection the SDK writes its requests in plain CBOR, which has no form for the sized kinds, so it sends them widened (sized integers as int, floats as float, a u64 above Long.MAX_VALUE as a decimal). Over the network a TYPE u8 (etc.) schema field is what makes the stored kind sized.

try (final Surreal driver = new Surreal()) {
    driver.connect("memory").useNs("test").useDb("test");

    Map<String, Object> params = new HashMap<>();
    params.put("small", ValueMut.createU8(200));
    params.put("big", ValueMut.createU64(new BigInteger("18446744073709551615")));
    driver.query("CREATE sample:1 SET small = $small, big = $big", params);

    Value row = driver.query("SELECT * FROM sample:1").take(0).getArray().get(0);
    Value big = row.getObject().get("big");
    System.out.println(big.getNumberType());  // U64
    System.out.println(big.isLong());         // false
    System.out.println(big.getBigInteger());  // 18446744073709551615
}

Date and time types (SurrealDB 4.0)

SurrealDB 4.0 adds four temporal kinds next to datetime and duration: date (a calendar day), time (a time of day), timestamp (a date and time without a zone) and interval (months, days and microseconds).

SurrealDB Read with Java type
date isDate() / getDate() java.time.LocalDate
time isTime() / getTime() java.time.LocalTime
timestamp isTimestamp() / getTimestamp() java.time.LocalDateTime
interval isInterval() / getInterval() com.surrealdb.Interval

An Interval keeps its months, days and micros apart, because a month or a day has no fixed length. Its toPeriod() returns the months and days and toDuration() the microseconds. The same conversions work for POJO fields and for untyped maps and lists, and an interval also fills a java.time.Period field when it has no time part (otherwise a SurrealException is thrown). The Period field is normalised, so Period.of(1, 2, 3) round-trips equal, but an interval of P14M3D reads back as P1Y2M3D. A datetime still fills a LocalDateTime field, read as UTC, and a timestamp fills an Instant, ZonedDateTime, OffsetDateTime, java.util.Date or java.sql field the same way. A time also fills a Duration field, as the time since midnight.

Writing: LocalDate is written as a date, LocalTime as a time, Interval as an interval and Period as an interval of its months (a year counts as twelve) and days. A LocalDateTime keeps being written as a datetime (interpreted as UTC); to write a timestamp, use ValueMut.createTimestamp. The factories are ValueMut.createDate, createTime, createTimestamp and createInterval; a date or timestamp outside the range SurrealDB supports (about the years -262143 to 262142, where the first and last day or instant stand for -infinity and infinity) throws an IllegalArgumentException.

Limits: SurrealDB allows the time 24:00:00, which LocalTime cannot hold, so getTime() throws a SurrealException for it (the text form still reads it). Interval compares its parts as they are, so 1 month and 30 days are different intervals here, although SurrealDB compares them as equal.

Results keep their kind on the embedded engine and over a remote connection to a 4.0 server. Values you send are different: the embedded engine keeps the kind of a bound value, but over a remote connection the SDK sends a bound date and timestamp as a datetime, a time as a duration and an interval as its ISO 8601 string (plain CBOR has no form for the new kinds). In the query, <date> $d, <timestamp> $ts and <interval> $i restore the kind, and a TYPE date or TYPE timestamp field accepts the datetime. A time cannot be cast back from a duration: bind its text ("12:34:56") and cast that with <time> $t, which is also how a TYPE time schema field gets a time over a remote connection.

Typed POJO and record fields read those widened forms back, so a remote create() or select() of a POJO round-trips without a schema. A LocalDate field accepts a datetime that is exactly midnight UTC, a LocalTime field a duration of at least 0 and less than 24 hours, an Interval or Period field the ISO 8601 string (Interval.parse reads it and is the inverse of Interval.toString), a BigDecimal or BigInteger field a numeric string (a bound bigdecimal arrives as one), and a LocalDateTime field the datetime a timestamp is sent as (read as UTC). Anything else throws a SurrealException: a datetime with a time part into a LocalDate, a duration of 24 hours or more into a LocalTime, a malformed interval or number. Untyped reads (a Map<String, Object> or List<Object>) are not guessed: they return the datetime, duration or string as it is.

try (final Surreal driver = new Surreal()) {
    driver.connect("memory").useNs("test").useDb("test");

    Map<String, Object> params = new HashMap<>();
    params.put("day", LocalDate.of(2026, 12, 3));
    params.put("at", LocalTime.of(9, 30));
    params.put("every", new Interval(1, 0, 0)); // one month
    params.put("seen", ValueMut.createTimestamp(LocalDateTime.of(2026, 12, 3, 9, 30)));
    driver.query("CREATE event:1 SET day = $day, at = $at, every = $every, seen = $seen", params);

    Value row = driver.query("SELECT * FROM event:1").take(0).getArray().get(0);
    System.out.println(row.getObject().get("day").getDate());          // 2026-12-03
    System.out.println(row.getObject().get("at").getTime());           // 09:30
    System.out.println(row.getObject().get("every").getInterval());    // P1M
    System.out.println(row.getObject().get("seen").getTimestamp());    // 2026-12-03T09:30
}

Reports

Developing

On Linux/Mac:

cargo build
./gradlew -i test

On Windows:

cargo build
./gradlew.bat -i test

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…