### Install NebulaGraph Python Client Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Installs the nebula3-python package using pip. ```python %pip install nebula3-python ``` -------------------------------- ### Explore Query Results (DataFrame) Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Demonstrates how to explore query results by converting them into a pandas DataFrame. ```python res1.as_data_frame() ``` ```python res2.as_data_frame() ``` -------------------------------- ### Explore Query Results (Primitive) Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Demonstrates how to explore query results by converting them into primitive Python types. ```python res1.as_primitive() ``` ```python res2.as_primitive() ``` -------------------------------- ### Session Pool Initialization Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Shows how to connect to a specific space using SessionPool, which is an alternative to ConnectionPool for managing sessions. ```python from nebula3.gclient.net.SessionPool import SessionPool from nebula3.Config import SessionPoolConfig session_pool = SessionPool( username=USER, password=PASSWORD, space_name="test", addresses=[(SERVER, PORT)] ) session_pool.init(SessionPoolConfig()) res3 = session_pool.execute_py("MATCH (v) RETURN v") ``` -------------------------------- ### Simple Query Execution with ConnectionPool Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Demonstrates how to initialize a connection pool, get a session, execute a simple query (SHOW TAGS), and process the results. ```python from nebula3.Config import Config from nebula3.gclient.net import ConnectionPool # Create and initialize pool config = Config() config.max_connection_pool_size = 10 pool = ConnectionPool() ok = pool.init([('127.0.0.1', 9669)], config) if not ok: print("Failed to init connection pool") exit(1) # Get session and execute queries session = pool.get_session('root', 'nebula') try: # Use space session.execute('USE nba') # Simple query result = session.execute('SHOW TAGS') if not result.is_succeeded(): print(f"Query error: {result.error_msg()}") else: print(f"Got {result.row_size()} tags:") for row in result.rows(): tag_name = row.values()[0].as_string() print(f" - {tag_name}") finally: session.release() pool.close() ``` -------------------------------- ### Schema Creation and Data Insertion Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Demonstrates creating a space, defining tags and edges, inserting vertices with properties, and running queries with parameters using a session context. ```python # Default parameters SERVER = "127.0.0.1" PORT = 9669 USER = "root" PASSWORD = "nebula" import time from nebula3.gclient.net import ConnectionPool from nebula3.Config import Config connection_pool = ConnectionPool() # if the given servers are ok, return true, else return false connection_pool.init([(SERVER, PORT)], Config()) # get a session with session_context, session will be released automatically with connection_pool.session_context(USER, PASSWORD) as session: # Create the space session.execute_py("CREATE SPACE IF NOT EXISTS test(vid_type=FIXED_STRING(30));") time.sleep(20) # two cycles of heartbeat, by default of a NebulaGraph cluster, we will need to sleep 20s # Create the schema session.execute_py( "USE test;" "CREATE TAG IF NOT EXISTS person(name string, age int);" "CREATE EDGE IF NOT EXISTS like (likeness double);" ) time.sleep(20) # two cycles of heartbeat, by default of a NebulaGraph cluster, we will need to sleep 20s # Clear the space if it exists session.execute_py("CLEAR SPACE test;") # Run queries with parameters args1 = { "p1": 3, "p2": True, "p3": "Bob", } stmt1 = "RETURN abs($p1)+3 AS col1, (toBoolean($p2) and false) AS col2, toLower($p3)+1 AS col3" res1 = session.execute_py(stmt1, args1) args2 = { "name1": "Bob", "age1": 10, "name2": "Lily", "age2": 9, "people": ["Bob", "Lily"], } session.execute_py( "INSERT VERTEX person(name, age) VALUES 'Bob':($name1, $age1), 'Lily':($name2, $age2)", args2 ) stmt2 = "MATCH (v) WHERE id(v) in $people RETURN id(v) AS vertex_id" res2 = session.execute_py(stmt2, args2) connection_pool.close() ``` -------------------------------- ### Explore Session Pool Query Results (DataFrame) Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Demonstrates exploring query results from SessionPool by converting them into a pandas DataFrame. ```python res3.as_data_frame() ``` -------------------------------- ### Timeout Configuration Examples Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Examples of setting the timeout configuration for different workloads. ```python # For various workloads config.timeout = 5000 # OLTP: 5s config.timeout = 30000 # OLAP: 30s config.timeout = 0 # No timeout (not recommended in production) ``` -------------------------------- ### Explore Session Pool Query Results (Primitive) Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Demonstrates exploring query results from SessionPool by converting them into primitive Python types. ```python res3.as_primitive() ``` -------------------------------- ### Connection Pool Initialization Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/get_started.ipynb Defines default connection parameters and initializes a ConnectionPool to connect to the NebulaGraph service. ```python import time from nebula3.gclient.net import ConnectionPool from nebula3.Config import Config connection_pool = ConnectionPool() # if the given servers are ok, return true, else return false connection_pool.init([(SERVER, PORT)], Config()) ``` -------------------------------- ### ConnectionPool get_session Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/ConnectionPool.md Example of getting a session and executing a query, ensuring the session is released. ```python session = connection_pool.get_session('root', 'nebula') try: result = session.execute('SHOW SPACES') finally: session.release() ``` -------------------------------- ### ConnectionPool init Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/ConnectionPool.md Example of initializing the ConnectionPool with a custom configuration. ```python from nebula3.Config import Config from nebula3.gclient.net import ConnectionPool config = Config() config.max_connection_pool_size = 10 connection_pool = ConnectionPool() ok = connection_pool.init([('127.0.0.1', 9669)], config) if not ok: print("Failed to initialize pool") ``` -------------------------------- ### Installation from source Source: https://github.com/vesoft-inc/nebula-python/blob/master/README.md Clone the repository and install the Python client from source. ```bash git clone https://github.com/vesoft-inc/nebula-python.git cd nebula-python pip install . ``` ```bash python3 setup.py install ``` -------------------------------- ### Connection Pool Sizing Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example calculation for connection pool sizing considering concurrent users and replicas. ```python config.min_connection_pool_size = 50 # 100 / (3 replicas / 2 expected utilization) config.max_connection_pool_size = 150 # 100 / 2 * 3 for headroom ``` -------------------------------- ### Complete Scan Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphStorageClient.md A comprehensive example demonstrating how to initialize the meta cache and storage client, scan vertices, and scan edges, then close the client. ```python from nebula3.mclient import MetaCache from nebula3.sclient.GraphStorageClient import GraphStorageClient # Initialize meta cache meta_cache = MetaCache([('127.0.0.1', 9559)]) if not meta_cache.init(): raise RuntimeError("Failed to connect to meta server") # Create storage client storage_client = GraphStorageClient(meta_cache, time_out=60000) # Scan vertices print("=== Scanning Vertices ===") result = storage_client.scan_vertex( space_name='nba', tag_name='player', prop_names=['name', 'age'], limit=100 ) total_vertices = 0 while result.has_next(): batch = result.next() if batch: for node in batch.as_nodes(): print(f"Node: {node.get_id()}") props = node.properties('player') print(f" Name: {props.get('name')}") print(f" Age: {props.get('age')}") total_vertices += 1 print(f"Total vertices: {total_vertices}") # Scan edges print("\n=== Scanning Edges ===") result = storage_client.scan_edge( space_name='nba', edge_name='follow', limit=100 ) total_edges = 0 while result.has_next(): batch = result.next() if batch: for edge in batch.as_relationships(): print(f"Edge: {edge.start_vertex_id()} -> {edge.end_vertex_id()}") props = edge.properties() if props: print(f" Properties: {props}") total_edges += 1 print(f"Total edges: {total_edges}") storage_client.close() ``` -------------------------------- ### Install Dependencies Source: https://github.com/vesoft-inc/nebula-python/blob/master/README.md Install the package and all development dependencies using PDM. ```bash pdm install ``` -------------------------------- ### Usage with ConnectionPool Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example of initializing a ConnectionPool with a custom configuration. ```python from nebula3.Config import Config from nebula3.gclient.net import ConnectionPool config = Config() config.max_connection_pool_size = 10 config.timeout = 5000 config.idle_time = 60000 config.interval_check = 30 pool = ConnectionPool() pool.init([('127.0.0.1', 9669)], config) ``` -------------------------------- ### Install PDM Source: https://github.com/vesoft-inc/nebula-python/blob/master/README.md Install PDM, a package manager. ```bash pipx install pdm ``` -------------------------------- ### Installation Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/API-OVERVIEW.md Install the nebula3-python package using pip. ```bash pip install nebula3-python ``` -------------------------------- ### Small Application Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example configuration for a small application with a single server. ```python config = SessionPoolConfig() config.min_size = 1 config.max_size = 5 config.timeout = 10000 ``` -------------------------------- ### Pagination Pattern Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Demonstrates how to implement pagination using SKIP and LIMIT clauses in queries. ```python from nebula3.gclient.net import ConnectionPool pool = ConnectionPool() pool.init([('127.0.0.1', 9669)]) session = pool.get_session('root', 'nebula') try: session.execute('USE nba') # Pagination parameters page_size = 10 total_pages = 5 for page in range(total_pages): offset = page * page_size # Query with SKIP and LIMIT result = session.execute( f'MATCH (v:player) RETURN v.name, v.age ' f'SKIP {offset} LIMIT {page_size}' ) if result.is_succeeded(): print(f"\n=== Page {page + 1} ===") for row in result.rows(): name = row.values()[0].as_string() age = row.values()[1].as_int() print(f" {name}: {age}") if result.row_size() < page_size: print("Last page reached") break else: print(f"Error: {result.error_msg()}") break finally: session.release() ``` -------------------------------- ### Usage with SessionPool Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example of initializing a SessionPool with a custom configuration. ```python from nebula3.Config import SessionPoolConfig from nebula3.gclient.net.SessionPool import SessionPool config = SessionPoolConfig() config.min_size = 5 config.max_size = 30 config.timeout = 30000 config.interval_check = 60 pool = SessionPool('root', 'nebula', 'nba', [('127.0.0.1', 9669)]) pool.init(config) ``` -------------------------------- ### ClientServerIncompatibleException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching ClientServerIncompatibleException. ```python try: connection.open('127.0.0.1', 9669, 1000) except ClientServerIncompatibleException: print("Client and server versions not compatible") ``` -------------------------------- ### Development/Testing Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example configuration for development or testing environments. ```python config = Config() config.max_connection_pool_size = 2 config.timeout = 5000 # 5 seconds ``` -------------------------------- ### release Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/Session.md Example usage of the release method. ```python try: result = session.execute('SHOW STATS') finally: session.release() # Always release ``` -------------------------------- ### High Availability Addresses Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example list of graphd server addresses for a multi-datacenter deployment. ```python # Multiple graphd servers addresses = [ ('graphd1.dc1.example.com', 9669), ('graphd2.dc1.example.com', 9669), ('graphd1.dc2.example.com', 9669), ] ``` -------------------------------- ### AuthFailedException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching AuthFailedException when authentication fails. ```python try: session = pool.get_session('root', 'wrong_password') except AuthFailedException as e: print(f"Auth failed: {e.message}") ``` -------------------------------- ### Health Check Strategy Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example configuration for health check intervals, idle connection timeouts, and minimum pool size. ```python # For production systems with multiple replicas config.interval_check = 30 # Check every 30 seconds config.idle_time = 300000 # Close idle after 5 minutes config.min_connection_pool_size = 5 # Keep minimum warm ``` -------------------------------- ### execute Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/Session.md Example usage of the execute method. ```python result = session.execute('USE nba') result = session.execute('MATCH (v:player) RETURN v LIMIT 5') if result.is_succeeded(): for row in result.rows(): print(row) ``` -------------------------------- ### Convert to DataFrame Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Demonstrates how to execute a query and convert the results into a pandas DataFrame for further analysis and manipulation. ```python import pandas as pd from nebula3.gclient.net import ConnectionPool pool = ConnectionPool() pool.init([('127.0.0.1', 9669)]) session = pool.get_session('root', 'nebula') try: session.execute('USE nba') # Query result = session.execute( 'MATCH (v:player) RETURN v.name, v.age, v.playing LIMIT 100' ) if result.is_succeeded(): # Convert to DataFrame df = result.as_data_frame() # Now use all pandas functionality print(df.head(10)) print(f"Shape: {df.shape}") print(f"Avg age: {df['v.age'].mean()}") # Save to CSV df.to_csv('players.csv', index=False) # Or JSON df.to_json('players.json') finally: session.release() pool.close() ``` -------------------------------- ### Basic TLS Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example of configuring SSL_config for basic TLS with server verification. ```python from nebula3.Config import SSL_config import ssl ssl_config = SSL_config() ssl_config.ssl_version = ssl.PROTOCOL_TLS ssl_config.cert_reqs = ssl.CERT_REQUIRED ssl_config.ca_certs = '/path/to/ca.crt' ssl_config.verify_name = True ``` -------------------------------- ### Custom Timezone Handling Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Example demonstrating how to handle datetime values with custom timezone offsets. ```python from nebula3.gclient.net import ConnectionPool pool = ConnectionPool() pool.init([('127.0.0.1', 9669)]) session = pool.get_session('root', 'nebula') try: session.execute('USE nba') # Query datetime result = session.execute('RETURN now()') if result.is_succeeded(): dt_value = result.row_values(0)[0] if dt_value.is_datetime(): dt_wrapper = dt_value.as_datetime() # UTC time from server utc_time = dt_wrapper.get_datetime() print(f"UTC: {utc_time.year}-{utc_time.month}-{utc_time.day} \ {utc_time.hour}:{utc_time.minute}:{utc_time.sec}") # With server timezone offset local_time = dt_wrapper.get_local_datetime() print(f"Local (server TZ): {local_time.year}-{local_time.month}-\ {local_time.day} {local_time.hour}:{local_time.minute}:\ {local_time.sec}") # Custom timezone (e.g., UTC+8) custom_offset = 8 * 3600 # 8 hours in seconds custom_time = dt_wrapper.get_local_datetime_by_timezone_offset(custom_offset) print(f"Custom (UTC+8): {custom_time.year}-{custom_time.month}-\ {custom_time.day} {custom_time.hour}:{custom_time.minute}:\ {custom_time.sec}") # String representation print(f"String: {dt_wrapper.get_local_datetime_str()}") finally: session.release() ``` -------------------------------- ### Error Handling with Retry Logic Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Provides an example of implementing robust error handling with automatic retry logic for transient network or authentication failures. ```python import time from nebula3.gclient.net import ConnectionPool from nebula3.Exception import IOErrorException, AuthFailedException config = Config() pool = ConnectionPool() pool.init([('127.0.0.1', 9669)], config) def execute_with_retry(session, query, max_retries=3): """Execute query with automatic retry on transient failures""" for attempt in range(max_retries): try: result = session.execute(query) if result.is_succeeded(): return result else: # Non-retryable error print(f"Query failed: {result.error_msg()}") return result except IOErrorException as e: if attempt < max_retries - 1: wait_time = 2 ** attempt # Exponential backoff print(f"Attempt {attempt + 1}/{max_retries} failed: {e.message}") print(f"Retrying in {wait_time}s...") time.sleep(wait_time) else: print(f"All {max_retries} attempts failed") raise except AuthFailedException as e: print(f"Authentication failed: {e.message}") raise # Usage session = pool.get_session('root', 'nebula') try: session.execute('USE nba') result = execute_with_retry(session, 'SHOW SPACES') if result.is_succeeded(): print("Success!") finally: session.release() ``` -------------------------------- ### Data Preparation and Visualization Source: https://github.com/vesoft-inc/nebula-python/blob/master/example/apache_echarts.html This snippet shows how to fetch data from NebulaGraph and prepare it for ECharts visualization. ```python from nebula3.gclient.net import NebulaConnectionPool from nebula3.Config import Config import json # Connection pool configuration config = Config() config.max_connections = 10 pool = NebulaConnectionPool() await pool.init(address=('127.0.0.1', 9699), config=config) # Get a session session = await pool.get_session('root', 'nebula', True) # Fetch data from NebulaGraph resp = await session.execute_nebula("MATCH (v)-[e]->(v2) RETURN v, e, v2 LIMIT 100") # Process data for ECharts data = { "nodes": [], "links": [] } node_ids = set() for row in resp.rows(): # Source node src_id = row.values(0)[0].as_node().id().decode('utf-8') if src_id not in node_ids: data["nodes"].append({ "id": src_id, "name": src_id, "symbolSize": 10, "draggable": True }) node_ids.add(src_id) # Destination node dst_id = row.values(2)[0].as_node().id().decode('utf-8') if dst_id not in node_ids: data["nodes"].append({ "id": dst_id, "name": dst_id, "symbolSize": 10, "draggable": True }) node_ids.add(dst_id) # Edge data["links"].append({ "source": src_id, "target": dst_id, "name": row.values(1)[0].as_edge().name().decode('utf-8'), "value": row.values(1)[0].as_edge().type() }) # Convert to JSON string json_data = json.dumps(data, indent=2) print(json_data) # Release session await pool.release_session(session) ``` -------------------------------- ### Server Error Code Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example demonstrating how to check for and retrieve server error codes and messages. ```python result = session.execute('USE nonexistent_space') if not result.is_succeeded(): code = result.error_code() msg = result.error_msg() print(f"Error {code}: {msg}") ``` -------------------------------- ### Installation via pip Source: https://github.com/vesoft-inc/nebula-python/blob/master/README.md Install the NebulaGraph Python client using pip for v3.x or v2.x. ```bash # for v3.x pip install nebula3-python==$version # for v2.x pip install nebula2-python==$version ``` -------------------------------- ### ConnectionPool session_context Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/ConnectionPool.md Example using the session_context for automatic session release. ```python with connection_pool.session_context('root', 'nebula') as session: result = session.execute('USE nba') result = session.execute('MATCH (v) RETURN COUNT(*) LIMIT 1') # Session automatically released here ``` -------------------------------- ### execute_parameter Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/Session.md Example usage of the execute_parameter method. ```python params = {'name': 'Tim Duncan', 'age': 42} result = session.execute_parameter( 'MATCH (v:player {name: $name, age: $age}) RETURN v', params ) ``` -------------------------------- ### Web Service Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example configuration for a web service with many concurrent users. ```python config = SessionPoolConfig() config.min_size = 10 config.max_size = 100 config.timeout = 30000 config.idle_time = 300000 # 5 min config.interval_check = 60 # Check every minute ``` -------------------------------- ### HTTP/2 with Custom Headers Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example configuration for using HTTP/2 with custom headers. ```python config = Config() config.use_http2 = True config.http_headers = { 'Authorization': 'Bearer token123', 'Custom-Header': 'value' } config.timeout = 10000 ``` -------------------------------- ### Custom Hostname Verification Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example of configuring SSL_config to verify against a custom hostname. ```python ssl_config = SSL_config() ssl_config.cert_reqs = ssl.CERT_REQUIRED ssl_config.ca_certs = '/path/to/ca.crt' ssl_config.verify_name = 'custom.hostname.com' ``` -------------------------------- ### Data Analysis Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example configuration for data analysis with long-running queries. ```python config = SessionPoolConfig() config.min_size = 2 config.max_size = 10 config.timeout = 120000 # 2 minutes config.idle_time = 600000 # 10 minutes ``` -------------------------------- ### keys Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/ResultSet.md Shows how to retrieve the column names of a query result. ```python result = session.execute('MATCH (v:player) RETURN v.name, v.age LIMIT 1') print(result.keys()) # Output: ['v.name', 'v.age'] ``` -------------------------------- ### Check pool health Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Demonstrates how to check the health of the connection pool and retrieve server information. ```python print(f"OK servers: {pool.get_ok_servers_num()}/{len(servers)}") print(f"Total connections: {pool.connects()}") session = pool.get_session('root', 'nebula') try: # Connection auto-fails over to next healthy server result = session.execute('SHOW SPACES') if result.is_succeeded(): print("Query succeeded despite potential failures") finally: session.release() pool.close() ``` -------------------------------- ### Encode/Decode Examples Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/types.md Illustrates timezone handling for time values during encoding and decoding. ```python # Server timezone offset applied automatically time_value = value_wrapper.as_time() local_time_str = time_value.get_local_time_str() # Uses server offset # Custom timezone conversion custom_offset_seconds = 3600 * 8 # UTC+8 custom_time = time_value.get_local_time_by_timezone_offset(custom_offset_seconds) ``` -------------------------------- ### ConnectionPool Initialization with SSL Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Demonstrates initializing a ConnectionPool with SSL configuration. ```python from nebula3.Config import Config, SSL_config from nebula3.gclient.net import ConnectionPool import ssl config = Config() config.max_connection_pool_size = 10 ssl_config = SSL_config() ssl_config.cert_reqs = ssl.CERT_REQUIRED ssl_config.ca_certs = '/etc/certs/ca.crt' ssl_config.verify_name = True pool = ConnectionPool() pool.init([('nebula.example.com', 9669)], config, ssl_config) ``` -------------------------------- ### Production with Health Checks Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Example configuration for production environments with health checks enabled. ```python config = Config() config.min_connection_pool_size = 5 config.max_connection_pool_size = 20 config.timeout = 10000 # 10 seconds config.idle_time = 300000 # 5 minutes config.interval_check = 30 # Check every 30 seconds ``` -------------------------------- ### Node tags example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphDataTypes.md Get all tag names on this vertex. Returns List[str] — Tag name list. ```python print(node.tags()) # Output: ['player', 'person'] ``` -------------------------------- ### Scan all edges with 'follow' type Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphStorageClient.md Example of scanning all edges of a specific type ('follow') in a given space and printing their start and end vertices. ```python result = storage_client.scan_edge('nba', 'follow') while result.has_next(): edge_result = result.next() if edge_result: for edge in edge_result.as_relationships(): print(f"{edge.start_vertex_id()} -> {edge.end_vertex_id()}") storage_client.close() ``` -------------------------------- ### SessionPool Initialization with SSL Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Demonstrates initializing a SessionPool with SSL configuration. ```python from nebula3.Config import SessionPoolConfig, SSL_config from nebula3.gclient.net.SessionPool import SessionPool import ssl ssl_config = SSL_config() ssl_config.cert_reqs = ssl.CERT_REQUIRED ssl_config.ca_certs = '/etc/certs/ca.crt' config = SessionPoolConfig() config.min_size = 5 config.max_size = 30 pool = SessionPool('root', 'nebula', 'nba', [('nebula.example.com', 9669)]) pool.init(config, ssl_config) ``` -------------------------------- ### Relationship properties example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphDataTypes.md Get all edge properties. Returns Dict[str, ValueWrapper] — Property name to wrapped value mapping. ```python props = edge.properties() degree = props['degree'].as_int() print(f"Degree: {degree}") ``` -------------------------------- ### Relationship start_vertex_id example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphDataTypes.md Get the source vertex ID. Returns ValueWrapper — Source vertex ID. Use `.as_int()` or `.as_string()`. ```python edge = result.row_values(0)[0].as_relationship() src = edge.start_vertex_id().as_int() print(f"From: {src}") ``` -------------------------------- ### Node properties example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphDataTypes.md Get all properties for a tag. Returns Dict[str, ValueWrapper] — Property name to wrapped value mapping. ```python props = node.properties('player') for name, value_wrapper in props.items(): print(f"{name}: {value_wrapper.cast()}") ``` -------------------------------- ### Node get_id example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphDataTypes.md Get the vertex ID. Returns ValueWrapper — ID value (cast with `.as_int()` or `.as_string()` depending on space vid_type). ```python result = session.execute('MATCH (v:player) RETURN v LIMIT 1') node = result.row_values(0)[0].as_node() node_id = node.get_id().as_string() # for fixed_string vid print(f"Node ID: {node_id}") ``` -------------------------------- ### ExecutionErrorException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching ExecutionErrorException for invalid syntax. ```python try: result = session.execute('INVALID SYNTAX') except ExecutionErrorException as e: print(f"Execution error: {e.message}") ``` -------------------------------- ### Bulk Scanning with Storage Client Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Illustrates how to use the `GraphStorageClient` for bulk scanning of vertices and edges, useful for large datasets. ```python from nebula3.mclient import MetaCache from nebula3.sclient.GraphStorageClient import GraphStorageClient # Initialize meta cache meta_cache = MetaCache([('127.0.0.1', 9559)]) if not meta_cache.init(): raise RuntimeError("Failed to init meta cache") # Create storage client client = GraphStorageClient(meta_cache, time_out=60000) try: # Scan all vertices print("=== Scanning All Players ===") result = client.scan_vertex( space_name='nba', tag_name='player', prop_names=['name', 'age', 'playing'], limit=100 ) total = 0 while result.has_next(): batch = result.next() if batch: for node in batch.as_nodes(): total += 1 props = node.properties('player') print(f"Player {total}: {node.get_id()}") print(f"Total players: {total}") # Scan all edges print("\n=== Scanning All Follow Relationships ===") result = client.scan_edge( space_name='nba', edge_name='follow', limit=100 ) total_edges = 0 while result.has_next(): batch = result.next() if batch: for edge in batch.as_relationships(): total_edges += 1 if total_edges <= 5: src = edge.start_vertex_id().cast() dst = edge.end_vertex_id().cast() degree = edge.properties()['degree'].as_int() print(f" {src} -> {dst}: degree {degree}") print(f"Total edges: {total_edges}") finally: client.close() ``` -------------------------------- ### SessionException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching SessionException, specifically for timeouts. ```python try: # Long-running query result = session.execute(long_query) except SessionException as e: if e.type == SessionException.E_SESSION_TIMEOUT: print("Query timed out") ``` -------------------------------- ### InValidHostname Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching InValidHostname when hostname cannot be resolved. ```python try: pool.init([('invalid.hostname.local', 9669)]) except InValidHostname as e: print(f"Invalid hostname: {e.message}") ``` -------------------------------- ### Monitoring Query Performance Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Shows how to monitor query performance, including server latency, total latency, and execution plan. ```python from nebula3.gclient.net import ConnectionPool pool = ConnectionPool() pool.init([('127.0.0.1', 9669)]) session = pool.get_session('root', 'nebula') try: session.execute('USE nba') # Execute and measure result = session.execute('MATCH (v:player) RETURN COUNT(*) as count') if result.is_succeeded(): # Latency info server_latency = result.latency() # Server processing time total_latency = result.whole_latency() # Includes network + deserialization network_latency = total_latency - server_latency print(f"Server processing: {server_latency} μs") print(f"Network & deserialization: {network_latency} μs") print(f"Total: {total_latency} μs ({total_latency / 1000:.2f} ms)") # Plan info (with EXPLAIN) explain_result = session.execute('EXPLAIN SHOW SPACES') plan = explain_result.plan_desc() if plan: print(f"Plan: {plan}") finally: session.release() ``` -------------------------------- ### Parameterized Queries Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Shows how to use parameterized queries with the nebula3-python client to prevent injection vulnerabilities and execute queries with dynamic parameters. ```python from nebula3.gclient.net import ConnectionPool from nebula3.Config import Config config = Config() pool = ConnectionPool() pool.init([('127.0.0.1', 9669)], config) session = pool.get_session('root', 'nebula') try: session.execute('USE nba') # Parameterized query - prevents injection params = { 'player_name': 'Tim Duncan', 'min_age': 35 } query = ''' MATCH (v:player {name: $player_name}) WHERE v.age >= $min_age RETURN v.name, v.age ''' result = session.execute_parameter(query, params) if result.is_succeeded(): for row in result.rows(): name = row.values()[0].as_string() age = row.values()[1].as_int() print(f"{name}: {age} years old") finally: session.release() ``` -------------------------------- ### NotValidConnectionException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching NotValidConnectionException when connection pool is unavailable. ```python try: session = pool.get_session('root', 'nebula') except NotValidConnectionException: print("No valid connections available") ``` -------------------------------- ### IOErrorException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching IOErrorException for connection broken or timeout errors. ```python try: result = session.execute('MATCH (v) RETURN COUNT(*)') except IOErrorException as e: if e.type == IOErrorException.E_CONNECT_BROKEN: print("Lost connection to server") elif e.type == IOErrorException.E_TIMEOUT: print("Operation timed out") ``` -------------------------------- ### Quick Example: Connecting to GraphD Using Graph Client Source: https://github.com/vesoft-inc/nebula-python/blob/master/README.md Demonstrates how to connect to NebulaGraph using the Graph Client, including session management and executing queries. ```python from nebula3.gclient.net import ConnectionPool from nebula3.Config import Config # define a config config = Config() config.max_connection_pool_size = 10 # init connection pool connection_pool = ConnectionPool() # if the given servers are ok, return true, else return false ok = connection_pool.init([('127.0.0.1', 9669)], config) # option 1 control the connection release yourself # get session from the pool session = connection_pool.get_session('root', 'nebula') # select space session.execute('USE basketballplayer') # show tags result = session.execute('SHOW TAGS') print(result) # release session session.release() # option 2 with session_context, session will be released automatically with connection_pool.session_context('root', 'nebula') as session: session.execute('USE basketballplayer') result = session.execute('SHOW TAGS') print(result) # close the pool connection_pool.close() ``` -------------------------------- ### InvalidValueTypeException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching InvalidValueTypeException when converting ValueWrapper to wrong type. ```python value = result.row_values(0)[0] try: num = value.as_int() # Fails if not int type except InvalidValueTypeException as e: print(f"Type error: {e.message}") ``` -------------------------------- ### Visualization with dict_for_vis Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Shows how to retrieve subgraph data and format it for visualization using the `dict_for_vis` method, suitable for tools like Apache ECharts. ```python import json from nebula3.gclient.net import ConnectionPool pool = ConnectionPool() pool.init([('127.0.0.1', 9669)]) session = pool.get_session('root', 'nebula') try: session.execute('USE nba') # Query for subgraph result = session.execute( 'GET SUBGRAPH 2 STEPS FROM "player100" ' 'YIELD VERTICES AS nodes, EDGES AS edges' ) if result.is_succeeded(): # Get visualization-ready format vis_data = result.dict_for_vis() # Can use with Apache ECharts or other viz tools print(f"Nodes: {vis_data['nodes_count']}") print(f"Edges: {vis_data['edges_count']}") # Save for web visualization with open('graph.json', 'w') as f: json.dump(vis_data, f, indent=2) finally: session.release() ``` -------------------------------- ### Memory vs Speed Trade-off Configuration Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/configuration.md Configuration examples demonstrating the trade-off between memory footprint and throughput by adjusting connection pool sizes and idle time. ```python # Low memory footprint config.min_connection_pool_size = 1 config.max_connection_pool_size = 5 config.idle_time = 10000 # High throughput config.min_connection_pool_size = 10 config.max_connection_pool_size = 100 config.idle_time = 600000 ``` -------------------------------- ### NoValidSessionException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching NoValidSessionException when session pool is unable to provide a session. ```python try: result = pool.execute('SHOW SPACES') except NoValidSessionException as e: print(f"No session available: {e.message}") ``` -------------------------------- ### InvalidKeyException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching InvalidKeyException when accessing result by non-existent column name. ```python try: values = result.column_values('nonexistent_col') except InvalidKeyException as e: print(f"Invalid column: {e.message}") ``` -------------------------------- ### OutOfRangeException Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/errors.md Example of catching OutOfRangeException when accessing result rows/columns by invalid index. ```python try: values = result.row_values(999) # Out of range except OutOfRangeException: print("Row index out of range") ``` -------------------------------- ### Constructor Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphStorageClient.md Create a storage client. ```python def __init__( self, meta_cache, storage_addrs: List[Tuple[str, int]] = None, time_out: int = 60000, ) ``` -------------------------------- ### Multi-Server Resilience Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Demonstrates how to configure the connection pool for multi-server resilience, including SSL configuration and setting connection pool parameters like minimum/maximum pool size, timeout, and idle time. It shows how to initialize the pool with a list of servers for High Availability (HA). ```python from nebula3.Config import Config, SSL_config from nebula3.gclient.net import ConnectionPool import ssl # Configure for multiple servers with SSL config = Config() config.min_connection_pool_size = 3 config.max_connection_pool_size = 20 config.timeout = 10000 config.idle_time = 300000 config.interval_check = 30 # Check every 30 seconds ssl_config = SSL_config() ssl_config.cert_reqs = ssl.CERT_REQUIRED ssl_config.ca_certs = '/path/to/ca.crt' ssl_config.verify_name = True # Multiple servers for HA servers = [ ('nebula1.example.com', 9669), ('nebula2.example.com', 9669), ('nebula3.example.com', 9669), ] pool = ConnectionPool() ok = pool.init(servers, config, ssl_config) if not ok: print("Failed to connect to any server") exit(1) ``` -------------------------------- ### SessionPool for Web Service Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/EXAMPLES.md Illustrates using SessionPool for web services, including initialization, executing queries within a request handler, and handling potential exceptions like NoValidSessionException and IOErrorException. ```python from nebula3.Config import SessionPoolConfig from nebula3.gclient.net.SessionPool import SessionPool from nebula3.Exception import NoValidSessionException, IOErrorException # Global initialization (once on startup) def init_pool(): config = SessionPoolConfig() config.min_size = 5 config.max_size = 50 config.timeout = 30000 pool = SessionPool('root', 'nebula', 'nba', [('127.0.0.1', 9669)]) if not pool.init(config): raise RuntimeError("Failed to init session pool") return pool session_pool = init_pool() # In request handler def get_player_count(): try: result = session_pool.execute('MATCH (v:player) RETURN COUNT(*) as count') if result.is_succeeded() and not result.is_empty(): count = result.row_values(0)[0].as_int() return {'count': count} else: return {'error': result.error_msg()} except NoValidSessionException as e: return {'error': f'No session available: {e.message}'} except IOErrorException as e: return {'error': f'Network error: {e.message}'} # In shutdown def shutdown_pool(): session_pool.close() ``` -------------------------------- ### ValueWrapper Type Checking Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/types.md An example of using type checking methods on a ValueWrapper. ```python value_wrapper = result.row_values(0)[0] if value_wrapper.is_int(): num = value_wrapper.as_int() elif value_wrapper.is_string(): text = value_wrapper.as_string() elif value_wrapper.is_vertex(): node = value_wrapper.as_node() ``` -------------------------------- ### Singleton Usage Pattern Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/SessionPool.md Demonstrates how to initialize and use the SessionPool as a singleton in an application. ```python # Global initialization (once) session_pool = SessionPool('root', 'nebula', 'nba', [('127.0.0.1', 9669)]) if not session_pool.init(SessionPoolConfig()): raise RuntimeError("Failed to initialize session pool") # Anywhere in application result = session_pool.execute('MATCH (v) RETURN COUNT(*)') print(result.row_size()) ``` -------------------------------- ### Type Conversion Examples Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/types.md Demonstrates common type checking and conversion patterns in the Nebula Graph Python client. ```python # Type checking pattern for row in result.rows(): for value in row.values(): if value.is_null(): print("NULL") elif value.is_bool(): print(f"Bool: {value.as_bool()}") elif value.is_int(): print(f"Int: {value.as_int()}") elif value.is_string(): print(f"String: {value.as_string()}") elif value.is_list(): print(f"List: {value.cast()}") # Safe conversion with defaults def get_string(value_wrapper, default=''): if value_wrapper.is_string(): return value_wrapper.as_string() return default # Graph object handling for row in result.rows(): val = row.values()[0] if val.is_vertex(): node = val.as_node() print(f"Node ID: {node.get_id()}") elif val.is_edge(): edge = val.as_relationship() print(f"Edge: {edge.start_vertex_id()} -> {edge.end_vertex_id()}") elif val.is_path(): path = val.as_path() for node in path.nodes(): print(f" {node.get_id()}") ``` -------------------------------- ### JSON Result Format Example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/Session.md Example structure of a JSON result when using execute_json(). ```json { "results": [ { "columns": ["col1", "col2"], "data": [ { "row": [value1, value2], "meta": [metadata1, metadata2] } ], "latencyInUs": 1000, "spaceName": "nba", "planDesc": { ... }, "comment": "" } ], "errors": [] } ``` -------------------------------- ### scan_vertex example Source: https://github.com/vesoft-inc/nebula-python/blob/master/_autodocs/api-reference/GraphStorageClient.md Scan all vertices with a specific tag. ```python from nebula3.mclient import MetaCache meta_cache = MetaCache([('127.0.0.1', 9559)]) meta_cache.init() storage_client = GraphStorageClient(meta_cache) # Scan all vertices with 'player' tag result = storage_client.scan_vertex('nba', 'player') while result.has_next(): vertex_result = result.next() if vertex_result: for vertex in vertex_result: print(vertex) storage_client.close() ```