### Run an Installed Query with Parameters Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Execute an installed GSQL query with specified parameters. This example shows how to run the 'RecommendMovies' query with input person, k1, and k2 values. ```python parameters = { "p": "Dan", "k1": 50, "k2": 10 } results = conn.runInstalledQuery("RecommendMovies", params=parameters) parsed = conn.parseQueryOutput(results) print(json.dumps(parsed, indent=2)) ``` -------------------------------- ### Run Installed Query with SET Parameter Source: https://context7.com/tigergraph/pytigergraph/llms.txt Demonstrates how to pass a SET parameter to an installed query, typically used for collections of vertices or other data types. ```python result = conn.runInstalledQuery( "find_common_friends", params={ "people": [("alice_123",), ("bob_456",), ("carol_789",)] # SET> } ) ``` -------------------------------- ### Install pyTigerGraph with Combined Extras Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Install pyTigerGraph with multiple extras combined, such as 'fast', 'gds', and 'mcp'. ```sh pip install 'pyTigerGraph[fast,gds,mcp]' ``` -------------------------------- ### Install Queries with Wait Parameter Source: https://github.com/tigergraph/pytigergraph/blob/master/CHANGELOG.md Control whether `installQueries()` blocks until installation completes. The default behavior differs for synchronous and asynchronous connections. ```python installQueries(wait=True) ``` ```python installQueries(wait=False) ``` -------------------------------- ### Install pyTigerGraph with MCP Extra Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Install pyTigerGraph with the 'mcp' extra to include the Model Context Protocol server, which is a convenience alias for pyTigerGraph-mcp. ```sh pip install 'pyTigerGraph[mcp]' ``` -------------------------------- ### Start MCP Server Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Start the TigerGraph MCP server. The server reads connection configuration from environment variables. ```sh # Start the server (reads connection config from environment variables) tigergraph-mcp ``` -------------------------------- ### Install pyTigerGraph Base Package Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Install the base pyTigerGraph package using pip. ```sh pip install pyTigerGraph ``` -------------------------------- ### Run Installed Query with MAP Parameter Source: https://context7.com/tigergraph/pytigergraph/llms.txt Illustrates passing a MAP parameter to an installed query, commonly used for key-value pairs such as configuration settings or feature weights. ```python result = conn.runInstalledQuery( "weighted_search", params={ "weights": {"feature1": 0.5, "feature2": 0.3, "feature3": 0.2} } ) ``` -------------------------------- ### Install pyTigerGraph with Fast JSON Backend Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Install pyTigerGraph with the 'fast' extra to enable the orjson JSON backend for faster parsing and GIL release. ```sh pip install 'pyTigerGraph[fast]' ``` -------------------------------- ### Manage Installed Queries with pyTigerGraph Source: https://context7.com/tigergraph/pytigergraph/llms.txt Retrieves a list of installed queries and their statistics. Use 'fmt="list"' for a simple list. ```python queries = conn.getInstalledQueries(fmt="list") print(f"Installed queries: {queries}") ``` ```python stats = conn.getStatistics(seconds=60, segments=10) print(f"Query statistics: {stats}") ``` -------------------------------- ### Install pyTigerGraph with MCP Alias Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Install pyTigerGraph using the convenience alias, which automatically includes the pyTigerGraph-mcp package. ```sh # Or via the pyTigerGraph convenience alias (installs pyTigerGraph-mcp automatically) pip install 'pyTigerGraph[mcp]' ``` -------------------------------- ### Asynchronous Connection to TigerGraph Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Establish an asynchronous connection to a TigerGraph database using AsyncTigerGraphConnection. This example demonstrates running an installed query within an async function and using asyncio.run(). ```python import asyncio from pyTigerGraph import AsyncTigerGraphConnection async def main(): async with AsyncTigerGraphConnection( host="http://localhost", graphname="my_graph", username="tigergraph", password="tigergraph", ) as conn: result = await conn.runInstalledQuery("my_query", {"param": "value"}) print(result) asyncio.run(main()) ``` -------------------------------- ### Create and Save a Complex Query Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Define and save a complex GSQL query for later installation and execution. This example demonstrates creating a movie recommendation query using cosine similarity. ```python result = conn.gsql('\ USE GRAPH movie CREATE QUERY RecommendMovies( VERTEX p, int k1, int k2 ) FOR GRAPH movie { OrAccum @rated; SumAccum @ratingByP; SumAccum @lengthASqr, @lengthBSqr, @dotProductAB; SumAccum @cosineSimilarity; AvgAccum @recommendScore; PSet = { p }; PRatedMovies = SELECT m FROM PSet -(Likes:r)-> Movie:m ACCUM m.@rated = true, m.@ratingByP = r.weight; PeopleRatedSameMovies = SELECT tgt FROM PRatedMovies:m -(:r)-> Person:tgt WHERE tgt != p ACCUM tgt.@lengthASqr += m.@ratingByP * m.@ratingByP, tgt.@lengthBSqr += r.weight * r.weight, tgt.@dotProductAB += m.@ratingByP * r.weight POST-ACCUM tgt.@cosineSimilarity = tgt.@dotProductAB / (sqrt(tgt.@lengthASqr) * sqrt(tgt.@lengthBSqr)) ORDER BY tgt.@cosineSimilarity DESC LIMIT k1; RecommendedMovies = SELECT m FROM PeopleRatedSameMovies -(Likes:r)-> Movie:m WHERE m.@rated == false ACCUM m.@recommendScore += r.weight ORDER BY m.@recommendScore DESC LIMIT k2; PRINT RecommendedMovies; }') print(result) ``` -------------------------------- ### Run Installed Query with Untyped VERTEX Parameter Source: https://context7.com/tigergraph/pytigergraph/llms.txt Shows how to pass an untyped VERTEX parameter to an installed query, requiring explicit specification of both the vertex ID and its type. ```python result = conn.runInstalledQuery( "generic_query", params={ "v": ("alice_123", "Person") # (id, vertex_type) for untyped VERTEX } ) ``` -------------------------------- ### Create and Manage Queries Programmatically with pyTigerGraph Source: https://context7.com/tigergraph/pytigergraph/llms.txt Programmatically creates, installs, drops, and retrieves metadata for GSQL queries. Supports force reinstall and waiting for installation. ```python conn.createQuery(""" CREATE QUERY find_neighbors(VERTEX p) FOR GRAPH social { start = {p}; neighbors = SELECT t FROM start:s -(FOLLOWS)-> Person:t; PRINT neighbors; } ") ``` ```python result = conn.installQueries( queries=["find_neighbors", "hello_world"], flag="-force", # Force reinstall wait=True # Wait for installation to complete ) ``` ```python conn.dropQueries("hello_world") ``` ```python conn.dropQueries(["query1", "query2"]) # Drop multiple ``` ```python metadata = conn.getQueryMetadata("find_neighbors") print(f"Parameters: {metadata}") ``` ```python query_names = conn.listQueryNames() print(f"All queries: {query_names}") ``` ```python source = conn.showQuery("find_neighbors") print(source) ``` -------------------------------- ### Retrieve Installed TigerGraph Queries Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Fetches and displays a list of all installed GSQL queries on the TigerGraph Solution. This is equivalent to running 'GSQL SHOW QUERIES *'. ```python print(json.dumps(conn.getInstalledQueries(),indent=2)) ``` -------------------------------- ### Install pyTigerGraph-mcp Standalone Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Install the standalone pyTigerGraph-mcp package for exposing TigerGraph operations as tools for AI agents and LLM applications. ```sh # Recommended — install the standalone package directly pip install pyTigerGraph-mcp ``` -------------------------------- ### Run Installed Queries in Parallel (Synchronous) Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Use ThreadPoolExecutor for concurrent execution of installed queries in synchronous mode. Ensure pyTigerGraph[fast] is installed for optimal performance with the orjson backend. ```python from concurrent.futures import ThreadPoolExecutor, as_completed with TigerGraphConnection(...) as conn: with ThreadPoolExecutor(max_workers=16) as executor: futures = [executor.submit(conn.runInstalledQuery, "q", {"p": v}) for v in values] for f in as_completed(futures): print(f.result()) ``` -------------------------------- ### Run Installed Queries Asynchronously Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Utilize asyncio and AsyncTigerGraphConnection for high-throughput, low-latency I/O-bound workloads. This mode uses a single aiohttp.ClientSession for shared connections. ```python import asyncio from pyTigerGraph import AsyncTigerGraphConnection async def main(): async with AsyncTigerGraphConnection(...) as conn: tasks = [conn.runInstalledQuery("q", {"p": v}) for v in values] results = await asyncio.gather(*tasks) asyncio.run(main()) ``` -------------------------------- ### Get Edges as DataFrame Source: https://context7.com/tigergraph/pytigergraph/llms.txt Retrieves edges and returns them as a Pandas DataFrame, facilitating data analysis. This example focuses on edges from a specific source vertex. ```python df = conn.getEdgesDataFrame( sourceVertexType="Person", sourceVertexId="alice_123", edgeType="FOLLOWS" ) print(df.head()) ``` -------------------------------- ### Synchronous Connection as Context Manager Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Use a synchronous TigerGraph connection as a context manager to ensure the underlying HTTP session is properly closed after use. This example demonstrates running an installed query. ```python with TigerGraphConnection(host="http://localhost", graphname="my_graph") as conn: result = conn.runInstalledQuery("my_query", {"param": "value"}) ``` -------------------------------- ### Install pyTigerGraph with GDS Extra Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Install pyTigerGraph with the 'gds' extra for Graph Data Science, which includes data loaders for PyTorch Geometric, DGL, and Pandas. ```sh pip install 'pyTigerGraph[gds]' ``` -------------------------------- ### Install a Saved Query Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Install a previously saved GSQL query onto the TigerGraph solution. This makes the query available for execution via `runInstalledQuery`. ```python print(conn.gsql('\ USE GRAPH movie INSTALL QUERY RecommendMovies ')) ``` -------------------------------- ### Run Installed Query with Parameters Source: https://context7.com/tigergraph/pytigergraph/llms.txt Executes a pre-installed query on the TigerGraph database, passing parameters such as source and target vertices, and query-specific options like timeout and size limit. ```python result = conn.runInstalledQuery( queryName="find_shortest_path", params={ "source": ("alice_123",), # VERTEX - tuple with ID "target": ("bob_456",), "max_depth": 5 }, timeout=30000, # 30 seconds sizeLimit=10000000 # 10MB response limit ) print(result) ``` -------------------------------- ### Loading Data via JSON with UpsertData Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Example of constructing a Python dictionary that conforms to the JSON structure for `UpsertData` and printing the results. ```python data = { "vertices": { "Person": { "Dan": { }, "Ben": { } }, "Movie": { "1": { "name": { "value": "Up" } }, "2": { "name": { "value": "Redline" }, } } }, "edges": { "Person": { "Dan": { "Likes": { "Movie": { "1": { "weight": { "value": 8.7 }, }, "2": { "weight": { "value": 9.1 }, } } } }, "Ben": { "Likes": { "Movie": { "1": { "weight": { "value": 8.2 }, }, "2": { "weight": { "value": 7.6 } } } } } } } } results = conn.upsertData(data) print(results) ``` -------------------------------- ### Query Execution Source: https://context7.com/tigergraph/pytigergraph/llms.txt Run installed queries and interpreted queries against the TigerGraph database. ```APIDOC ## Query Execution ### Description Run installed queries and interpreted queries against the TigerGraph database. Supports parameter passing, timeouts, async execution, and various output formats. ### Run an installed query with parameters ```python # Run an installed query with parameters result = conn.runInstalledQuery( queryName="find_shortest_path", params={ "source": ("alice_123",), # VERTEX - tuple with ID "target": ("bob_456",), "max_depth": 5 }, timeout=30000, # 30 seconds sizeLimit=10000000 # 10MB response limit ) print(result) ``` ### Query with SET parameter ```python # Query with SET parameter result = conn.runInstalledQuery( "find_common_friends", params={ "people": [("alice_123",), ("bob_456",), ("carol_789",)] # SET> } ) ``` ### Query with untyped VERTEX ```python # Query with untyped VERTEX (requires type specification) result = conn.runInstalledQuery( "generic_query", params={ "v": ("alice_123", "Person") # (id, vertex_type) for untyped VERTEX } ) ``` ### Query with MAP parameter ```python # Query with MAP parameter result = conn.runInstalledQuery( "weighted_search", params={ "weights": {"feature1": 0.5, "feature2": 0.3, "feature3": 0.2} } ) ``` ### Run query asynchronously (detached mode) ```python # Run query asynchronously (detached mode) result = conn.runInstalledQuery( "long_running_analysis", params={"depth": 10}, runAsync=True ) request_id = result[0]["requestId"] ``` ### Check async query status ```python # Check async query status status = conn.checkQueryStatus(request_id) print(f"Status: {status}") ``` ### Get async query result when complete ```python # Get async query result when complete final_result = conn.getQueryResult(request_id) ``` ``` -------------------------------- ### Get Specific Loading Job Information Source: https://context7.com/tigergraph/pytigergraph/llms.txt Fetch detailed information about a specific loading job by its name. The 'verbose' flag provides more detailed output. ```python job_info = conn.getLoadingJobInfo("load_persons", verbose=True) print(f"Job details: {job_info}") ``` -------------------------------- ### Get All Loading Jobs Source: https://context7.com/tigergraph/pytigergraph/llms.txt Retrieve a list of all available loading jobs configured in the TigerGraph database. ```python jobs = conn.getLoadingJobs() print(f"Available jobs: {jobs}") ``` -------------------------------- ### Get Loaded Stats Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Call `getLoadedStats()` to view the number of vertices and edges successfully loaded into the graph. ```python getLoadedStats() ``` -------------------------------- ### Get Vertices as DataFrame Source: https://context7.com/tigergraph/pytigergraph/llms.txt Fetches vertices and returns them as a Pandas DataFrame, allowing for easy data manipulation and analysis. Supports attribute selection and filtering. ```python df = conn.getVertexDataFrame("Person", select="name,age", where="age>20") print(df.head()) ``` -------------------------------- ### Get Vertex by Primary ID Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Fetch a specific vertex using its `PrimaryId` and `vertexType` with `getVerticesById`. Multiple vertices can be retrieved by providing a list of `PrimaryId`s. ```python results = conn.getVerticesById("Person", "Dan") print(json.dumps(results, indent=2)) print("----------") results = conn.getVerticesById("Movie", ["2","4"]) print(json.dumps(results, indent=2)) ``` -------------------------------- ### Get Vertex Statistics Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve statistics for a specific vertex type or all vertex types using `getVertexStats`. Use '*' as a wildcard for all types and `skipNA=True` to exclude types with no applicable stats. ```python results = conn.getVertexStats("Person") print(json.dumps(results, indent=2)) results = conn.getVertexStats("Movie") print(json.dumps(results, indent=2)) results = conn.getVertexStats("*", skipNA=True) print(json.dumps(results, indent=2)) ``` -------------------------------- ### Get Loaded Graph Statistics Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Counts and displays the number of vertices and edges of specific types, along with sample data. Useful for verifying data loading status. ```python def getLoadedStats(limit=5): numPeople = conn.getVertexCount("Person") numMovies = conn.getVertexCount("Movie") numEdges = conn.getEdgeCount("Likes") people = conn.getVertices("Person", limit=limit) movies = conn.getVertices("Movie", limit=limit) # edges = conn.getEdgesByType("rate", limit=limit) print(f"There are currently {numPeople} people, {numMovies} movies, and {numEdges} edges connecting them") print(f"Our people are: {json.dumps(people, indent=2)}") print(f"Our movies are: {json.dumps(movies, indent=2)}") # print(f"Our edges are: {json.dumps(edges, indent=2)}") getLoadedStats() ``` -------------------------------- ### Get Specific Edge Type Info Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve detailed information about a specific edge type, including its attributes and configuration. Use the exact edge type name. ```python results = conn.getEdgeType("Likes") print(f"Rate Edge Attributes:\n {json.dumps(results, indent=2)}) ``` -------------------------------- ### Retrieve Edge Data as Pandas DataFrame Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Query edge data from the graph and return it as a Pandas DataFrame. Supports retrieving edges from a specified starting vertex. ```python # Get all edges from selected starting vertex df4 = conn.getEdgesDataframe("Person", "Dan", limit=3) print("Edges Dataframe") print(df4) print("---------------------") result = conn.getEdges("Person", "Dan", limit=3) print("JSON Edge Set") print(json.dumps(result, indent=2)) print("---------------------") df5 = conn.edgeSetToDataFrame(result) print("Converted Edge Set as Dataframe") print(df5) ``` -------------------------------- ### Get Specific Vertex Type Info Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve detailed information about a specific vertex type, including its attributes and primary ID configuration. Use the exact vertex type name. ```python results = conn.getVertexType("Person") print(f"Person Vertex Attributes:\n {json.dumps(results, indent=2)}") print("---------------') ``` -------------------------------- ### Get Edge Statistics Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve statistics for a specific edge type using `getEdgeStats`. This is useful for understanding aggregate values like MAX, MIN, and AVG for attributes. ```python results = conn.getEdgeStats("Likes") print(json.dumps(results, indent=2)) print("----------") ``` -------------------------------- ### Run One-Off Query in Interpreted Mode Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Execute a query directly without saving or installing it on the TigerGraph solution. This is ideal for ad-hoc queries or testing new query logic. ```python results = conn.runInterpretedQuery('INTERPRET QUERY testQuery2() FOR GRAPH movie { PRINT "testQuery2 works!"; }') print(results) ``` -------------------------------- ### Programmatically Delete Edges Based on Attributes in PyTigerGraph Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Iterate through edges of a specific type and delete them individually if their attributes meet certain conditions. This example deletes 'Likes' edges where the 'weight' attribute is less than 9.0. ```python # Get all 'rate' edges edges = conn.getEdgesByType("Likes") # Delete any edges with a rating less than 9.0 for edge in edges: if edge["attributes"]["weight"] < 9.0: rating = edge["attributes"]["weight"] fromPerson = edge["from_id"] deleted = conn.delEdges("Person", edge["from_id"]) print(f"Deleting a rating of {rating} from {fromPerson}") print("-------------") results = conn.getEdgeStats("Likes") edgeCnt = conn.getEdgeCount(edgeType="Likes") print("After deleting ratings less than '9.0'") print(f"{edgeCnt} 'rate' edges") print(json.dumps(results, indent=2)) ``` -------------------------------- ### Create a Test Query via GSQL Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Demonstrates creating a simple GSQL query named 'testQuery' that prints a confirmation message. This uses the `CREATE QUERY` command within the `movie` graph. ```python results = conn.gsql(''' USE GRAPH movie CREATE QUERY testQuery() FOR GRAPH movie { PRINT "testQuery works!"; }''') print(results) ``` -------------------------------- ### Create a Data Source for Cloud Storage Source: https://context7.com/tigergraph/pytigergraph/llms.txt Configure a new data source, such as an S3 bucket, for accessing data stored in cloud services. Requires a name and a configuration dictionary. ```python conn.createDataSource( dsName="my_s3_source", config={ "type": "s3", "access.key": "AKIAIOSFODNN7EXAMPLE", "secret.key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "region": "us-west-2" } ) ``` -------------------------------- ### List Loading Jobs via GSQL Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Uses the `conn.gsql('ls')` command to list available loading jobs in the TigerGraph instance. ```python print(conn.gsql('ls')) ``` -------------------------------- ### Load Data from File using Loading Job Source: https://context7.com/tigergraph/pytigergraph/llms.txt Initiate a data loading job from a specified file path. Requires the file path, a file tag, the job name, and optionally a separator and timeout. ```python result = conn.runLoadingJobWithFile( filePath="/data/persons.csv", fileTag="f", jobName="load_persons", sep=",", timeout=60000 ) print(f"Loaded: {result}") ``` -------------------------------- ### Import pyTigerGraph Library Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Import the main pyTigerGraph library for database interactions. ```python import pyTigerGraph as tg ``` -------------------------------- ### Initialize TigerGraph Connection Source: https://context7.com/tigergraph/pytigergraph/llms.txt Establishes a connection to a TigerGraph database. Supports basic authentication, token-based authentication, and TigerGraph Cloud. Can be used as a context manager for automatic cleanup. ```python from pyTigerGraph import TigerGraphConnection # Basic connection with username/password conn = TigerGraphConnection( host="http://localhost", graphname="social_network", username="tigergraph", password="tigergraph" ) # Connection with token-based authentication conn = TigerGraphConnection( host="http://localhost", graphname="social_network", gsqlSecret="my_secret_key" # Automatically generates a session token ) # TigerGraph Cloud connection with HTTPS conn = TigerGraphConnection( host="https://my-instance.i.tgcloud.io", graphname="social_network", username="tigergraph", password="tigergraph", tgCloud=True ) # Using as context manager for automatic cleanup with TigerGraphConnection( host="http://localhost", graphname="social_network", username="tigergraph", password="tigergraph" ) as conn: result = conn.runInstalledQuery("my_query", {"param": "value"}) print(result) # Test the connection print(conn.echo()) # Returns "Hello GSQL" if connected print(conn.getVer()) # Returns version like "4.1.0" ``` -------------------------------- ### Initialize Async TigerGraph Connection Source: https://context7.com/tigergraph/pytigergraph/llms.txt Provides an asynchronous interface for connecting to TigerGraph using async/await syntax. Ideal for high-throughput applications leveraging aiohttp. ```python import asyncio from pyTigerGraph import AsyncTigerGraphConnection async def main(): # Create async connection async with AsyncTigerGraphConnection( host="http://localhost", graphname="social_network", username="tigergraph", password="tigergraph" ) as conn: # Run a query asynchronously result = await conn.runInstalledQuery("find_friends", {"person": "Alice"}) print(result) # Run multiple queries concurrently queries = [ conn.runInstalledQuery("query1", {"p": v}) for v in ["a", "b", "c"] ] results = await asyncio.gather(*queries) for r in results: print(r) asyncio.run(main()) ``` -------------------------------- ### Import Additional Libraries Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Import necessary libraries for data handling and configuration. ```python import json import pandas as pd ``` -------------------------------- ### Show Specific Loading Jobs via GSQL Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Executes a GSQL command to show all loading jobs for the 'movie' graph. This requires specifying the graph and using the `SHOW JOB *` command. ```python results = conn.gsql(''' USE GRAPH movie SHOW JOB *''') print(results) ``` -------------------------------- ### Get Edge Types Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve a list of all edge type names in the graph. This helps in understanding the relationships available between vertices. ```python results = conn.getEdgeTypes() print(f"Edges: {results}") ``` -------------------------------- ### Get Edge Count Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Use `getEdgeCountFrom` to find the number of edges connected to a vertex. You can filter by `edgeType` and target vertex details. ```python results = conn.getEdgeCountFrom("Person", "Nick") print("Number of edges connected to person 'Nick'") print(results) print("--------------") # Can also specify edge type and/or target vertex type and target vertex id results = conn.getEdgeCountFrom("Person", "Nick", edgeType="Likes") print("Number of 'rate' edges connected to person 'Nick'") print(results) print("--------------") ``` -------------------------------- ### Establish TigerGraph Connection Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Connect to the TigerGraph database using host, username, and password read from a configuration file. ```python from pyTigerGraph import TigerGraphConnection # Read in DB configs with open('../config.json', "r") as config_file: config = json.load(config_file) conn = TigerGraphConnection( host=config["host"], username=config["username"], password=config["password"]) ``` -------------------------------- ### Get Vertex Types Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve a list of all vertex type names in the graph. This is useful for quickly identifying available vertex categories. ```python results = conn.getVertexTypes() print(f"Verticies: {results}") ``` -------------------------------- ### Get Async Query Result Source: https://context7.com/tigergraph/pytigergraph/llms.txt Fetches the final result of an asynchronous query once it has completed execution, using the query's request ID. ```python final_result = conn.getQueryResult(request_id) ``` -------------------------------- ### Format Data for Bulk Vertex Loading Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Prepares lists of tuples for bulk loading vertices. Each tuple contains a vertex ID and a dictionary of attributes. Suitable for data generated programmatically. ```python # Vertex format [(PrimaryId, {attributes})] people = [ ("Ben", {}), ("Nick", {}), ("Leena", {}) ] movies = [ (2, {"name": "Inception"}), (3, {"name": "Her"}), (4, {"name": "Ferris Bueller's Day Off"}) ] ``` -------------------------------- ### Get Specific Vertices by ID Source: https://context7.com/tigergraph/pytigergraph/llms.txt Retrieves one or more vertices from the database using their unique IDs. Accepts a single ID or a list of IDs. ```python alice = conn.getVerticesById("Person", "alice_123") multiple = conn.getVerticesById("Person", ["alice_123", "bob_456"]) ``` -------------------------------- ### Create Neighbor Loader for GNN Training Source: https://context7.com/tigergraph/pytigergraph/llms.txt Set up a neighbor loader for sampling subgraphs using neighbor sampling, suitable for Graph Neural Network training. Supports various output formats like PyTorch Geometric. ```python neighbor_loader = conn.gds.neighborLoader( v_in_feats=["x"], v_out_labels=["y"], v_extra_feats=["train_mask", "val_mask"], batch_size=64, num_neighbors=10, num_hops=2, shuffle=True, filter_by="train_mask", output_format="PyG", add_self_loop=False ) ``` -------------------------------- ### Get All Edges Connected to a Vertex Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve all edges connected to a specified vertex using `getEdges`. This function can return detailed information about the connected edges. ```python results = conn.getEdges("Person", "Nick") print("All edges connected to person 'Nick'") print(json.dumps(results, indent=2)) ``` -------------------------------- ### Create TigerGraph Connection with Token Source: https://context7.com/tigergraph/pytigergraph/llms.txt Instantiate a TigerGraphConnection using an API token for authentication. Ensure the token is pre-obtained. ```python conn2 = TigerGraphConnection( host="http://localhost", graphname="social", apiToken=token # Use pre-obtained token ) ``` -------------------------------- ### Get Full Graph Schema Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve the complete schema of the graph, including vertex and edge types, their attributes, and configurations. The output is a JSON object. ```python results = conn.getSchema() print(json.dumps(results, indent=2)) ``` -------------------------------- ### Manage Authentication Tokens with pyTigerGraph Source: https://context7.com/tigergraph/pytigergraph/llms.txt Creates, retrieves, and uses secrets to generate authentication tokens for secure database access. Tokens are automatically set on the connection. ```python conn = TigerGraphConnection( host="http://localhost", graphname="social", username="tigergraph", password="tigergraph" ) # Create a secret for token generation secret = conn.createSecret(alias="my_app_secret") print(f"Created secret: {secret}") ``` ```python # Or create with alias returned secret_dict = conn.createSecret(alias="app_v2", withAlias=True) print(f"Secret: {secret_dict}") # {'app_v2': 'abc123...'} ``` ```python # Get existing secrets secrets = conn.getSecrets() print(f"All secrets: {secrets}") ``` ```python # Get a token using the secret token = conn.getToken(secret=secret, lifetime=86400) # 24 hours print(f"Token: {token}") ``` -------------------------------- ### Add a Person Vertex Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Inserts or updates a 'Person' vertex using `upsertVertex`. The vertex ID is the person's name, and it has no attributes in this example. This operation is idempotent. ```python results = conn.upsertVertex("Person", "Dan", {}) print(results) ``` -------------------------------- ### List Available Data Sources Source: https://context7.com/tigergraph/pytigergraph/llms.txt Retrieve a list of all configured data sources in the TigerGraph database. ```python sources = conn.getDataSources() print(f"Data sources: {sources}") ``` -------------------------------- ### Get All Edges of a Type Source: https://context7.com/tigergraph/pytigergraph/llms.txt Retrieves all edges of a specified type. This operation uses an interpreted query internally and supports limiting the number of results and specifying the output format. ```python all_follows = conn.getEdgesByType("FOLLOWS", fmt="df", limit=1000) ``` -------------------------------- ### Get Edge Count Source: https://context7.com/tigergraph/pytigergraph/llms.txt Retrieves the total number of edges of a specific type or edges originating from a particular source vertex. Useful for understanding graph density and connectivity. ```python total = conn.getEdgeCount("FOLLOWS") from_alice = conn.getEdgeCountFrom( sourceVertexType="Person", sourceVertexId="alice_123", edgeType="FOLLOWS" ) print(f"Total edges: {total}, From Alice: {from_alice}") ``` -------------------------------- ### Customize Headers for Resource Control Source: https://github.com/tigergraph/pytigergraph/blob/master/CHANGELOG.md Set connection-wide headers for query resource control using `customizeHeader()`. This allows specifying thread and memory limits. ```python customizeHeader(threadLimit=..., memoryLimit=...) ``` -------------------------------- ### GSQL Reserved Keyword Helpers Source: https://github.com/tigergraph/pytigergraph/blob/master/CHANGELOG.md Query the canonical set of GSQL reserved keywords using static methods. ```python getReservedKeywords() ``` ```python isReservedKeyword(name) ``` -------------------------------- ### Run Interpreted Query with pyTigerGraph Source: https://context7.com/tigergraph/pytigergraph/llms.txt Executes an interpreted GSQL query with parameters and prints the result. Ensure the graph name is correctly set in the query. ```python result = conn.runInterpretedQuery(""" INTERPRET QUERY (INT max_results) FOR GRAPH $graphname { SetAccum> @@top_users; start = {Person.*}; results = SELECT s FROM start:s WHERE s.score > 100 ORDER BY s.score DESC LIMIT max_results; PRINT results; } """, params={"max_results": 10}) print(result) ``` -------------------------------- ### Execute GSQL Statements with pyTigerGraph Source: https://context7.com/tigergraph/pytigergraph/llms.txt Executes GSQL statements directly for schema management and query creation. Ensure the connection is established before execution. ```python conn = TigerGraphConnection( host="http://localhost", graphname="social", username="tigergraph", password="tigergraph" ) # Execute GSQL statements result = conn.gsql(""" USE GRAPH social CREATE QUERY hello_world() FOR GRAPH social { PRINT "Hello, TigerGraph!"; } INSTALL QUERY hello_world ") print(result) ``` -------------------------------- ### Check TigerGraph Solution Status with echo Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Verifies if the TigerGraph Solution is online by sending an echo request. The function should respond with 'Hello GSQL' if the solution is accessible. ```python print(conn.echo()) ``` -------------------------------- ### Default TigerGraph Connection Configuration Source: https://github.com/tigergraph/pytigergraph/blob/master/tests/README.md This JSON object represents the hardcoded default configuration parameters used when a `testserver.json` file is not found. It includes essential connection details for a TigerGraph instance. ```json { "host": "http://127.0.0.1", "graphname": "tests", "username": "tigergraph", "password": "tigergraph", "gsqlSecret": "", "restppPort": "9000", "gsPort": "14240", "gsqlVersion": "", "userCert": None, "certPath": None, "sslPort": "443", "tgCloud": False, "gcp": False, } ``` -------------------------------- ### Create Vertex Loader for GDS Source: https://context7.com/tigergraph/pytigergraph/llms.txt Initialize a vertex loader for Graph Data Science tasks, allowing batched loading of vertex data with options for filtering, shuffling, and output format. ```python vertex_loader = conn.gds.vertexLoader( attributes=["x", "y", "train_mask", "val_mask", "test_mask"], batch_size=256, shuffle=True, filter_by="train_mask", # Only load vertices where train_mask=True output_format="dataframe" ) ``` -------------------------------- ### Delete Edges with WHERE Clause in PyTigerGraph Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Use the `delEdges` method with a WHERE clause to remove edges that meet specific criteria. This example deletes 'Likes' edges with a 'weight' less than 9.0. ```python # Stats before deleting ratings below 9.0 results = conn.getEdgeStats("Likes") edgeCnt = conn.getEdgeCount(edgeType="Likes") print("Before deleting ratings less than '9.0'") print(f"{edgeCnt} 'Likes' edges") print(json.dumps(results, indent=2)) print("-------------") results = conn.delEdges("Person", "Nick", edgeType="Likes", where="weight < 9.0") print(results) print("-------------") results = conn.getEdgeStats("Likes") edgeCnt = conn.getEdgeCount(edgeType="Likes") print("After deleting ratings less than '9.0' that Nick made") print(f"{edgeCnt} 'Likes' edges") print(json.dumps(results, indent=2)) ``` -------------------------------- ### Load All Vertex Data at Once with GDS Source: https://context7.com/tigergraph/pytigergraph/llms.txt Configure a vertex loader to load all data in a single batch. Useful for smaller datasets or when processing all data is required. ```python vertex_loader = conn.gds.vertexLoader( attributes={"Paper": ["x", "y"]}, # Specify per vertex type num_batches=1 ) all_data = vertex_loader.data print(f"Total vertices: {len(all_data)}") ``` -------------------------------- ### Get Edge Endpoint and Direction Information Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Determine the source and target vertex types for a given edge, and check if the edge is directed. Also retrieves the name of the reverse edge if it exists. ```python sourceVertex = conn.getEdgeSourceVertexType("Likes") targetVertex = conn.getEdgeTargetVertexType("Likes") directed = conn.isDirected("Likes") directedText = "is" if directed==True else "is not" reverseEdge = conn.getReverseEdge("Likes") print(f"Edge 'Likes' '{directedText} directed' with a source vertex type '{sourceVertex}' and a target vertex type '{targetVertex}'") if directed: print(f"The reverse edge is '{reverseEdge}'") ``` -------------------------------- ### Load Graph Data in Batches with pyTigerGraph Source: https://context7.com/tigergraph/pytigergraph/llms.txt Load entire graph batches or the full graph using graphLoader. Useful for large graphs and graph-level tasks. Supports PyG output format. ```python from pyTigerGraph import TigerGraphConnection conn = TigerGraphConnection( host="http://localhost", graphname="molecules", username="tigergraph", password="tigergraph" ) conn.getToken(conn.createSecret()) # Load graph in batches (for large graphs) graph_loader = conn.gds.graphLoader( v_in_feats=["atom_type", "charge"], v_out_labels=["is_aromatic"], e_in_feats=["bond_type"], batch_size=1000, # Edges per batch num_batches=10, shuffle=True, output_format="PyG" ) for batch in graph_loader: print(f"Graph batch with {batch.num_nodes} nodes, {batch.num_edges} edges") # Process batch... # Load entire graph at once full_loader = conn.gds.graphLoader( v_in_feats=["x"], v_out_labels=["y"], num_batches=1, output_format="PyG" ) full_graph = full_loader.data print(f"Full graph: {full_graph.num_nodes} nodes, {full_graph.num_edges} edges") ``` -------------------------------- ### Create Schema Change Job API Source: https://github.com/tigergraph/pytigergraph/blob/master/CHANGELOG.md Manage schema change jobs using the provided API. This includes creating, retrieving, running, and dropping schema change jobs. ```python createSchemaChangeJob() ``` ```python getSchemaChangeJobs() ``` ```python runSchemaChangeJob() ``` ```python dropSchemaChangeJobs() ``` -------------------------------- ### Upsert and Get Vertex Data Source: https://context7.com/tigergraph/pytigergraph/llms.txt Performs insert or update operations on single and multiple vertices. Supports attribute updates with special operators like increment and max. Also demonstrates retrieving vertex counts with and without filters. ```python from pyTigerGraph import TigerGraphConnection conn = TigerGraphConnection( host="http://localhost", graphname="social", username="tigergraph", password="tigergraph" ) # Upsert a single vertex (insert or update) count = conn.upsertVertex( vertexType="Person", vertexId="alice_123", attributes={ "name": "Alice Smith", "age": 30, "score": (100, "+"), # Increment score by 100 "embedding": [0.1, 0.2, 0.3] # Vector attribute } ) print(f"Upserted {count} vertex") # Output: Upserted 1 vertex # Upsert multiple vertices vertices = [ ("bob_456", {"name": "Bob Jones", "age": 25}), ("carol_789", {"name": "Carol White", "age": 35, "score": (50, "max")}), ] count = conn.upsertVertices("Person", vertices, atomic=True) print(f"Upserted {count} vertices") # Output: Upserted 2 vertices # Get vertex count total = conn.getVertexCount("Person") filtered = conn.getVertexCount("Person", where="age>25") all_types = conn.getVertexCount("*") # Returns dict of all types print(f"Total: {total}, Filtered: {filtered}, All: {all_types}") ``` -------------------------------- ### Create and View TigerGraph Secrets Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Demonstrates how to create a new secret with a specified alias and retrieve all accessible secrets for the current user account. This is useful for managing authentication credentials. ```python secret = conn.createSecret(alias="testSecret2") print(secret) print("---------------ի") print(conn.getSecrets()) ``` -------------------------------- ### Refresh and Delete Connection Tokens Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Manage connection tokens by refreshing an existing token with a specified lifespan or deleting a token. The lifespan is defined in seconds. ```python # Will give you a new token print(conn.refreshToken(secret, lifetime=2592000)) # 2,592,000 is 30 days worth of seconds # Deletes an existing token # print(conn.deleteToken(secret)) ``` -------------------------------- ### Run Graph Algorithms with Featurizer Source: https://context7.com/tigergraph/pytigergraph/llms.txt Utilize the featurizer to run TigerGraph GDS algorithms for feature generation. Supports listing algorithms, running PageRank, Louvain, and similarity algorithms. ```python from pyTigerGraph import TigerGraphConnection conn = TigerGraphConnection( host="http://localhost", graphname="social", username="tigergraph", password="tigergraph" ) conn.getToken(conn.createSecret()) # Get the featurizer feat = conn.gds.featurizer() # List available algorithms algorithms = feat.listAlgorithms() print(f"Available algorithms: {algorithms}") # Run PageRank result = feat.runAlgorithm( "tg_pagerank", params={ "v_type": "Person", "e_type": "FOLLOWS", "max_change": 0.001, "max_iter": 25, "damping": 0.85, "top_k": 100, "print_results": True, "result_attribute": "pagerank" # Store results in vertex attribute } ) print(f"PageRank results: {result}") # Run community detection (Louvain) result = feat.runAlgorithm( "tg_louvain", params={ "v_type_set": ["Person"], "e_type_set": ["FOLLOWS"], "result_attribute": "community_id" } ) # Run centrality algorithms betweenness = feat.runAlgorithm( "tg_betweenness_cent", params={ "v_type": "Person", "e_type": "FOLLOWS", "result_attribute": "betweenness" } ) # Install an algorithm if not already installed feat.installAlgorithm("tg_jaccard_nbor_ss") # Run similarity algorithm similarity = feat.runAlgorithm( "tg_jaccard_nbor_ss", params={ "source": "alice_123", "v_type": "Person", "e_type": "FOLLOWS", "top_k": 10 } ) print(f"Similar users to Alice: {similarity}") ``` -------------------------------- ### Create Graph with Existing Types Source: https://github.com/tigergraph/pytigergraph/blob/master/CHANGELOG.md When creating a new graph, you can optionally include existing global vertex and edge types. Use `vertexTypes=['*']` to include all global types. ```python createGraph("g", vertexTypes=["Person"], edgeTypes=["Knows"]) ``` -------------------------------- ### Iterate Through Neighbor Loader Batches Source: https://context7.com/tigergraph/pytigergraph/llms.txt Process data in batches generated by the neighbor loader, typically used within a GNN training loop. Each batch contains nodes, edges, features, and labels. ```python for batch in neighbor_loader: print(f"Batch: {batch}") print(f" Nodes: {batch.num_nodes}") print(f" Edges: {batch.num_edges}") print(f" Features shape: {batch.x.shape}") print(f" Labels shape: {batch.y.shape}") ``` -------------------------------- ### Synchronous Connection to TigerGraph Source: https://github.com/tigergraph/pytigergraph/blob/master/README.md Establish a synchronous connection to a TigerGraph database using provided host, graphname, username, and password. The echo() method can be used to verify the connection. ```python from pyTigerGraph import TigerGraphConnection conn = TigerGraphConnection( host="http://localhost", graphname="my_graph", username="tigergraph", password="tigergraph", ) print(conn.echo()) ``` -------------------------------- ### Retrieve TigerGraph Version Information Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieves version information for all components of the TigerGraph Solution using getVersion(), or for a specific component like 'gle' using getVer(). ```python print(json.dumps(conn.getVersion(), indent=2)) print("-----------------") print(json.dumps(conn.getVer("gle"), indent=2)) ``` -------------------------------- ### Concurrent Query Execution with pyTigerGraph Source: https://context7.com/tigergraph/pytigergraph/llms.txt Execute queries in parallel using ThreadPoolExecutor for synchronous operations or asyncio for asynchronous operations, enabling high-throughput workloads. ```python from pyTigerGraph import TigerGraphConnection, AsyncTigerGraphConnection from concurrent.futures import ThreadPoolExecutor, as_completed import asyncio ``` -------------------------------- ### Find All Paths Between Vertices Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Retrieve all possible paths between specified vertices, with an upper limit on the number of edge traversals. This is useful for exploring connections in the graph. ```python results = conn.allPaths([("Person", "Dan")], [("Person", "Ben")], 4) print(json.dumps(results, indent=2)) ``` -------------------------------- ### Asynchronous Parallel Query Execution Source: https://context7.com/tigergraph/pytigergraph/llms.txt Utilize asyncio for efficient asynchronous parallel query execution, especially beneficial for I/O-bound tasks. Requires Python 3.7+. ```python import asyncio from pyTigerGraph import AsyncTigerGraphConnection async def fetch_all_profiles(): async with AsyncTigerGraphConnection( host="http://localhost", graphname="social", username="tigergraph", password="tigergraph" ) as conn: tasks = [ conn.runInstalledQuery("get_user_profile", {"user_id": (uid,)}) for uid in user_ids ] results = await asyncio.gather(*tasks, return_exceptions=True) for uid, result in zip(user_ids, results): if isinstance(result, Exception): print(f"Error for {uid}: {result}") else: print(f"User {uid}: {result}") asyncio.run(fetch_all_profiles()) ``` -------------------------------- ### Load Data from String using Loading Job Source: https://context7.com/tigergraph/pytigergraph/llms.txt Load data directly from a string into TigerGraph using a predefined loading job. Specify the data string, file tag, job name, and separator. ```python csv_data = """alice,Alice Smith,30 bob,Bob Jones,25 carol,Carol White,35""" result = conn.runLoadingJobWithData( data=csv_data, fileTag="f", jobName="load_persons", sep="," ) print(f"Loaded from string: {result}") ``` -------------------------------- ### Retrieve Vertices with Filtering and Pagination Source: https://context7.com/tigergraph/pytigergraph/llms.txt Fetches vertices of a specific type with options for selecting attributes, filtering by conditions, limiting results, sorting, and specifying the output format. Use 'py' for Python dictionaries, 'json' for JSON strings, or 'df' for Pandas DataFrames. ```python vertices = conn.getVertices( vertexType="Person", select="name,age", where="age>=25", limit=10, sort="-age", # Descending by age fmt="py" # Options: "py", "json", "df" ) for v in vertices: print(f"{v['v_id']}: {v['attributes']}") ``` -------------------------------- ### Upsert Vertices and Edges Source: https://github.com/tigergraph/pytigergraph/blob/master/examples/pyTigergraph_101.ipynb Use `upsertVertices` and `upsertEdges` to load data. Only one vertex or edge type can be loaded per upsert command. ```python results = conn.upsertVertices("Person", people) print(results) results = conn.upsertVertices("Movie", movies) print(results) results = conn.upsertEdges("Person", "Likes", "Movie", ratings) print(results) ```