### Start Dgraph Zero Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSample/README.md Starts the Dgraph zero process. Ensure you are in the 'dgraphdata/zero' directory before running. ```sh cd dgraphdata/zero rm -rf zw; dgraph zero ``` -------------------------------- ### Start Dgraph Alpha Server Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSample/README.md Starts the Dgraph alpha server, connecting to the zero instance. Ports are shifted by 100 from defaults. ```sh cd dgraphdata/data rm -rf p w; dgraph alpha --zero localhost:5080 -o 100 ``` -------------------------------- ### Install OpenSSL Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Installs the openssl tool, which may be required for converting client keys to PKCS#8 format for TLS client verification. ```sh apt install openssl ``` -------------------------------- ### Initialize DgraphClient with Connection String Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Use the DgraphClient.open() method for quick setup using a URI-formatted connection string. Ensure the client is shut down after use to release resources. ```java import io.dgraph.DgraphClient; // Simple connection without authentication DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Connection with ACL authentication DgraphClient authClient = DgraphClient.open("dgraph://groot:password@localhost:9080"); // Connection with TLS and API key DgraphClient tlsClient = DgraphClient.open( "dgraph://dg.example.com:443?sslmode=verify-ca&apikey=your-api-key" ); // Connection with TLS (skip verification for dev environments) DgraphClient devClient = DgraphClient.open( "dgraph://localhost:9080?sslmode=require" ); // Always close the client when done client.shutdown(); ``` -------------------------------- ### Launch Dgraph Standalone Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/concurrent-modification/README.md Starts a local Dgraph instance using Docker for development and testing. ```sh docker run -it -p 8080:8080 -p 9080:9080 dgraph/standalone:master ``` -------------------------------- ### Initialize Dgraph Schema Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/concurrent-modification/README.md Defines the schema for the concurrent modification example. ```text : int @index(int) . : string @index(exact) . ``` -------------------------------- ### Install Dgraph4j via Gradle Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Add this line to your build.gradle file to include the Dgraph client in your Gradle project. ```groovy compile 'io.dgraph:dgraph4j:25.0.0' ``` -------------------------------- ### Concurrent Modification Logs Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/concurrent-modification/README.md Example output showing thread conflict resolution and retries. ```text 1599628015260 Thread #2 increasing clickCount for uid 0xe, Name: Alice 1599628015260 Thread #1 increasing clickCount for uid 0xe, Name: Alice 1599628015291 Thread #1 succeeded after 0 retries 1599628015297 Thread #2 found a concurrent modification conflict, sleeping for 1 second... 1599628016297 Thread #2 resuming 1599628016310 Thread #2 increasing clickCount for uid 0xe, Name: Alice 1599628016333 Thread #2 succeeded after 1 retries ``` -------------------------------- ### Install Dgraph4j via Maven Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Add this dependency to your pom.xml file to include the Dgraph client in your Maven project. ```xml io.dgraph dgraph4j 25.0.0 ``` -------------------------------- ### DQL Query Example Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md A DQL query to find entities by name, using a variable for the search term. This is the query string itself. ```dql query all($a: string) { all(func: eq(name, $a)) { name } } ``` -------------------------------- ### Perform a JSON Mutation Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Serialize a Java object to JSON, create a `Mutation` object, and run it within a transaction. This example shows how to retrieve UIDs created by the mutation. ```java // Create data Person person = new Person(); person.name = "Alice"; // Serialize it Gson gson = new Gson(); String json = gson.toJson(person); // Run mutation Mutation mu = Mutation.newBuilder() .setSetJson(ByteString.copyFromUtf8(json.toString())) .build(); // mutationResponse stores a Response protocol buffer object Response mutationResponse = txn.mutate(mu); // eg: to get the UIDs created in this mutation System.out.println(mutationResponse.getUidsMap()) ``` -------------------------------- ### Automatic Retry with Default Policy Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use `withRetry` for managed transactions with automatic retries on retryable failures. This example uses the default retry policy (5 retries, 100ms base delay, exponential backoff). ```java Response resp = client.withRetry(txn -> { txn.mutate(mutation); txn.commit(); return txn.query(query); }); ``` -------------------------------- ### Drop All Data and Schema Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Resets the Dgraph instance to a clean state by dropping all data and schema. Useful for examples and testing. ```java dgraphClient.alter(Operation.newBuilder().setDropAll(true).build()); ``` -------------------------------- ### Run sample application Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSampleDeadlineInterceptors/README.md Execute the sample application using Gradle. ```text $ ./gradlew run Loop iteration: 1 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 2 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 3 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 4 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 5 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 6 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 7 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 8 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 9 people found: 1 Alice Sleeping for 1 second Done! Loop iteration: 10 people found: 1 Alice Sleeping for 1 second Done! ``` -------------------------------- ### Run Sample Application Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSampleWithDeadlineAfter/README.md Command to execute the sample application using Gradle. ```bash $ ./gradlew run ``` -------------------------------- ### Initialize DgraphClient with ClientOptions Builder Source: https://context7.com/dgraph-io/dgraph4j/llms.txt The ClientOptions builder allows for granular configuration of TLS, authentication, and authorization headers. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphClient.ClientOptions; // Basic plaintext connection DgraphClient client = ClientOptions.forAddress("localhost", 9080) .withPlaintext() .build(); // Connection with ACL credentials DgraphClient authClient = ClientOptions.forAddress("localhost", 9080) .withPlaintext() .withACLCredentials("groot", "password") .build(); // Connection with TLS and API key DgraphClient secureClient = ClientOptions.forAddress("dg.example.com", 443) .withTLS() .withDgraphApiKey("your-api-key") .build(); // Connection with bearer token DgraphClient tokenClient = ClientOptions.forAddress("dg.example.com", 443) .withTLS() .withBearerToken("your-access-token") .build(); client.shutdown(); ``` -------------------------------- ### Run Gradle Sample Project Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSample/README.md Executes the sample Java application using Gradle. Warning: This will clear all data from your Dgraph instance. ```sh $ ./gradlew run > Task :run people found: 1 Alice BUILD SUCCESSFUL in 1s 2 actionable tasks: 2 executed ``` -------------------------------- ### Format source code with Gradle Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use these commands to check or apply the project's code style formatting. ```bash ./gradlew build ``` ```bash ./gradlew goJF ``` -------------------------------- ### Create Dgraph Data Directories Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSample/README.md Creates the necessary directories for Dgraph zero and Dgraph server data. ```sh mkdir -p dgraphdata/zero dgraphdata/data ``` -------------------------------- ### Publish Artifacts Locally Source: https://github.com/dgraph-io/dgraph4j/blob/main/PUBLISHING.md Execute these commands to publish and release artifacts to the Sonatype staging repository. ```bash ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository ``` -------------------------------- ### Initialize DgraphClient with gRPC Stubs Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Directly configure gRPC channels and stubs for advanced load balancing or custom metadata requirements. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphGrpc; import io.dgraph.DgraphGrpc.DgraphStub; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.Metadata; import io.grpc.stub.MetadataUtils; // Create channel and stub ManagedChannel channel = ManagedChannelBuilder .forAddress("localhost", 9080) .usePlaintext() .build(); DgraphStub stub = DgraphGrpc.newStub(channel); // Create client with single stub DgraphClient client = new DgraphClient(stub); // Create client with multiple stubs for load balancing ManagedChannel channel2 = ManagedChannelBuilder .forAddress("localhost", 9082) .usePlaintext() .build(); DgraphStub stub2 = DgraphGrpc.newStub(channel2); DgraphClient haClient = new DgraphClient(stub, stub2); // Add custom metadata headers Metadata metadata = new Metadata(); metadata.put( Metadata.Key.of("auth-token", Metadata.ASCII_STRING_MARSHALLER), "your-auth-token" ); DgraphStub stubWithHeaders = MetadataUtils.attachHeaders(stub, metadata); DgraphClient clientWithHeaders = new DgraphClient(stubWithHeaders); // Cleanup client.shutdown(); channel.shutdown(); ``` -------------------------------- ### Configure TLS and mTLS Connections Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Demonstrates setting up a Dgraph client with CA certificate validation and mTLS using NettyChannelBuilder. Ensure client keys are in PKCS#8 format for mTLS. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphGrpc; import io.grpc.netty.GrpcSslContexts; import io.grpc.netty.NettyChannelBuilder; import io.netty.handler.ssl.SslContext; import java.io.File; // TLS with CA certificate validation SslContext sslContext = GrpcSslContexts.forClient() .trustManager(new File("/path/to/ca.crt")) .build(); NettyChannelBuilder channelBuilder = NettyChannelBuilder .forAddress("dgraph.example.com", 9080) .sslContext(sslContext); DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channelBuilder.build()); DgraphClient client = new DgraphClient(stub); // TLS with client certificate authentication (mTLS) SslContext mtlsContext = GrpcSslContexts.forClient() .trustManager(new File("/path/to/ca.crt")) .keyManager( new File("/path/to/client.crt"), new File("/path/to/client.key") // Must be PKCS#8 format ) .build(); NettyChannelBuilder mtlsChannelBuilder = NettyChannelBuilder .forAddress("dgraph.example.com", 9080) .sslContext(mtlsContext); DgraphClient mtlsClient = new DgraphClient( DgraphGrpc.newStub(mtlsChannelBuilder.build()) ); client.shutdown(); mtlsClient.shutdown(); ``` -------------------------------- ### Configure Local Gradle Credentials Source: https://github.com/dgraph-io/dgraph4j/blob/main/PUBLISHING.md Set these properties in ~/.gradle/gradle.properties to enable local artifact publishing. ```properties ossrhUsername= ossrhPassword= signing.keyId= signing.password= signing.secretKeyRingFile= ``` -------------------------------- ### Configure DgraphStub with request deadlines Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSampleDeadlineInterceptors/README.md Use a ClientInterceptor to enforce a 5-second timeout on Dgraph requests. ```java stub = stub.withInterceptors( new ClientInterceptor() { @Override public ClientCall interceptCall( MethodDescriptor method, CallOptions callOptions, Channel next) { return next.newCall(method, callOptions.withDeadlineAfter(5, TimeUnit.SECONDS)); } }); ``` -------------------------------- ### Manage Namespaces with Dgraph Java Client Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Use the Dgraph client to create, list, and drop namespaces. Requires admin privileges and login as 'groot'. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.CreateNamespaceResponse; import io.dgraph.DgraphProto.ListNamespacesResponse; // Login as admin (groot) to manage namespaces DgraphClient client = DgraphClient.open("dgraph://groot:password@localhost:9080"); // Create a new namespace CreateNamespaceResponse createResponse = client.createNamespace(); long newNamespaceId = createResponse.getNsId(); System.out.println("Created namespace: " + newNamespaceId); // List all namespaces ListNamespacesResponse listResponse = client.listNamespaces(); System.out.println("Namespaces: " + listResponse.getNsListList()); // Login to specific namespace client.loginIntoNamespace("user", "password", newNamespaceId); // Work within the namespace... client.setSchema("name: string @index(exact) ."); // Drop namespace when done client.dropNamespace(newNamespaceId); client.shutdown(); ``` -------------------------------- ### Run unit and integration tests Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Executes tests against a local Dgraph server. Warning: This will wipe all data from the target Dgraph instance. ```bash ./gradlew test ``` -------------------------------- ### Create Secure Client with TLS Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Sets up a gRPC channel with TLS enabled for secure communication with the Dgraph Alpha server. Requires CA certificate for trust and client certificate/key for verification. ```java SslContextBuilder builder = GrpcSslContexts.forClient(); builder.trustManager(new File("")); // Skip the next line if you are not performing client verification. builder.keyManager(new File(""), new File("")); SslContext sslContext = builder.build(); ManagedChannel channel = NettyChannelBuilder.forAddress("localhost", 9080) .sslContext(sslContext) .build(); DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel); DgraphClient dgraphClient = new DgraphClient(stub); ``` -------------------------------- ### Create DgraphClient with Managed Channels Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md This snippet demonstrates creating a synchronous DgraphClient using multiple ManagedChannels. Each channel is configured with usePlaintext() for non-TLS connections. ```java ManagedChannel channel1 = ManagedChannelBuilder .forAddress("localhost", 9080) .usePlaintext().build(); DgraphStub stub1 = DgraphGrpc.newStub(channel1); ManagedChannel channel2 = ManagedChannelBuilder .forAddress("localhost", 9082) .usePlaintext().build(); DgraphStub stub2 = DgraphGrpc.newStub(channel2); ManagedChannel channel3 = ManagedChannelBuilder .forAddress("localhost", 9083) .usePlaintext().build(); DgraphStub stub3 = DgraphGrpc.newStub(channel3); DgraphClient dgraphClient = new DgraphClient(stub1, stub2, stub3); ``` -------------------------------- ### Build Dgraph Source Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Build the Dgraph Java client source code using Gradle. This command also runs integration tests against a local Dgraph instance. ```sh ./gradlew build ``` -------------------------------- ### Run DQL Query with Variables and Flags Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Execute a DQL query with variables and specify read-only or best-effort flags. Ensure variables are correctly mapped. ```java Map vars = Collections.singletonMap("$name", "Alice"); Response response = dgraphClient.runDQL( "query q($name: string) { q(func: eq(name, $name)) { uid name } }", vars, true, // readOnly false // bestEffort ); ``` -------------------------------- ### Login to Default Namespace with ACL Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Logs into the Dgraph server using provided user ID and password for the default namespace (0). Assumes ACL is enabled. ```java dgraphClient.login(USER_ID, USER_PASSWORD); ``` -------------------------------- ### Create Namespace Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Create a new namespace in Dgraph for multi-tenancy. The response contains the ID of the newly created namespace. ```java // Create a new namespace DgraphProto.CreateNamespaceResponse response = dgraphClient.createNamespace(); long nsId = response.getNsId(); ``` -------------------------------- ### Open Connection with Connection String Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use DgraphClient.open with a connection string to establish a connection to an ACL-enabled, non-TLS cluster. Ensure to shut down the client when done. ```java DgraphClient client = DgraphClient.open("dgraph://groot:password@localhost:8090"); // some time later... client.shutdown(); ``` -------------------------------- ### runDQL Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Executes DQL queries and mutations directly without requiring an explicit transaction. ```APIDOC ## runDQL ### Description Executes a DQL query or mutation directly. Supports variables and optional flags for read-only and best-effort execution. ### Parameters - **dql** (String) - Required - The DQL query string. - **vars** (Map) - Optional - Variables for the query. - **readOnly** (boolean) - Optional - Set to true for read-only operations. - **bestEffort** (boolean) - Optional - Set to true for best-effort execution. ### Response - **Response** (Object) - Contains the query result and latency information. ``` -------------------------------- ### Execute DQL Queries with Variables in Java Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Demonstrates querying Dgraph with and without variables, including deserializing JSON responses into Java objects using Gson. ```java import com.google.gson.Gson; import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Response; import java.util.Collections; import java.util.List; import java.util.Map; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Define classes for deserializing response class Person { String uid; String name; int age; } class QueryResult { List all; } // Query without variables Response simpleResponse = client.newReadOnlyTransaction() .query("{ all(func: has(name)) { uid name age } }"); // Query with variables String query = "query all($name: string) {\n" + " all(func: eq(name, $name)) {\n" + " uid\n" + " name\n" + " age\n" + " }\n" + "}"; Map vars = Collections.singletonMap("$name", "Alice"); Response response = client.newReadOnlyTransaction().queryWithVars(query, vars); // Deserialize JSON response Gson gson = new Gson(); QueryResult result = gson.fromJson(response.getJson().toStringUtf8(), QueryResult.class); System.out.printf("Found %d people%n", result.all.size()); result.all.forEach(p -> System.out.printf(" %s: %s, age %d%n", p.uid, p.name, p.age)); client.shutdown(); ``` -------------------------------- ### Execute Concurrent Modification Sample Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/concurrent-modification/README.md Runs the Java sample project using Maven. Warning: This will clear all existing data in the target Dgraph instance. ```sh mvn clean install exec:java ``` -------------------------------- ### Use Convenience Alter Methods Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Simplify common schema and data cleanup tasks using built-in client methods that wrap protocol buffer calls. ```java import io.dgraph.DgraphClient; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Set schema directly client.setSchema("name: string @index(exact) .\nage: int ."); // Drop all data and schema client.dropAll(); // Drop data only (preserves schema) client.dropData(); // Drop a specific predicate client.dropPredicate("name"); // Drop a specific type client.dropType("Person"); client.shutdown(); ``` -------------------------------- ### Implement Automatic Retries with withRetry() Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Uses exponential backoff to handle transient failures. Supports custom retry policies and specialized read-only or best-effort configurations. ```java import com.google.protobuf.ByteString; import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Mutation; import io.dgraph.DgraphProto.Response; import io.dgraph.RetryPolicy; import java.time.Duration; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Default retry policy: 5 retries, 100ms base delay, exponential backoff Response response = client.withRetry(txn -> { Mutation mutation = Mutation.newBuilder() .setSetJson(ByteString.copyFromUtf8("{\"name\": \"Alice\"}")) .build(); txn.mutate(mutation); txn.commit(); return txn.query("{ all(func: eq(name, \"Alice\")) { uid } }"); }); // Custom retry policy RetryPolicy customPolicy = RetryPolicy.builder() .maxRetries(10) .baseDelay(Duration.ofMillis(200)) .maxDelay(Duration.ofSeconds(10)) .jitter(0.2) .build(); Response customResponse = client.withRetry(customPolicy, txn -> { txn.mutate(Mutation.newBuilder() .setSetJson(ByteString.copyFromUtf8("{\"name\": \"Bob\"}")) .build()); txn.commit(); return txn.query("{ all(func: has(name)) { name } }"); }); // Read-only retry Response readResponse = client.withRetry(RetryPolicy.readOnly(), txn -> txn.query("{ all(func: has(name)) { uid name } }") ); // Best-effort retry (read-only with relaxed consistency) Response bestEffortResponse = client.withRetry(RetryPolicy.bestEffort(), txn -> txn.query("{ all(func: has(name)) { uid name } }") ); client.shutdown(); ``` -------------------------------- ### Run Mutation with CommitNow Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use the `CommitNow` field in the `Mutation` object to ensure the mutation is immediately committed without further queries. ```java Request request = Request.newBuilder() .addMutations(mu) .build(); txn.doRequest(request); ``` -------------------------------- ### Attaching Metadata Headers Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use MetadataUtils to attach authentication tokens or other headers to the gRPC stub for all subsequent RPC calls. ```java // create the stub first ManagedChannel channel = ManagedChannelBuilder.forAddress(TEST_HOSTNAME, TEST_PORT).usePlaintext(true).build(); DgraphStub stub = DgraphGrpc.newStub(channel); // use MetadataUtils to augment the stub with headers Metadata metadata = new Metadata(); metadata.put( Metadata.Key.of("auth-token", Metadata.ASCII_STRING_MARSHALLER), "the-auth-token-value"); stub = MetadataUtils.attachHeaders(stub, metadata); // create the DgraphClient wrapper around the stub DgraphClient dgraphClient = new DgraphClient(stub); // trigger a RPC call using the DgraphClient dgraphClient.alter(Operation.newBuilder().setDropAll(true).build()); ``` -------------------------------- ### Manage ACID Transactions in Java Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Demonstrates read-write, read-only, and best-effort transaction modes. Always discard transactions in a finally block to ensure resources are released. ```java import com.google.gson.Gson; import com.google.protobuf.ByteString; import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Mutation; import io.dgraph.DgraphProto.Response; import io.dgraph.Transaction; import io.dgraph.TxnConflictException; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Read-write transaction Transaction txn = client.newTransaction(); try { // Perform mutations Mutation mutation = Mutation.newBuilder() .setSetJson(ByteString.copyFromUtf8("{\"name\": \"Alice\"}")) .build(); txn.mutate(mutation); // Query within same transaction sees uncommitted changes Response response = txn.query("{ all(func: eq(name, \"Alice\")) { uid name } }"); // Commit all changes txn.commit(); } catch (TxnConflictException e) { // Handle concurrent modification - retry with new transaction System.out.println("Transaction conflict, retrying..."); } finally { // Always discard - safe to call after commit txn.discard(); } // Read-only transaction (more efficient for queries) Transaction readTxn = client.newReadOnlyTransaction(); Response result = readTxn.query("{ all(func: has(name)) { uid name } }"); // No commit or discard needed for read-only queries // Best-effort read-only (sees uncommitted data, lowest latency) Transaction bestEffortTxn = client.newReadOnlyTransaction(); bestEffortTxn.setBestEffort(true); Response fastResult = bestEffortTxn.query("{ all(func: has(name)) { uid name } }"); client.shutdown(); ``` -------------------------------- ### List Namespaces Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Retrieve a list of all namespaces currently configured in Dgraph. This is useful for managing multi-tenancy. ```java // List all namespaces DgraphProto.ListNamespacesResponse response = dgraphClient.listNamespaces(); ``` -------------------------------- ### Run Simple DQL Query Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Execute a DQL query directly using the runDQL method. This is suitable for simple, self-contained operations. ```java // Run a simple query Response response = dgraphClient.runDQL("{all(func: has(name)) {uid name}}"); String json = response.getJson().toStringUtf8(); ``` -------------------------------- ### Execute and Deserialize Dgraph Query in Java Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md This snippet demonstrates executing a DQL query with variables, deserializing the JSON response into a Java object, and printing the results. ```java // Query String query = "query all($a: string){\n" + " all(func: eq(name, $a)) {\n" + " name\n" + " }\n" + "}\n"; Map vars = Collections.singletonMap("$a", "Alice"); Response response = dgraphClient.newReadOnlyTransaction().queryWithVars(query, vars); // Deserialize People ppl = gson.fromJson(response.getJson().toStringUtf8(), People.class); // Print results System.out.printf("people found: %d\n", ppl.all.size()); ppl.all.forEach(person -> System.out.println(person.name)); ``` -------------------------------- ### Create a Normal Read-Write Transaction Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use this for transactions that include queries and mutations. Always call `Transaction#discard()` in a `finally` block. ```java Transaction txn = dgraphClient.newTransaction(); try { // Do something here // ... } finally { txn.discard(); } ``` -------------------------------- ### Automatic Retry with Custom Policy Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Configure a custom retry policy for `withRetry` by specifying the maximum number of retries and the base delay. ```java Response resp = client.withRetry( RetryPolicy.builder() .maxRetries(10) .baseDelay(Duration.ofMillis(200)) .build(), txn -> { txn.mutate(mutation); txn.commit(); return txn.query(query); }); ``` -------------------------------- ### Namespace Management Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Methods for managing multi-tenancy namespaces in Dgraph. ```APIDOC ## Namespace Management ### Description Operations to create, list, and drop namespaces for multi-tenancy support. ### Methods - **createNamespace()** - Creates a new namespace. - **listNamespaces()** - Lists all existing namespaces. - **dropNamespace(long nsId)** - Drops a specific namespace by ID. ``` -------------------------------- ### Login to Specific Namespace with ACL Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Logs into a specified namespace on the Dgraph server using user ID and password. Requires ACL to be enabled. ```java dgraphClient.loginIntoNamespace(USER_ID, USER_PASSWORD, NAMESPACE); ``` -------------------------------- ### Retrieve DQL Query Results in RDF Format Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Shows how to fetch query results as RDF N-Quads using queryRDFWithVars. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Response; import java.util.Collections; import java.util.Map; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Query returning RDF format String query = "query me($name: string) {\n" + " me(func: eq(name, $name)) {\n" + " name\n" + " age\n" + " friend {\n" + " name\n" + " }\n" + " }\n" + "}"; Map vars = Collections.singletonMap("$name", "Alice"); Response response = client.newReadOnlyTransaction().queryRDFWithVars(query, vars); // Get RDF output String rdf = response.getRdf().toStringUtf8(); System.out.println(rdf); // Output: // <0x1> "Alice" . // <0x1> "30"^^ . // <0x1> <0x2> . // <0x2> "Bob" . client.shutdown(); ``` -------------------------------- ### Allocate Namespaces Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Pre-allocate a range of namespace IDs from Dgraph. This is relevant for multi-tenant applications. ```java // Allocate namespace IDs DgraphProto.AllocateIDsResponse nsResponse = dgraphClient.allocateNamespaces(10); ``` -------------------------------- ### Performing an Upsert with Query and Mutation Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Execute a combined query and mutation using txn.doRequest. This is useful for atomic operations where the mutation depends on query results. ```java String query = "query {\n" + "user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n" + "}"; Mutation mu = Mutation.newBuilder() .setSetNquads(ByteString.copyFromUtf8("uid(user) \"correct_email@dgraph.io\" .")) .build(); Request request = Request.newBuilder() .setQuery(query) .addMutations(mu) .setCommitNow(true) .build(); txn.doRequest(request); ``` -------------------------------- ### Convert Client Key to PKCS#8 Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Converts a client private key from PKCS#1 to PKCS#8 format using the openssl tool. This is necessary for gRPC client verification when using TLS. ```sh openssl pkcs8 -in client.name.key -topk8 -nocrypt -out client.name.java.key ``` -------------------------------- ### Check Dgraph Version with Java Client Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Verify Dgraph server connectivity and retrieve the server version using the Java client. This is useful for compatibility checks. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Version; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Check version (also tests connectivity) Version version = client.checkVersion(); System.out.println("Dgraph version: " + version.getTag()); // Output: Dgraph version: v24.0.0 client.shutdown(); ``` -------------------------------- ### Execute Dgraph Request with Request Builder Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use the `Request.newBuilder()` to construct a request object for executing queries or mutations via `txn.doRequest()`. ```java Request request = Request.newBuilder() .setQuery(query) .build(); txn.doRequest(request); ``` -------------------------------- ### Query Response Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/concurrent-modification/README.md The expected JSON response after concurrent updates. ```json { "data": { "Alice": [ { "uid": "0xe", "name": "Alice", "clickCount": 3 } ] } } ``` -------------------------------- ### Check Dgraph Version Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Retrieves and prints the Dgraph server version tag. Useful for verifying client-server communication and as an initial test before performing other operations. ```java Version v = dgraphClient.checkVersion(); System.out.println(v.getTag()); ``` -------------------------------- ### Perform Mutations with RDF N-Quads Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Use RDF N-Quad format for mutations to define complex relationships or perform specific deletions. ```java import com.google.protobuf.ByteString; import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Mutation; import io.dgraph.DgraphProto.Response; import io.dgraph.Transaction; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); client.setSchema("name: string @index(exact) .\nage: int .\nfriend: [uid] ."); Transaction txn = client.newTransaction(); try { // Insert data using N-Quads String nquads = "_:alice \"Alice\" .\n" + "_:alice \"30\"^^ .\n" + "_:bob \"Bob\" .\n" + "_:alice _:bob ."; Mutation mutation = Mutation.newBuilder() .setSetNquads(ByteString.copyFromUtf8(nquads)) .build(); Response response = txn.mutate(mutation); // Get the actual UIDs assigned to blank nodes String aliceUid = response.getUidsMap().get("alice"); String bobUid = response.getUidsMap().get("bob"); System.out.printf("Alice UID: %s, Bob UID: %s%n", aliceUid, bobUid); txn.commit(); } finally { txn.discard(); } client.shutdown(); ``` -------------------------------- ### Set DgraphStub Deadline Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/DgraphJavaSampleWithDeadlineAfter/README.md Configures a deadline for the entire life of the DgraphStub. Note that this is generally discouraged; refer to the project documentation for proper deadline management. ```java stub = stub.withDeadlineAfter(5, TimeUnit.SECONDS); ``` -------------------------------- ### Configuring gRPC Deadlines Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Set timeouts for client calls to ensure they terminate after a specified duration. Deadlines can be applied globally via interceptors or per individual request. ```java channel = ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build(); DgraphGrpc.DgraphStub stub = DgraphGrpc.newStub(channel); ClientInterceptor timeoutInterceptor = new ClientInterceptor(){ @Override public ClientCall interceptCall( MethodDescriptor method, CallOptions callOptions, Channel next) { return next.newCall(method, callOptions.withDeadlineAfter(500, TimeUnit.MILLISECONDS)); } }; stub = stub.withInterceptors(timeoutInterceptor); DgraphClient dgraphClient = new DgraphClient(stub); ``` ```java dgraphClient.newTransaction().query(query, 500, TimeUnit.MILLISECONDS); ``` -------------------------------- ### Perform Mutations with JSON Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Serialize objects to JSON and use the setSetJson method to add or modify data within a transaction. ```java import com.google.gson.Gson; import com.google.protobuf.ByteString; import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Mutation; import io.dgraph.DgraphProto.Response; import io.dgraph.Transaction; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); client.setSchema("name: string @index(exact) .\nage: int ."); // Define data class class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } } Gson gson = new Gson(); Transaction txn = client.newTransaction(); try { // Create and serialize data Person person = new Person("Alice", 30); String json = gson.toJson(person); // Build and run mutation Mutation mutation = Mutation.newBuilder() .setSetJson(ByteString.copyFromUtf8(json)) .build(); Response response = txn.mutate(mutation); // Get assigned UIDs System.out.println("Created UIDs: " + response.getUidsMap()); // Output: {blank-0=0x1} txn.commit(); } finally { txn.discard(); } client.shutdown(); ``` -------------------------------- ### Configure netty-tcnative-boringssl-static dependency Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Required for gRPC with TLS on Java 1.8.x for dgraph4j versions prior to v24.0.0. ```xml io.netty netty-tcnative-boringssl-static ``` ```groovy compile 'io.netty:netty-tcnative-boringssl-static:' ``` -------------------------------- ### Asynchronous DQL Query Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Execute a DQL query asynchronously using the DgraphAsyncClient. Results are returned via a CompletableFuture. ```java // Query String query = "query all($a: string){\n" + " all(func: eq(name, $a)) {\n" + " name\n " + "} "; Map vars = Collections.singletonMap("$a", "Alice"); AsyncTransaction txn = dgraphAsyncClient.newTransaction(); txn.query(query).thenAccept(response -> { // Deserialize People ppl = gson.fromJson(res.getJson().toStringUtf8(), People.class); // Print results System.out.printf("people found: %d\n", ppl.all.size()); ppl.all.forEach(person -> System.out.println(person.name)); }); ``` -------------------------------- ### Modify Schema with alter() Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Use the Operation protocol buffer to define schema changes, background indexing, or data/schema drop operations. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Operation; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Set schema String schema = "name: string @index(exact) .\n" + "age: int .\n" + "friend: [uid] @reverse ."; Operation setSchema = Operation.newBuilder() .setSchema(schema) .build(); client.alter(setSchema); // Set schema with background indexing (non-blocking) Operation bgSchema = Operation.newBuilder() .setSchema("description: string @index(fulltext) .") .setRunInBackground(true) .build(); client.alter(bgSchema); // Drop all data and schema client.alter(Operation.newBuilder().setDropAll(true).build()); // Drop only data (preserve schema) client.alter(Operation.newBuilder() .setDropOp(Operation.DropOp.DATA) .build()); // Drop a specific predicate client.alter(Operation.newBuilder() .setDropOp(Operation.DropOp.ATTR) .setDropValue("name") .build()); client.shutdown(); ``` -------------------------------- ### Execute DQL Directly without Transactions Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Utilizes runDQL for simple operations, including support for read-only and best-effort flags. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Response; import java.util.Collections; import java.util.Map; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Simple query Response response = client.runDQL("{ all(func: has(name)) { uid name } }"); System.out.println(response.getJson().toStringUtf8()); // Query with variables Map vars = Collections.singletonMap("$name", "Alice"); Response varResponse = client.runDQL( "query q($name: string) { q(func: eq(name, $name)) { uid name } }", vars, true, // readOnly false // bestEffort ); // Best-effort read (may see uncommitted data, lower latency) Response bestEffortResponse = client.runDQL( "{ all(func: has(name)) { uid name } }", Collections.emptyMap(), true, // readOnly true // bestEffort ); client.shutdown(); ``` -------------------------------- ### Query Alice's Data Source: https://github.com/dgraph-io/dgraph4j/blob/main/samples/concurrent-modification/README.md Retrieves the final state of the user 'Alice' to verify the click count. ```graphql { Alice(func: has()) @filter(eq(name,"Alice" )) { uid name clickCount } } ``` -------------------------------- ### Handle Dgraph Exceptions by Subclass (e.g., AlphaShutdown) Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Route exceptions based on their subclass, such as AlphaShutdownException, to implement specific recovery logic like switching to a different Alpha node. ```java try { txn.mutate(mutation); txn.commit(); } catch (AlphaShutdownException e) { // switch to a different Alpha and retry } catch (DgraphException e) { if (e.isRetryable()) { // back off and retry on the same node } throw e; } ``` -------------------------------- ### Schema and Data Management Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Convenience methods for managing schema, dropping data, and managing predicates or types. ```APIDOC ## Schema and Data Management ### Description Provides administrative methods to modify the database schema or clear data. ### Methods - **setSchema(String schema)** - Sets the database schema. - **dropAll()** - Drops all data and schema. - **dropData()** - Drops all data while preserving the schema. - **dropPredicate(String predicate)** - Drops a specific predicate. - **dropType(String type)** - Drops a specific type definition. ``` -------------------------------- ### Execute Conditional Upserts in Java Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Uses the @if directive to perform mutations only when specific query conditions are met. Requires a properly configured Dgraph client and transaction. ```java import com.google.protobuf.ByteString; import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Mutation; import io.dgraph.DgraphProto.Request; import io.dgraph.Transaction; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); client.setSchema("email: string @index(exact) @upsert .\nname: string .\nverified: bool ."); Transaction txn = client.newTransaction(); try { // Only update if exactly one matching user exists String query = "query {\n" + " user as var(func: eq(email, \"alice@example.com\"))\n" + "}"; Mutation mutation = Mutation.newBuilder() .setSetNquads(ByteString.copyFromUtf8( "uid(user) \"true\" ." )) .setCond("@if(eq(len(user), 1))") // Execute only if one user found .build(); Request request = Request.newBuilder() .setQuery(query) .addMutations(mutation) .setCommitNow(true) .build(); txn.doRequest(request); System.out.println("Conditional upsert completed"); } finally { txn.discard(); } client.shutdown(); ``` -------------------------------- ### Delete Edges with Helpers Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Use the Helpers.deleteEdges utility to generate mutations for removing specific predicates from a node. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Mutation; import io.dgraph.Helpers; import io.dgraph.Transaction; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); Transaction txn = client.newTransaction(); try { String uid = "0x1"; // UID of node to modify // Create mutation to delete specific edges Mutation mutation = Mutation.newBuilder().build(); mutation = Helpers.deleteEdges(mutation, uid, "friend", "location", "age"); // Execute the deletion txn.mutate(mutation); txn.commit(); System.out.println("Edges deleted from node " + uid); } finally { txn.discard(); } client.shutdown(); ``` -------------------------------- ### Automatic Retry for Read-Only or Best-Effort Operations Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Execute read-only or best-effort operations using `withRetry` with pre-defined policies. These are suitable for queries that do not modify data. ```java Response resp = client.withRetry(RetryPolicy.readOnly(), txn -> txn.query(query)); Response resp = client.withRetry(RetryPolicy.bestEffort(), txn -> txn.query(query)); ``` -------------------------------- ### Define a Java Class for JSON Mutation Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Define a simple Java class that will be serialized to JSON for use in a mutation. ```java class Person { String name; Person() {} } ``` -------------------------------- ### Allocate IDs with Dgraph Java Client Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Pre-allocate ranges of UIDs, timestamps, or namespace IDs using the Dgraph client for bulk operations or external ID management. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.AllocateIDsResponse; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Allocate a range of UIDs AllocateIDsResponse uidResponse = client.allocateUIDs(100); long startUid = uidResponse.getStartId(); long endUid = uidResponse.getEndId(); System.out.printf("Allocated UIDs: %d to %d%n", startUid, endUid); // Allocate timestamps AllocateIDsResponse tsResponse = client.allocateTimestamps(50); System.out.printf("Allocated timestamps: %d to %d%n", tsResponse.getStartId(), tsResponse.getEndId()); // Allocate namespace IDs AllocateIDsResponse nsResponse = client.allocateNamespaces(10); System.out.printf("Allocated namespace IDs: %d to %d%n", nsResponse.getStartId(), nsResponse.getEndId()); client.shutdown(); ``` -------------------------------- ### Querying with RDF response in Java Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Use queryRDFWithVars to retrieve results in RDF format. Note that querying for UID values only should be done using JSON format instead. ```java // Query String query = "query me($a: string) { me(func: eq(name, $a)) { name }}"; Map vars = Collections.singletonMap("$a", "Alice"); Response response = dgraphAsyncClient.newReadOnlyTransaction().queryRDFWithVars(query, vars).join(); // Print results System.out.println(response.getRdf().toStringUtf8()); ``` -------------------------------- ### Check Request Latency with Dgraph Java Client Source: https://context7.com/dgraph-io/dgraph4j/llms.txt Access latency metrics from Dgraph query and mutation responses for performance monitoring and debugging. Metrics are provided in nanoseconds. ```java import io.dgraph.DgraphClient; import io.dgraph.DgraphProto.Latency; import io.dgraph.DgraphProto.Response; DgraphClient client = DgraphClient.open("dgraph://localhost:9080"); // Query and get latency Response response = client.newReadOnlyTransaction() .query("{ all(func: has(name)) { uid name } }"); Latency latency = response.getLatency(); System.out.printf("Parsing: %d ns%n", latency.getParsingNs()); System.out.printf("Processing: %d ns%n", latency.getProcessingNs()); System.out.printf("Encoding: %d ns%n", latency.getEncodingNs()); System.out.printf("Total: %d ns%n", latency.getTotalNs()); // Convert to milliseconds for readability double totalMs = latency.getTotalNs() / 1_000_000.0; System.out.printf("Total latency: %.2f ms%n", totalMs); client.shutdown(); ``` -------------------------------- ### ID Allocation Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Methods to pre-allocate ranges for UIDs, timestamps, or namespace IDs. ```APIDOC ## ID Allocation ### Description Allocates ranges for system identifiers. ### Methods - **allocateUIDs(int count)** - Allocates a range of UIDs. - **allocateTimestamps(int count)** - Allocates a range of timestamps. - **allocateNamespaces(int count)** - Allocates a range of namespace IDs. ``` -------------------------------- ### Log Mutation Latency Source: https://github.com/dgraph-io/dgraph4j/blob/main/README.md Retrieve and log the latency metrics for a Dgraph mutation request. This helps in understanding the performance of write operations. ```java Assigned assignedIds = dgraphClient.newTransaction().mutate(mu); Latency latency = assignedIds.getLatency(); ```