Skip to content

Python SDK guide

This topic introduces how to set up the Python SDK to connect to NebulaGraph and perform simple queries.

Prerequisites

Connection information is obtained from NebulaGraph Cloud. For more information, see Connect to your database.

Steps

  1. Log in to NebulaGraph Cloud and download the python SDK package, for example, nebulagraph_python-5.0.0a1-py3-none-any.whl.

  2. Install the Python SDK. Example:

    pip install nebulagraph_python-5.0.0a1-py3-none-any.whl
    
  3. Use the SDK to NebulaGraph and perform queries as follows:

    from nebulagraph_python.client import NebulaClient
    
    # Create client
    client = NebulaClient(
        hosts=["<host>:<port>"],
        username="<username>",
        password="<password>",
    )
    
    query = """
        RETURN 1 AS a, 2 AS b
    """
    # Execute query
    result = client.execute(query)
    

    Replace <host>:<port>, <username>, and <password> with the actual connection information obtained from NebulaGraph Cloud.

  4. To inspect the query result, refer to the following methods:

    • Print the result in table style

      result.print()
      

      Return:

      ╔═══╤═══╗
      ║      ║
      ║ a  b ║
      ║      ║
      ╟───┼───╢
      ║      ║
      ║ 1  2 ║
      ║      ║
      ╚═══╧═══╝
      
      Summary
      ├── Rows: 1
      └── Latency: 1450μs  
      
    • Retrieve specific values from the query set

      # Get one row
      row = result.one()
      
      # Get one value
      cell = row["a"].cast_primitive()
      
      # Print its value
      print(cell, type(cell))  
      

      Return:

      1 <class 'int'>
      
    • Retrieve primitive values from the result set

      print(result.as_primitive_by_column())
      print(list(result.as_primitive_by_row()))
      

      Return:

      {'a': [1], 'b': [2]}
      [{'a': 1, 'b': 2}]
      
    • Retrieve a Pandas DataFrame from the query set

      result = client.execute(query)
      df = result.as_pandas_df()
      

      Return:

         a  b
      0  1  2
      

More information