### Install Badger Library (Shell) Source: https://docs.hypermode.com/badger/quickstart Uses the Go command-line tool to download and install the Badger key-value store library. ```Shell go get github.com/dgraph-io/badger/v4 ``` -------------------------------- ### Install Badger CLI Utility (Shell) Source: https://docs.hypermode.com/badger/quickstart Installs the Badger command-line utility into the user's GOBIN path for direct interaction with Badger databases. ```Shell go install github.com/dgraph-io/badger/v4/badger@latest ``` -------------------------------- ### Running Dgraph Standalone Docker (sh) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/introduction Command to run the Dgraph standalone Docker image for quickstarts. Maps ports 8080 (HTTP) and 9080 (gRPC) and removes the container on exit. This setup is not recommended for production. ```sh docker run --rm -it -p 8080:8080 -p 9080:9080 dgraph/standalone:latest ``` -------------------------------- ### Installing Python Dependencies (Shell) Source: https://docs.hypermode.com/getting-started-with-hyper-commerce Installs the required Python packages listed in the `requirements.txt` file. This is necessary to run the data seeding script. ```Shell pip install -r requirements.txt ``` -------------------------------- ### Installing Python Dependencies for Data Population Source: https://docs.hypermode.com/getting-started-with-hyper-commerce This command installs the necessary Python libraries (requests, gql, requests_toolbelt, pandas, numpy) required to execute the data population script for the Hypermode Commerce template. ```sh pip install requests gql requests_toolbelt pandas numpy ``` -------------------------------- ### Run Frontend Development Server (bash) Source: https://docs.hypermode.com/getting-started-with-hyper-commerce Execute the npm script to start the local development server for the frontend application. This command compiles the code and serves the application, allowing you to test changes in real-time. ```bash npm run dev ``` -------------------------------- ### Install Dgraph Go Client Source: https://docs.hypermode.com/dgraph/sdks/go Instructions for installing the Dgraph Go client library using `go get`. Requires Go 1.23 or later and GO111MODULE=on. ```sh Requires at least Go 1.23 export GO111MODULE=on go get -u -v github.com/dgraph-io/dgo/v210 ``` -------------------------------- ### Helm Install Output Example Source: https://docs.hypermode.com/dgraph/self-managed/ha-cluster Example output shown after successfully deploying Dgraph using the Helm chart, including notes on accessing the service. ```sh NAME: LAST DEPLOYED: Wed Feb 1 21:26:32 2023 NAMESPACE: default STATUS: deployed REVISION: 1 TEST SUITE: None NOTES: 1. You have just deployed Dgraph, version 'v21.12.0'. For further information: * Documentation: https://docs.hypermode.com/dgraph * Community and Issues: https://discuss.hypermode.com/ 2. Get the Dgraph Alpha HTTP/S endpoint by running these commands. export ALPHA_POD_NAME=$(kubectl get pods --namespace default --selector "statefulset.kubernetes.io/pod-name=-dgraph-alpha-0,release=-dgraph" --output jsonpath="{.items[0].metadata.name}") echo "Access Alpha HTTP/S using http://localhost:8080" kubectl --namespace default port-forward $ALPHA_POD_NAME 8080:8080 NOTE: Change "http://" to "https://" if TLS was added to the Ingress, Load Balancer, or Dgraph Alpha service. ``` -------------------------------- ### Starting Read-Only Transaction (Go) Source: https://docs.hypermode.com/badger/quickstart Initiates a read-only transaction using the db.View method. Operations within the provided function closure will have a consistent view of the database state at the time the transaction started. ```Go err := db.View(func(txn *badger.Txn) error { // your code here return nil }) ``` -------------------------------- ### Start Dgraph Services with Docker Compose (Shell) Source: https://docs.hypermode.com/dgraph/self-managed/single-host-setup Executes the `docker-compose up` command with `sudo` to build, create, and start the services defined in the `docker-compose.yml` file. This brings up the Dgraph Zero, Alpha, and Ratel containers. ```sh sudo docker-compose up ``` -------------------------------- ### Running Hypermode Frontend Development Server Source: https://docs.hypermode.com/getting-started-with-hyper-commerce This command executes the `dev` script defined in the project's `package.json` file. It is used to start the local development server for the Hypermode frontend application, allowing you to test the integration. ```sh npm run dev ``` -------------------------------- ### Starting Read-Write Transaction (Go) Source: https://docs.hypermode.com/badger/quickstart Initiates a read-write transaction using the db.Update method. This allows performing database operations like Set and Delete within the provided function closure. ```Go err := db.Update(func(txn *badger.Txn) error { // Your code here… return nil }) ``` -------------------------------- ### Example Output of Docker Containers (Shell Output) Source: https://docs.hypermode.com/dgraph/self-managed/single-host-setup Shows a sample output from the `sudo docker ps -a` command, listing the container ID, image, command, and creation time for the running Dgraph Zero, Alpha, and Ratel containers. ```sh CONTAINER ID IMAGE COMMAND CREATED 4b67157933b6 dgraph/dgraph:latest "dgraph zero --my=ze—" 2 days ago 3faf9bba3a5b dgraph/ratel:latest "/usr/local/bin/dgra—" 2 days ago a6b5823b668d dgraph/dgraph:latest "dgraph alpha --my=a—" 2 days ago a6b5823b668d dgraph/dgraph:latest "dgraph alpha --my=a…" 2 days ago ``` -------------------------------- ### Manually Managing Writable Badger Transactions in Go Source: https://docs.hypermode.com/badger/quickstart Demonstrates how to manually start a writable transaction using `db.NewTransaction(true)`, perform operations like `txn.Set`, and commit the transaction using `txn.Commit()`. Includes using `defer txn.Discard()` for cleanup in case of early exit. ```Go // Start a writable transaction. txn := db.NewTransaction(true) defer txn.Discard() // Use the transaction... err := txn.Set([]byte("answer"), []byte("42")) if err != nil { return err } // Commit the transaction and check for error. if err := txn.Commit(); err != nil { return err } ``` -------------------------------- ### Start React Development Server Source: https://docs.hypermode.com/dgraph/guides/to-do-app/ui Commands to navigate into the project directory and start the local development server. ```sh cd todo-react-app npm start ``` -------------------------------- ### Handling Large Transactions (Go) Source: https://docs.hypermode.com/badger/quickstart Demonstrates how to handle the ErrTxnTooBig error during a read-write transaction by committing the current transaction and starting a new one to continue processing updates. ```Go updates := make(map[string]string) txn := db.NewTransaction(true) for k,v := range updates { if err := txn.Set([]byte(k),[]byte(v)); err == badger.ErrTxnTooBig { _ = txn.Commit() txn = db.NewTransaction(true) _ = txn.Set([]byte(k),[]byte(v)) } } _ = txn.Commit() ``` -------------------------------- ### Install Core UI Dependencies Source: https://docs.hypermode.com/dgraph/guides/to-do-app/ui Installs necessary front-end libraries for the UI components and routing. ```sh npm install todomvc-app-css classnames graphql-tag history react-router-dom ``` -------------------------------- ### Run Java Concurrent Modification Example Source: https://docs.hypermode.com/dgraph/sdks/java Maven command to clean, install, and execute the concurrent modification example from the dgraph4j samples. ```sh mvn clean install exec:java ``` -------------------------------- ### Start React App (Get Token) Source: https://docs.hypermode.com/dgraph/guides/to-do-app/auth0-jwt Starts the React application using npm, typically for development. This step is performed to access the application in a browser and retrieve the JWT from the network tab. ```npm npm start ``` -------------------------------- ### Starting Dgraph Standalone with Docker Source: https://docs.hypermode.com/dgraph/guides/to-do-app/schema-design This command starts a Dgraph standalone instance using Docker, mapping the default GraphQL port (8080) from the container to the host machine. Ensure Docker is installed before running. ```sh docker run -it -p 8080:8080 dgraph/standalone:%VERSION_HERE ``` -------------------------------- ### Running Dgraph Ratel UI Docker (sh) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/introduction Command to run the Dgraph Ratel UI Docker image. Maps port 8000 and runs in detached mode. Access the UI via a web browser at http://localhost:8000. ```sh docker run --rm -d -p 8000:8000 dgraph/ratel:latest ``` -------------------------------- ### Implementing Pagination with BadgerDB Prefix Scan (Go) Source: https://docs.hypermode.com/badger/quickstart This Go function demonstrates how to implement pagination using BadgerDB's prefix scan feature. It iterates through keys matching a given prefix, starting from an optional cursor, and limits the number of results per iteration. It returns the next cursor for subsequent pages and any encountered error. ```go // startCursor may look like 'feed:tQpnEDVRoCxTFQDvyQEzdo:1733127486'. // A prefix scan with this cursor locates the specific key where // the previous iteration stopped. err = db.badger.View(func(txn *badger.Txn) error { it := txn.NewIterator(opts) defer it.Close() // Prefix example 'feed:tQpnEDVRoCxTFQDvyQEzdo' // if no cursor provided prefix scan starts from the beginning p := prefix if startCursor != nil { p = startCursor } iterNum := 0 // Tracks the number of iterations to enforce the limit. for it.Seek(p); it.ValidForPrefix(p); it.Next() { // The method it.ValidForPrefix ensures that iteration continues // as long as keys match the prefix. // For example, if p = 'feed:tQpnEDVRoCxTFQDvyQEzdo:1733127486', // it matches keys like // 'feed:tQpnEDVRoCxTFQDvyQEzdo:1733127889:pprRrNL2WP4yfVXsSNBSx6'. // Once the starting point for iteration is found, revert the prefix // back to 'feed:tQpnEDVRoCxTFQDvyQEzdo' to continue iterating sequentially. // Otherwise, iteration would stop after a single prefix-key match. p = prefix item := it.Item() key := string(item.Key()) if iterNum > limit { // Limit reached. nextCursor = key // Save the next cursor for future iterations. return nil } iterNum++ // Increment iteration count. err := item.Value(func(v []byte) error { fmt.Printf("key=%s, value=%s\n", k, v) return nil }) if err != nil { return err } } // If the number of iterations is less than the limit, // it means there are no more items for the prefix. if iterNum < limit { nextCursor = "" } return nil }) return nextCursor, err ``` -------------------------------- ### Start Application Development Server - Shell Source: https://docs.hypermode.com/dgraph/guides/to-do-app/ui Command used in the terminal to start the local development server for the application. ```Shell npm start ``` -------------------------------- ### Configure Index Cache Size (Go) Source: https://docs.hypermode.com/badger/quickstart Sets the IndexCache option for a Badger database to improve read performance, especially when encryption is enabled. The example sets a 100 MB cache. ```Go opts.IndexCache = 100 << 20 // 100 mb or some other size based on the amount of data ``` -------------------------------- ### Install Apollo and Auth0 Dependencies Source: https://docs.hypermode.com/dgraph/guides/to-do-app/ui Installs libraries required for integrating Apollo Client for GraphQL and Auth0 for authentication. ```sh npm install @apollo/react-hooks apollo-cache-inmemory apollo-client apollo-link-http graphql apollo-link-context react-todomvc @auth0/auth0-react ``` -------------------------------- ### Run Dgraph Zero using CLI Source: https://docs.hypermode.com/dgraph/self-managed/single-host-setup Starts a Dgraph Zero instance directly using the Dgraph command line. The --my flag specifies the address where Alpha nodes can connect to Zero. ```sh dgraph zero --my=:5080 ``` -------------------------------- ### Adding a Review with GraphQL Mutation (Dgraph) Source: https://docs.hypermode.com/dgraph/graphql/quickstart This GraphQL mutation adds a new review to the graph. It identifies the reviewer by username and the product by productID. Note that the productID '0x2' is an example and should be replaced with the actual ID returned from a previous product creation mutation. ```graphql mutation { addReview( input: [ { by: { username: "Michael" } about: { productID: "0x2" } comment: "Fantastic, easy to install, worked great. Best GraphQL server available" rating: 10 } ] ) { review { comment rating by { username } about { name } } } } ``` -------------------------------- ### Cloning and Setting Up Firebase Todo App (Shell) Source: https://docs.hypermode.com/dgraph/guides/to-do-app/firebase-jwt These shell commands clone the Dgraph GraphQL sample apps repository, navigate into the specific todo-react-firebase example directory, and install the necessary Node.js dependencies using npm. This prepares the local environment for deploying the Firebase Cloud Function. ```shell git clone https://github.com/dgraph-io/graphql-sample-apps.git cd graphql-sample-apps/todo-react-firebase npm i ``` -------------------------------- ### Start Local PostgreSQL with Docker Compose (sh) Source: https://docs.hypermode.com/modus/search Navigates to the local tools directory and starts the PostgreSQL database instance using Docker Compose. ```sh cd modus/runtime/tools/local docker compose up ``` -------------------------------- ### Install Hyp CLI (Shell) Source: https://docs.hypermode.com/quickstart Installs the Hypermode command-line interface globally using npm. This is required to interact with Hypermode projects from the terminal. ```sh npm install -g @hypermode/hyp-cli ``` -------------------------------- ### Using Monotonically Increasing Sequence with DB.GetSequence in Badger Go Source: https://docs.hypermode.com/badger/quickstart Shows how to obtain a thread-safe, monotonically increasing integer sequence using `db.GetSequence`. It demonstrates getting the next number in a loop and using `defer seq.Release()` to release the sequence resources when done. ```Go seq, err := db.GetSequence(key, 1000) defer seq.Release() for { num, err := seq.Next() } ``` -------------------------------- ### Kubectl Get Pods Output Example Source: https://docs.hypermode.com/dgraph/self-managed/ha-cluster Example output from `kubectl get pods` showing the status of Dgraph Alpha and Zero pods after deployment. ```sh NAME READY STATUS RESTARTS AGE -dgraph-alpha-0 1/1 Running 0 4m48s -dgraph-alpha-1 1/1 Running 0 4m2s -dgraph-alpha-2 1/1 Running 0 3m31s -dgraph-zero-0 1/1 Running 0 4m48s -dgraph-zero-1 1/1 Running 0 4m10s -dgraph-zero-2 1/1 Running 0 3m50s ``` -------------------------------- ### Run Dgraph Alpha Nodes using CLI Source: https://docs.hypermode.com/dgraph/self-managed/single-host-setup Starts two Dgraph Alpha nodes using the Dgraph command line. Each Alpha connects to the Zero node using --zero and specifies its own address using --my. The second Alpha uses -o=1 for instance offset. ```sh dgraph alpha --my=:7080 --zero=localhost:5080 dgraph alpha --my=:7081 --zero=localhost:5080 -o=1 ``` -------------------------------- ### Opening Badger Database (Go) Source: https://docs.hypermode.com/badger/quickstart Demonstrates how to open a Badger database using badger.Open with default options, specifying the directory path. Includes basic error handling and ensures the database is closed using defer. ```Go package main import ( "log" badger "github.com/dgraph-io/badger/v4" ) func main() { // Open the Badger database located in the /tmp/badger directory. // It is created if it doesn't exist. db, err := badger.Open(badger.DefaultOptions("/tmp/badger")) if err != nil { log.Fatal(err) } defer db.Close() // your code here } ``` -------------------------------- ### Querying Dgraph with alloftext (GraphQL) - Example 1 Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/advanced-text-search This query demonstrates the `alloftext` function in Dgraph's GraphQL+- query language. It searches for tweets where the `tweet` predicate contains all the specified tokens, regardless of their order. This example uses the search string "graph analyze and it in graphdb data". ```graphql { search_tweet(func: alloftext(tweet, "graph analyze and it in graphdb data")) { tweet } } ``` -------------------------------- ### Querying Dgraph with alloftext (GraphQL) - Example 3 Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/advanced-text-search This query demonstrates the `alloftext` function in Dgraph's GraphQL+- query language. It searches for tweets where the `tweet` predicate contains all the specified tokens, regardless of their order. This example uses the search string "analyze data and it in graph graphdb", further illustrating the order-independent nature of `alloftext`. ```graphql { search_tweet(func: alloftext(tweet, "analyze data and it in graph graphdb")) { tweet } } ``` -------------------------------- ### Querying Dgraph with alloftext (GraphQL) - Example 2 Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/advanced-text-search This query demonstrates the `alloftext` function in Dgraph's GraphQL+- query language. It searches for tweets where the `tweet` predicate contains all the specified tokens, regardless of their order. This example uses the search string "data and data analyze it graphdb in", showing that reordering terms doesn't affect the result. ```graphql { search_tweet(func: alloftext(tweet, "data and data analyze it graphdb in")) { tweet } } ``` -------------------------------- ### Create React App Project Source: https://docs.hypermode.com/dgraph/guides/to-do-app/ui Command to initialize a new React project using `create-react-app`. ```sh npx create-react-app todo-react-app ``` -------------------------------- ### Install Dgraph with Custom Helm Values (Ingress) - sh Source: https://docs.hypermode.com/dgraph/self-managed/ha-cluster Installs Dgraph using Helm, applying service configurations defined in a custom values file, typically used for Ingress setups. ```sh helm install dgraph/dgraph --values .yaml ``` -------------------------------- ### Running Python Data Population Script Source: https://docs.hypermode.com/getting-started-with-hyper-commerce This command executes the Python script `ecommerce_populate.py` to upload your prepared CSV data into the Hypermode project's collections. ```sh python3 ecommerce_populate.py ``` -------------------------------- ### Install Dgraph with Custom Helm Values (LoadBalancer) - sh Source: https://docs.hypermode.com/dgraph/self-managed/ha-cluster Installs Dgraph using Helm, applying service configurations defined in a custom values file, typically used for private LoadBalancer setups. ```sh helm install dgraph/dgraph --values .yaml ``` -------------------------------- ### Using uint64 Merge Operator in Go Source: https://docs.hypermode.com/badger/quickstart Shows how to use Badger's merge operator with the uint64 addition functions. It initializes the operator, adds uint64 values (1, 2, 3) after converting them to byte slices, and retrieves the merged result using `Get()`. The expected result is 6, encoded as a byte slice. ```go key := []byte("merge") m := db.GetMergeOperator(key, add, 200*time.Millisecond) defer m.Stop() m.Add(uint64ToBytes(1)) m.Add(uint64ToBytes(2)) m.Add(uint64ToBytes(3)) res, _ := m.Get() // res should have value 6 encoded ``` -------------------------------- ### Running Dgraph Bulk Loader with Encryption Options Source: https://docs.hypermode.com/dgraph/admin/bulk-loader These examples demonstrate how to use the `dgraph bulk` command with encryption flags. The first example uses a key file specified by `--encryption key-file`. The second example uses HashiCorp Vault for key retrieval via the `vault_*` options. Both examples show how to handle encrypted input (`--encrypted="true"`) and generate unencrypted output (`--encrypted_out="false"`). ```sh # Encryption Key from the file path dgraph bulk --files "" --schema "" --zero "" \ --encrypted="true" --encrypted_out="false" \ --encryption key-file="" # Encryption Key from HashiCorp Vault dgraph bulk --files "" --schema "" --zero "" \ --encrypted="true" --encrypted_out="false" \ --vault addr="http://localhost:8200";enc-field="enc_key";enc-format="raw";path="secret/data/dgraph/alpha";role-id-file="./role_id";secret-id-file="./secret_id" ``` -------------------------------- ### Install Golang Migrate Utility (sh) Source: https://docs.hypermode.com/modus/search Installs the golang-migrate command-line utility on MacOS using Homebrew. This tool is used for applying database migrations. ```sh brew install golang-migrate ``` -------------------------------- ### Running Data Seeding Script (Shell) Source: https://docs.hypermode.com/getting-started-with-hyper-commerce Executes the `ecommerce_populate.py` Python script using the `python3` interpreter. This script populates the Hypermode project with data from a CSV file. ```Shell python3 ecommerce_populate.py ``` -------------------------------- ### Initialize New Modus App Source: https://docs.hypermode.com/modus/quickstart Runs the Modus CLI command to create a new Modus application directory, prompting the user to select a language (Go or AssemblyScript) and optionally initialize a Git repository. ```sh modus new ``` -------------------------------- ### Example Output for Getting User Information in Dgraph JSON Source: https://docs.hypermode.com/dgraph/enterprise/access-control-lists Shows the expected JSON output from the GraphQL query to get a user by name, displaying the user's name and the list of groups they are a member of. ```json { "data": { "getUser": { "name": "alice", "groups": [ { "name": "dev" } ] } } } ``` -------------------------------- ### Install Modus CLI (npm) Source: https://docs.hypermode.com/modus/quickstart Installs the Modus command-line interface globally using npm, providing essential tools for creating, building, and running Modus applications. ```sh npm install -g @hypermode/modus-cli ``` -------------------------------- ### Configuring and Running Badger Stream (Go) Source: https://docs.hypermode.com/badger/quickstart Demonstrates how to initialize and configure a Badger Stream for concurrent iteration. It shows setting the number of goroutines, key prefix, log prefix, custom key selection (ChooseKey), custom key-value conversion (KeyToList), and defining the serial Send function before orchestrating the stream. ```go stream := db.NewStream() // db.NewStreamAt(readTs) for managed mode. // -- Optional settings stream.NumGo = 16 // Set number of goroutines to use for iteration. stream.Prefix = []byte("some-prefix") // Leave nil for iteration over the whole DB. stream.LogPrefix = "Badger.Streaming" // For identifying stream logs. Outputs to Logger. // ChooseKey is called concurrently for every key. If left nil, assumes true by default. stream.ChooseKey = func(item *badger.Item) bool { return bytes.HasSuffix(item.Key(), []byte("er")) } // KeyToList is called concurrently for chosen keys. This can be used to convert // Badger data into custom key-values. If nil, uses stream.ToList, a default // implementation, which picks all valid key-values. stream.KeyToList = nil // -- End of optional settings. // Send is called serially, while Stream.Orchestrate is running. stream.Send = func(list *pb.KVList) error { return proto.MarshalText(w, list) // Write to w. } // Run the stream if err := stream.Orchestrate(context.Background()); err != nil { return err } // Done. ``` -------------------------------- ### Example YAML Config (kebab-case) Source: https://docs.hypermode.com/dgraph/self-managed/config Provides a full example of a YAML configuration file (`config.yml`) using kebab-case for option names. ```yaml badger: compression: zstd:1 trace: jaeger: http://jaeger:14268 security: whitelist: 10.0.0.0/8,172.0.0.0/8,192.168.0.0/16 tls: ca-cert: /dgraph/tls/ca.crt client-auth-type: REQUIREANDVERIFY server-cert: /dgraph/tls/node.crt server-key: /dgraph/tls/node.key use-system-ca: true internal-port: true client-cert: /dgraph/tls/client.dgraphuser.crt client-key: /dgraph/tls/client.dgraphuser.key ``` -------------------------------- ### Add Data with GraphQL Mutation Source: https://docs.hypermode.com/dgraph/graphql/quickstart This GraphQL mutation adds sample Product and Customer data to the Dgraph database using the auto-generated add mutations. It demonstrates how to populate the database after deploying the schema. ```graphql mutation { addProduct( input: [ { name: "GraphQL on Dgraph" } { name: "Dgraph: The GraphQL Database" } ] ) { product { productID name } } addCustomer(input: [{ username: "Michael" }]) { customer { username } } } ``` -------------------------------- ### Example Output for Getting Group Information in Dgraph JSON Source: https://docs.hypermode.com/dgraph/enterprise/access-control-lists Shows the expected JSON output from the GraphQL query to get a group by name, displaying the group's name, the list of users in the group, and its ACL rules with permission levels and predicates. ```json { "data": { "getGroup": { "name": "dev", "users": [ { "name": "alice" } ], "rules": [ { "permission": 7, "predicate": "friend" }, { "permission": 7, "predicate": "~friend" } ] } } } ``` -------------------------------- ### Performing case-insensitive regex search with prefix in Dgraph Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/advanced-text-search Modifies the case-insensitive regex query to match only hashtags that start with "graph" using the pattern `^graph.*$/i`. This demonstrates how to refine regex patterns for more specific searches. ```GraphQL { reg_search(func: regexp(hashtag, /^graph.*$/i)) { hashtag } } ``` -------------------------------- ### Querying with Recursive Traversal in Dgraph (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/basic-operations This GraphQL query performs a recursive traversal starting from the node identified by MICHAELS_UID. It uses the @recurse directive with a depth of 4 to traverse relationships up to four levels deep, retrieving the name, age, and follows predicates at each level. ```graphql { find_follower(func: uid(MICHAELS_UID)) @recurse(depth: 4) { name age follows } } ``` -------------------------------- ### Example JSON Config (kebab-case) Source: https://docs.hypermode.com/dgraph/self-managed/config Provides a full example of a JSON configuration file (`config.json`) using kebab-case for option names. ```json { "badger": { "compression": "zstd:1" }, "trace": { "jaeger": "http://jaeger:14268" }, "security": { "whitelist": "10.0.0.0/8,172.0.0.0/8,192.168.0.0/16" }, "tls": { "ca-cert": "/dgraph/tls/ca.crt", "client-auth-type": "REQUIREANDVERIFY", "server-cert": "/dgraph/tls/node.crt", "server-key": "/dgraph/tls/node.key", "use-system-ca": true, "internal-port": true, "client-cert": "/dgraph/tls/client.dgraphuser.crt", "client-key": "/dgraph/tls/client.dgraphuser.key" } } ``` -------------------------------- ### BadgerDB CLI Backup - Shell Source: https://docs.hypermode.com/badger/quickstart Creates a version-agnostic backup of the BadgerDB database located at the specified directory to a file named 'badger.bak' in the current working directory using the standard 'badger' CLI tool. ```sh badger backup --dir ``` -------------------------------- ### Single-Level Edge Traversal in Dgraph (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/basic-operations Shows a basic GraphQL query in Dgraph to traverse a single level of the graph. It starts from a root node identified by its UID (`MICHAELS_UID`) and traverses the `follows` edge, returning specified predicates (`name`, `age`) for the connected nodes. ```graphql { find_follower(func: uid(MICHAELS_UID)){ name age follows { name age } } } ``` -------------------------------- ### Verify Kubernetes Nodes (Shell) Source: https://docs.hypermode.com/dgraph/self-managed/single-server-cluster Checks the status of nodes in the Kubernetes cluster to ensure access before installing Dgraph. ```sh kubectl get nodes ``` -------------------------------- ### Multi-Level Edge Traversal (4 Levels) in Dgraph (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/basic-operations Demonstrates a four-level deep traversal query in Dgraph. It recursively traverses the `follows` edge four times starting from the root node (`MICHAELS_UID`), returning specified predicates at each level to explore deeper connections in the graph. ```graphql { find_follower(func: uid(MICHAELS_UID)) { name age follows { name age follows { name age follows { name age } } } } } ``` -------------------------------- ### Multi-Level Edge Traversal (3 Levels) in Dgraph (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/basic-operations Extends the single-level traversal query to explore the graph three levels deep. It starts from the root node (`MICHAELS_UID`), traverses the `follows` edge, and then recursively traverses the `follows` edge again from the resulting nodes, returning specified predicates at each level. ```graphql { find_follower(func: uid(MICHAELS_UID)) { name age follows { name age follows { name age } } } } ``` -------------------------------- ### Build and Run Modus App Locally Source: https://docs.hypermode.com/modus/quickstart Navigates into the newly created app directory and executes the Modus CLI command to build and run the application in development mode, making it accessible locally. ```sh modus dev ``` -------------------------------- ### Get Host IP Address using Shell Source: https://docs.hypermode.com/dgraph/self-managed/single-host-setup Commands to find the IP address of the host machine. Use `ip addr` on Arch Linux or `ifconfig` on Ubuntu/Mac. ```sh ip addr # On Arch Linux ifconfig # On Ubuntu/Mac ``` -------------------------------- ### lsbackup Standard Output Example Source: https://docs.hypermode.com/dgraph/enterprise/lsbackup Provides an example of the default JSON output from the `lsbackup` command when the `--verbose` flag is not used, showing key information about a backup. ```json [ { "path": "/home/user/Dgraph/20.11/backup/manifest.json", "since": 30005, "backup_id": "reverent_vaughan0", "backup_num": 1, "encrypted": false, "type": "full" } ] ``` -------------------------------- ### Dgraph Custom Configuration File (YAML) Source: https://docs.hypermode.com/dgraph/self-managed/ha-cluster Example YAML file demonstrating how to define custom configuration settings for Dgraph Alpha and Zero servers. ```yaml # .yaml alpha: configFile: config.yaml: | alsologtostderr: true badger: compression_level: 3 tables: mmap vlog: mmap postings: /dgraph/data/p wal: /dgraph/data/w zero: configFile: config.yaml: | alsologtostderr: true wal: /dgraph/data/zw ``` -------------------------------- ### Setup Apollo Client in React App Source: https://docs.hypermode.com/dgraph/guides/to-do-app/ui Configures and initializes the Apollo Client with an HTTP link pointing to the GraphQL API endpoint and wraps the main App component with ApolloProvider. ```javascript import React from "react" import ApolloClient from "apollo-client" import { InMemoryCache } from "apollo-cache-inmemory" import { ApolloProvider } from "@apollo/react-hooks" import { createHttpLink } from "apollo-link-http" import "./App.css" const createApolloClient = () => { const httpLink = createHttpLink({ uri: "http://localhost:8080/graphql", options: { reconnect: true, }, }) return new ApolloClient({ link: httpLink, cache: new InMemoryCache(), }) } const App = () => { const client = createApolloClient() return (

todos

) } export default App ``` -------------------------------- ### Generated GraphQL Queries for Post Type Source: https://docs.hypermode.com/dgraph/graphql/query/overview Examples of the three types of GraphQL queries automatically generated by Dgraph for the 'Post' type: get (by ID), query (with filters/pagination), and aggregate. ```graphql getPost(postID: ID!): Post queryPost(filter: PostFilter, order: PostOrder, first: Int, offset: Int): [Post] aggregatePost(filter: PostFilter): PostAggregateResult ``` -------------------------------- ### Launch Ratel UI Container using Docker Source: https://docs.hypermode.com/dgraph/self-managed/single-host-setup Starts the Ratel UI for Dgraph in a Docker container, mapping port 8000. This allows accessing the Dgraph UI via localhost:8000. ```sh docker run --name ratel -d -p "8000:8000" dgraph/ratel:latest ``` -------------------------------- ### Setting User Metadata on Key in Go Source: https://docs.hypermode.com/badger/quickstart Shows how to attach a single byte of user metadata to a key-value pair in Badger DB. It creates a new `Entry` for the key "answer" and value "42", adds metadata byte `1` using `WithMeta()`, and saves the entry within an update transaction using `Txn.SetEntry()`. ```go err := db.Update(func(txn *badger.Txn) error { e := badger.NewEntry([]byte("answer"), []byte("42")).WithMeta(byte(1)) err := txn.SetEntry(e) return err }) ``` -------------------------------- ### Querying User with Posts Traversal - GraphQL Source: https://docs.hypermode.com/dgraph/guides/message-board-app/graphql/react-graphql-queries This query finds `User1` as the starting point, grabs the `username` and `displayName`, and then traverses into the graph following the `posts` edges to get the titles of all the user's posts. ```graphql query { getUser(username: "User1") { username displayName posts { title } } } ``` -------------------------------- ### BadgerDB CLI Restore - Shell Source: https://docs.hypermode.com/badger/quickstart Restores a backup file named 'badger.bak' from the current working directory to a new BadgerDB database located at the specified directory using the standard 'badger' CLI tool. ```sh badger restore --dir ``` -------------------------------- ### Querying All Tags in Dgraph (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/types-and-operations This query uses the `has` function to find all nodes in the database that possess the `tag_name` predicate. It then retrieves the `tag_name` for each of these nodes, effectively listing all existing tags. ```GraphQL { all_tags(func: has(tag_name)) { tag_name } } ``` -------------------------------- ### Iterating Over All Keys in Go Source: https://docs.hypermode.com/badger/quickstart Demonstrates how to iterate over all key-value pairs in Badger DB using an iterator within a read-only transaction. It obtains an iterator with default options (adjusting prefetch size), rewinds to the beginning, and loops through valid items using `Valid()` and `Next()`. Inside the loop, it retrieves the key and value for each item. ```go err := db.View(func(txn *badger.Txn) error { opts := badger.DefaultIteratorOptions opts.PrefetchSize = 10 it := txn.NewIterator(opts) defer it.Close() for it.Rewind(); it.Valid(); it.Next() { item := it.Item() k := item.Key() err := item.Value(func(v []byte) error { fmt.Printf("key=%s, value=%s\n", k, v) return nil }) if err != nil { return err } } return nil }) ``` -------------------------------- ### Configure Frontend Environment Variables (env) Source: https://docs.hypermode.com/getting-started-with-hyper-commerce Add the necessary Hypermode API token and endpoint to the frontend's local environment configuration file (`.env.local`). These values are required for the frontend to communicate with the Hypermode backend services. ```env HYPERMODE_API_TOKEN = YOUR_API_TOKEN HYPERMODE_API_ENDPOINT = YOUR_API_ENDPOINT ``` -------------------------------- ### Querying all hashtags using has() in Dgraph Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/advanced-text-search Demonstrates how to use the `has()` function in Dgraph to retrieve all nodes that have the 'hashtag' predicate. This is used to show the initial data before applying regex filters. ```GraphQL { hash_tags(func: has(hashtag)) { hashtag } } ``` -------------------------------- ### Periodically Running Badger Value Log GC (Go) Source: https://docs.hypermode.com/badger/quickstart Provides a recommended pattern for performing online value log garbage collection in Badger. It uses a time ticker to periodically call `db.RunValueLogGC(0.7)` and includes a goto loop to immediately retry the GC process if a successful run occurs, maximizing space reclamation. ```go ticker := time.NewTicker(5 * time.Minute) defer ticker.Stop() for range ticker.C { again: err := db.RunValueLogGC(0.7) if err == nil { goto again } } ``` -------------------------------- ### Helm Values for Ingress Configuration - yaml Source: https://docs.hypermode.com/dgraph/self-managed/ha-cluster Example Helm values file configuring global ingress settings for Dgraph, specifying the ingress class and hostnames for Alpha and Ratel services. ```yaml # .yaml global: ingress: enabled: false annotations: kubernetes.io/ingress.class: nginx ratel_hostname: "ratel." alpha_hostname: "alpha." ``` -------------------------------- ### Querying All User Names in Dgraph (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/fuzzy-search This GraphQL query retrieves all nodes that have the `user_name` predicate and selects the `user_name` value for each. It is used to list existing user names before demonstrating fuzzy search. ```GraphQL { names(func: has(user_name)) { user_name } } ``` -------------------------------- ### lsbackup Verbose Output Example Source: https://docs.hypermode.com/dgraph/enterprise/lsbackup Shows an example of the JSON output when the `--verbose` flag is enabled, including additional details such as the `groups` field which maps groups to predicates. ```json [ { "path": "/home/user/Dgraph/20.11/backup/manifest.json", "since": 30005, "backup_id": "reverent_vaughan0", "backup_num": 1, "encrypted": false, "type": "full", "groups": { "1": [ "dgraph.graphql.schema_created_at", "dgraph.graphql.xid", "dgraph.drop.op", "dgraph.type", "dgraph.cors", "dgraph.graphql.schema_history", "score", "dgraph.graphql.p_query", "dgraph.graphql.schema", "dgraph.graphql.p_sha256hash", "series" ] } } ] ``` -------------------------------- ### BadgerDB v0.8 Backup Tool - Shell Source: https://docs.hypermode.com/badger/quickstart Uses the 'badger_backup' tool provided in BadgerDB v0.8.1 to create a backup file. This is recommended for users with databases created using v0.8 or below before restoring with the latest 'badger' tool to upgrade. ```sh badger_backup --dir --backup-file badger.bak ``` -------------------------------- ### Verifying Updated Predicate by UID (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/basic-operations This GraphQL query is used to confirm that the 'age' predicate of the node identified by `MICHAELS_UID` has been successfully updated. It fetches the 'name' and 'age' predicates for the specified node. ```graphql { find_using_uid(func: uid(MICHAELS_UID)){ name age } } ``` -------------------------------- ### Querying Authors and Blogs in Dgraph (GraphQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/types-and-operations This query retrieves authors with a rating of 4.0 or higher. It then traverses the `published` edge from these authors to fetch associated blog posts, including their title, content, and dislikes. ```GraphQL { authors_and_ratings(func: ge(rating, 4.0)) { uid author_name rating published { title content dislikes } } } ``` -------------------------------- ### Saving Key/Value with Txn.SetEntry and Entry Object in Badger Go Source: https://docs.hypermode.com/badger/quickstart Illustrates an alternative method to save a key/value pair by first creating a `badger.Entry` object and then using `txn.SetEntry`. This allows setting additional properties on the entry. ```Go err := db.Update(func(txn *badger.Txn) error { e := badger.NewEntry([]byte("answer"), []byte("42")) err := txn.SetEntry(e) return err }) ``` -------------------------------- ### Example Model Input Parameters (JSON) Source: https://docs.hypermode.com/quickstart Illustrates the JSON structure used for input parameters when invoking a chat model like Meta Llama 3.2-3B-Instruct within Hypermode, including system and user messages, max tokens, and temperature. ```json { "model": "meta-llama/Llama-3.2-3B-Instruct", "messages": [ { "role": "system", "content": "You are a helpful assistant. Limit your answers to 150 words." }, { "role": "user", "content": "How are black holes created?" } ], "max_tokens": 200, "temperature": 0.7 } ``` -------------------------------- ### Querying all authors and ratings (DQL) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/types-and-operations This DQL query retrieves all nodes that possess the `author_name` predicate. It selects the `uid`, `author_name`, and `rating` predicates for each matching node, demonstrating a basic query using the `has()` function. ```dql { authors_and_ratings(func: has(author_name)) { uid author_name rating } } ``` -------------------------------- ### Configuring Hypermode Frontend Environment Variables Source: https://docs.hypermode.com/getting-started-with-hyper-commerce This shell snippet shows how to create a `.env.local` file to store the Hypermode API token and endpoint URL for the frontend application. Replace `YOUR_API_TOKEN` and `YOUR_API_ENDPOINT` with your actual credentials obtained from the Hypermode console. ```sh HYPERMODE_API_TOKEN=YOUR_API_TOKEN HYPERMODE_API_ENDPOINT=YOUR_API_ENDPOINT ``` -------------------------------- ### Querying Nodes with has Function (Dgraph Query) Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/introduction Dgraph query using the `has` function to retrieve all nodes that have a "name" predicate. Selects the "name" and "age" predicates for the results to be displayed. ```sh { people(func: has(name)) { name age } } ``` -------------------------------- ### Helm Values for Private LoadBalancer (AWS) - yaml Source: https://docs.hypermode.com/dgraph/self-managed/ha-cluster Example Helm values file configuring Alpha and Ratel services to use a LoadBalancer with an AWS annotation for creating an internal (private) load balancer. ```yaml # .yaml alpha: service: type: LoadBalancer annotations: service.beta.kubernetes.io/aws-load-balancer-internal: "true" ratel: service: type: LoadBalancer annotations: service.beta.kubernetes.io/aws-load-balancer-internal: "true" ``` -------------------------------- ### Link Modus App to Hypermode (Shell) Source: https://docs.hypermode.com/quickstart Links a local Modus application to Hypermode via the CLI. This command creates a new Hypermode project and deploys the application. ```sh hyp link ``` -------------------------------- ### Running React App Boilerplate (Shell) Source: https://docs.hypermode.com/dgraph/guides/message-board-app/react-ui/react-app-boiler-plate Installs project dependencies using yarn and then starts the React development server. This command builds the source and serves the app UI in development mode, typically at http://localhost:3000. ```sh yarn install yarn start ``` -------------------------------- ### lsbackup MinIO Example Source: https://docs.hypermode.com/dgraph/enterprise/lsbackup Demonstrates how to use `lsbackup` to list backups stored in a MinIO bucket by providing the MinIO URI as the location. ```sh dgraph lsbackup -l minio://localhost:9000/dgraph_backup ``` -------------------------------- ### Iterating Over Key Prefix in Go Source: https://docs.hypermode.com/badger/quickstart Shows how to perform a prefix scan in Badger DB using an iterator. It obtains an iterator, seeks to the specified prefix ("1234"), and then iterates through all valid items that have that prefix using `ValidForPrefix()` and `Next()`. For each matching item, it retrieves and prints the key and value. ```go db.View(func(txn *badger.Txn) error { it := txn.NewIterator(badger.DefaultIteratorOptions) defer it.Close() prefix := []byte("1234") for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() { item := it.Item() k := item.Key() err := item.Value(func(v []byte) error { fmt.Printf("key=%s, value=%s\n", k, v) return nil }) if err != nil { return err } } return nil }) ``` -------------------------------- ### Install Badger v1.6.0 for Migration Backup Source: https://docs.hypermode.com/badger/troubleshooting Navigates to the Badger source directory, checks out the v1.6.0 tag, and installs the binary to prepare for creating a backup in the old format. ```Shell cd $GOPATH/src/github.com/dgraph-io/badger ``` ```Shell git checkout v1.6.0 ``` ```Shell cd badger && go install ``` -------------------------------- ### Attempting Reverse Edge Traversal (No Index) in Dgraph GraphQL Source: https://docs.hypermode.com/dgraph/guides/get-started-with-dgraph/types-and-operations Attempts to traverse the `tagged` edge in reverse using the `~` prefix. This query is shown to fail because reverse traversals in Dgraph require a `reverse` index to be added to the predicate. ```GraphQL { devrel_tag(func: eq(tag_name,"devrel")) { tag_name ~tagged { title content } } } ```