<jupyter_start><jupyter_text>环境<jupyter_code>!pip install pydgraph
import requests
import json
import time
import pprint
import pydgraph

headers = {
    'Content-Type': 'application/json',
}

URL_PREFIX = 'http://localhost'
PORT_RATEL_HTTP = 8008
PORT_ALPHA_HTTP = 8088
PORT_ALPHA_GRPC = 9088

URL_PREFIX_GRAPHQL = URL_PREFIX + ':{port}/graphql'.format(
    port=PORT_ALPHA_HTTP)
URL_PREFIX_GRAPHQL_ADMIN = URL_PREFIX + ':{port}/admin'.format(
    port=PORT_ALPHA_HTTP)
print(URL_PREFIX_GRAPHQL)
print(URL_PREFIX_GRAPHQL_ADMIN)<jupyter_output>http://localhost:8088/graphql
http://localhost:8088/admin<jupyter_text>/graphql, /admin `/admin`:- The  `health` query lets you know if everything is connected and if there’s a schema currently being served at /graphql.- The `state` query returns the current state of the cluster and group membership information. For more information about state see here.- The `config` query returns the configuration options of the cluster set at the time of starting it.- The `getGQLSchema` query gets the current GraphQL schema served at /graphql, or returns null if there’s no such schema.- The `getAllowedCORSOrigins` query returns your CORS policy.- The `updateGQLSchema` mutation allows you to change the schema currently served at /graphql.  Query schema<jupyter_code>url = URL_PREFIX_GRAPHQL_ADMIN
print(url)

query = """
query {
  queryCustomer(filter: {username: {regexp: "/Mich.*/"}}) {
    username
    reviews(order: {asc: rating}, first: 5) {
      comment
      rating
      about {
        name
      }
    }
  }
}
"""
params = {
    'query': query
}

r = requests.get(url, params=params)
print(r)
pprint.pprint(r.json())
url = URL_PREFIX_GRAPHQL_ADMIN
print(url)

query = """
query {
          querySchemaHistory ( first : 10 ){
              schema
              created_at
           }
}
"""
params = {
    'query': query
}

r = requests.get(url, params=params)
print(r)
pprint.pprint(r.json())<jupyter_output>http://localhost:8088/admin
<Response [200]>
{'data': {'querySchemaHistory': []},
 'extensions': {'tracing': {'duration': 5522600,
                            'endTime': '2021-02-03T10:37:29.0208931Z',
                            'execution': {'resolvers': [{'dgraph': [{'duration': 5207300,
                                                                     'label': 'query',
                                                                     'startOffset': 243100}],
                                                         'duration': 5321400,
                                                         'fieldName': 'querySchemaHistory',
                                                         'parentType': 'Query',
                                                         'path': ['querySchemaHistory'],
                                                         'returnType': '[SchemaHistory]',
                                                         'startOffset': 180400}]},
               [...]<jupyter_text>Validate schema<jupyter_code>url = URL_PREFIX_GRAPHQL_ADMIN + '/schema/validate'
print(url)

schema = """
type Product {
    productID: ID!
    name: String @search(by: [term])
    reviews: [Review] @hasInverse(field: about)
}

type Customer {
    username: String! @id @search(by: [hash, regexp])
    reviews: [Review] @hasInverse(field: by)
}

type Review {
    id: ID!
    about: Product!
    by: Customer!
    comment: String @search(by: [fulltext])
    rating: Int @search
}
"""

r = requests.post(url, data=schema)
print(r)
pprint.pprint(r.json())<jupyter_output>http://localhost:8088/admin/schema/validate
<Response [200]>
{'errors': [{'extensions': {'code': 'success'}, 'message': 'Schema is valid'}]}<jupyter_text>Create schema  post schema file<jupyter_code>url = URL_PREFIX_GRAPHQL_ADMIN + '/schema'
print(url)

schema = """
type Product {
    productID: ID!
    name: String @search(by: [term])
    reviews: [Review] @hasInverse(field: about)
}

type Customer {
    username: String! @id @search(by: [hash, regexp])
    reviews: [Review] @hasInverse(field: by)
}

type Review {
    id: ID!
    about: Product!
    by: Customer!
    comment: String @search(by: [fulltext])
    rating: Int @search
}
"""
print(schema)

schema_content = schema.replace('\n', ' ')
print('|'+schema_content+'|')

files = {
    'file': ('products.graphql', schema_content, 'application/x-www-form-urlencoded'),
}
r = requests.post(url, files=files)
print(r.text)

print(r)
pprint.pprint(r.json())<jupyter_output>http://localhost:8088/admin/schema

type Product {
    productID: ID!
    name: String @search(by: [term])
    reviews: [Review] @hasInverse(field: about)
}

type Customer {
    username: String! @id @search(by: [hash, regexp])
    reviews: [Review] @hasInverse(field: by)
}

type Review {
    id: ID!
    about: Product!
    by: Customer!
    comment: String @search(by: [fulltext])
    rating: Int @search
}

| type Product {     productID: ID!     name: String @search(by: [term])     reviews: [Review] @hasInverse(field: about) }  type Customer {     username: String! @id @search(by: [hash, regexp])     reviews: [Review] @hasInverse(field: by) }  type Review {     id: ID!     about: Product!     by: Customer!     comment: String @search(by: [fulltext])     rating: Int @search } |
{"errors":[{"message":"resolving updateGQLSchema failed because input:1: Unexpected \u003cInvalid\u003e\n (Locations: [{Line: 3, Column: 4}])","extensions":{"code":"Error"}}]}
<Response [200]>
{'errors': [{'exte[...]<jupyter_text>updateGQLSchema<jupyter_code>url = URL_PREFIX_GRAPHQL_ADMIN
print(url)

schema = """
 type Product {
    productID: ID!
    name: String @search(by: [term])
    reviews: [Review] @hasInverse(field: about)
}

 type Customer {
    username: String! @id @search(by: [hash, regexp])
    reviews: [Review] @hasInverse(field: by)
}

 type Review {
    id: ID!
    about: Product!
    by: Customer!
    comment: String @search(by: [fulltext])
    rating: Int @search
}
"""
print(schema)

schema_content = schema.replace('\n', '')
print(schema_content)
print()
mutation = """
mutation {
  updateGQLSchema( input: { set: { schema: """ + '"' + schema_content + '"' + """}})
  {
    gqlSchema {
      schema
      generatedSchema
    }
  }
}
""".replace('\n', '')

print(mutation)
print()

params = {}
data = {
    'query': mutation,
   # """mutation {  updateGQLSchema(    input: { set: { schema: "type Product {  productID: ID!  name: String @search(by: [term]) reviews: [Review] @hasInverse(field: about)}  type Customer { username: String! @id @search(by: [hash, regexp]) reviews: [Review] @hasInverse(field: by)}  type Review { id: ID! about: Product! by: Customer! comment: String @search(by: [fulltext]) rating: Int @search}"}})  {    gqlSchema {      schema      generatedSchema    }  }}"""
}
r = requests.post(url, headers=headers, params=params, data=json.dumps(data))

print(r)
pprint.pprint(r.json())<jupyter_output>http://localhost:8088/admin

 type Product {
    productID: ID!
    name: String @search(by: [term])
    reviews: [Review] @hasInverse(field: about)
}

 type Customer {
    username: String! @id @search(by: [hash, regexp])
    reviews: [Review] @hasInverse(field: by)
}

 type Review {
    id: ID!
    about: Product!
    by: Customer!
    comment: String @search(by: [fulltext])
    rating: Int @search
}

 type Product {    productID: ID!    name: String @search(by: [term])    reviews: [Review] @hasInverse(field: about)} type Customer {    username: String! @id @search(by: [hash, regexp])    reviews: [Review] @hasInverse(field: by)} type Review {    id: ID!    about: Product!    by: Customer!    comment: String @search(by: [fulltext])    rating: Int @search}


mutation {
  updateGQLSchema( input: { set: { schema: " type Product {    productID: ID!    name: String @search(by: [term])    reviews: [Review] @hasInverse(field: about)} type Customer {    username: String! @id @search(by: [hash[...]<jupyter_text>Dgraph Python Clinet- https://dgraph.io/docs/clients/python/  Create client<jupyter_code>client_stub = pydgraph.DgraphClientStub('localhost:{port}'.format(port=PORT_ALPHA_GRPC))
client = pydgraph.DgraphClient(client_stub)
dir(client)<jupyter_output><empty_output><jupyter_text>Add schema<jupyter_code>schema = """name: string @index(exact) ."""

op = pydgraph.Operation(schema=schema)
client.alter(op)<jupyter_output><jupyter_text>Mutation<jupyter_code>p = {
    'name': 'Alice',
}

txn = client.txn()
try:
    txn.mutate(set_obj=p)
    txn.commit()
finally:
    txn.discard()<jupyter_output><empty_output><jupyter_text>Query<jupyter_code>query = """query all($a: string)
{
    all(func: eq(name, $a))
    {
        uid
    }
}"""
variables = {'$a': 'Alice'}

txn = client.txn(read_only=True)
try:
    res = txn.query(query,variables=variables)
    ppl = json.loads(res.json)
    pprint.pprint(ppl)
finally:
    txn.discard()<jupyter_output>{'all': [{'uid': '0x2712'}]}<jupyter_text>Upsert<jupyter_code>query = """{
    u as var(func: eq(name, "Alice"))
}"""
nquad = """
    uid(u) <name> "Alice" .
    uid(u) <age> "25" .
"""

txn = client.txn()
try:
    mutation = txn.create_mutation(set_nquads=nquad)
    request = txn.create_request(query=query,
                                 mutations=[mutation],
                                 commit_now=True)
    txn.do_request(request)
finally:
    txn.discard()<jupyter_output><empty_output><jupyter_text>Conditional upsert<jupyter_code>query = """{
    user as var(func: eq(email, "<EMAIL>"))
}"""
cond = "@if(eq(len(user), 1))"
nquads = """
    uid(user) <email> "<EMAIL>" .
"""

txn = client.txn()
try:
    mutation = txn.create_mutation(cond=cond, set_nquads=nquads)
    request = txn.create_request(mutations=[mutation],
                                 query=query,
                                 commit_now=True)
    txn.do_request(request)
finally:
    txn.discard()<jupyter_output><empty_output><jupyter_text>Close resource<jupyter_code>client_stub.close()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1496993987975952, 'fraction_numerical': 0.011923847695390781, 'mean_word_length': 3.2060682680151706, 'pattern_counts': {'":': 4, '<': 50, '<?xml version=': 0, '>': 50, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '401286', 'license': 'MIT', 'n_tokens_mistral': 3418, 'n_tokens_neox': 3338, 'n_words': 745, 'path': 'codes/dbms/dgraph/GraphQL.ipynb', 'repo_name': 'zhoujiagen/dbms-hacks', 'size': '10010'}