Skip to content

DQL Learning

DUONG Phu-Hiep edited this page Jun 4, 2022 · 8 revisions

Run dgraph

  • Dgraph Zero controls the Dgraph cluster, and stores information about it. It automatically moves data between different Dgraph Alpha instances based on the size of the data served by each Alpha instance. Before you can run dgraph alpha, you must run at least one dgraph zero node
  • Dgraph Alpha provides several HTTP endpoints for administrators, as follows:
    • /health?all
    • /admin/shutdown initiates a proper shutdown of the Alpha.

Run dgraph zero and alpha separately

# Run Dgraph zero
docker run -it -p 5080:5080 -p 6080:6080 -p 8080:8080 \
  -p 9080:9080 -p 8000:8000 -v ~/dgraph:/dgraph --name dgraph \
  dgraph/dgraph:v21.03.0 dgraph zero

# In another terminal, now run Dgraph alpha
docker exec -it dgraph dgraph alpha --cache size-mb=2048 --zero localhost:5080 --security whitelist=0.0.0.0/0

or Standalone

docker run -it -p 5080:5080 -p 6080:6080 -p 8080:8080 \
  -p 9080:9080 -p 8000:8000 -v ~/dgraph:/dgraph --name dgraph \
  dgraph/standalone:v21.03.0

image

Shutdown alpha gracefully

GET http://localhost:8080/admin/shutdown

Drop all

A. To drop all data and schema:

$ curl -X POST localhost:8080/alter -d '{"drop_all": true}'

B. To drop all data only (keep schema):

$ curl -X POST localhost:8080/alter -d '{"drop_op": "DATA"}'

Import schema

curl -X POST localhost:8080/admin/schema --data @schema.graphql

Import data

$ dgraph live -f 1million.rdf.gz --alpha localhost:9080 --zero localhost:5080 -c 1

or

$ docker exec -it dgraph dgraph live -f 1million.rdf.gz --alpha localhost:9080 --zero localhost:5080 -c 1

dgraph live

dgraph live --help
 Run Dgraph Live Loader 
Usage:
  dgraph live [flags] 

Flags:
  -a, --alpha string                 Comma-separated list of Dgraph alpha gRPC server addresses (default "127.0.0.1:9080")
  -t, --auth_token string            The auth token passed to the server for Alter operation of the schema file. If used with --slash_grpc_endpoint, then this should be set to the API token issuedby Slash GraphQL
  -b, --batch int                    Number of N-Quads to send as part of a mutation. (default 1000)
  -m, --bufferSize string            Buffer for each thread (default "100")
  -c, --conc int                     Number of concurrent requests to make to Dgraph (default 10)
      --creds string                 Various login credentials if login is required.
                                        user defines the username to login.
                                        password defines the password of the user.
                                        namespace defines the namespace to log into.
                                        Sample flag could look like --creds user=username;password=mypass;namespace=2
      --encryption string            [Enterprise Feature] Encryption At Rest options
                                         key-file=; The file that stores the symmetric key of length 16, 24, or 32 bytes.The key size determines the chosen AES cipher (AES-128, AES-192, and AES-256 respectively).
                                      (default "key-file=")
  -f, --files string                 Location of *.rdf(.gz) or *.json(.gz) file(s) to load
      --force-namespace int          Namespace onto which to load the data.Only guardian of galaxy should use this for loading data into multiple namespaces or somespecific namespace. Setting it to negative value will preserve the namespace.
      --format string                Specify file format (rdf or json) instead of getting it from filename
  -h, --help                         help for live
      --http string                  Address to serve http (pprof). (default "localhost:6060")
      --new_uids                     Ignore UIDs in load files and assign new ones.
  -s, --schema string                Location of schema file
      --slash_grpc_endpoint string   Path to Slash GraphQL GRPC endpoint. If --slash_grpc_endpoint is set, all other TLS options and connection options will beignored
      --tls string                   TLS Client options
                                         ca-cert=; The CA cert file used to verify server certificates. Required for enabling TLS.
                                         client-cert=; (Optional) The Cert file provided by the client to the server.
                                         client-key=; (Optional) The private Key file provided by the clients to the server.
                                         internal-port=false; (Optional) Enable inter-node TLS encryption between cluster nodes.
                                         server-name=; Used to verify the server hostname.
                                         use-system-ca=true; Includes System CA into CA Certs.
                                      (default "use-system-ca=true; internal-port=false;")
      --tmp string                   Directory to store temporary buffers. (default "t")
  -U, --upsertPredicate string       run in upsertPredicate mode. the value would be used to store blank nodes as an xid
  -C, --use_compression              Enable compression on connection to alpha server
      --vault string                 Vault options
                                         addr=http://localhost:8200; Vault server address (format: http://ip:port).
                                         enc-field=; Vault field containing encryption key.
                                         enc-format=base64; Encryption key format, can be 'raw' or 'base64'.
                                         path=secret/data/dgraph; Vault KV store path (e.g. 'secret/data/dgraph' for KV V2, 'kv/dgraph' for KV V1).
                                         role-id-file=; Vault RoleID file, used for AppRole authentication.
                                         secret-id-file=; Vault SecretID file, used for AppRole authentication.
                                      (default "addr=http://localhost:8200; role-id-file=; secret-id-file=; path=secret/data/dgraph; enc-field=; enc-format=base64")
      --verbose                      Run the live loader in verbose mode
  -x, --xidmap string                Directory to store xid to uid mapping
  -z, --zero string                  Dgraph zero gRPC server address (default "127.0.0.1:5080")

Global Flags:
      --alsologtostderr                  log to standard error as well as files
      --bindall                          Use 0.0.0.0 instead of localhost to bind to all addresses on local machine. (default true)
      --block_rate int                   Block profiling rate. Must be used along with block profile_mode
      --config string                    Configuration file. Takes precedence over default values, but is overridden to values set with environment variables and flags.
      --cwd string                       Change working directory to the path specified. The parent must exist.
      --expose_trace                     Allow trace endpoint to be accessible from remote
      --log_backtrace_at traceLocation   when logging hits line file:N, emit a stack trace (default :0)
      --log_dir string                   If non-empty, write log files in this directory
      --logtostderr                      log to standard error instead of files
      --profile_mode string              Enable profiling mode, one of [cpu, mem, mutex, block]
  -v, --v Level                          log level for V logs
      --vmodule moduleSpec               comma-separated list of pattern=N settings for file-filtered logging

Sample DQL

{
  q(func: allofterms(name@., "Michael")) {
    name
    age
    friend(orderasc: age, offset: 1, first: 2) @filter(ge(age, 27) AND le(age, 48)) {
      name@.
      age
    }
    count(friend) @filter(between(age, 27, 48))
  }
}

{
  lots_of_friends(func: ge(count(friend), 2)) {
    name@.
    age
    friend {
      name@.
    }
  }
}

The @normalize directive

  • returns only edges listed with an alias, and
  • flattens the result to remove nesting
{
  michael_and_pet_name(func: allofterms(name@., "Michael")) @normalize {
    name: name
    age   # this wont come out because there is no alias
    friend {
      friend_name: name
    }
  }
}

Facets

$ curl -sH "Content-Type: application/rdf" "localhost:8080/mutate?commitNow=true" -XPOST -d $'
{
  set {
    # -- Facets on scalar predicates
    _:alice <name> "Alice" .
    _:alice <mobile> "040123456" (since=2006-01-02T15:04:05) .
    _:alice <car> "MA0123" (since=2006-02-02T13:01:09, first=true) .
  }
} | python -m json.tool

Set data with json

{
    "set": [
        {
            "uid": "_:company1",
            "industry": "Machinery",
            "dgraph.type": "Company",
            "name": "CompanyABC"
        }
    ]
}