### Install CogDB Source: https://github.com/arun1729/cog/blob/master/README.md Install the cogdb package using pip. This is the first step to using CogDB in your Python project. ```bash pip install cogdb ``` -------------------------------- ### Serving a Graph Over HTTP Source: https://context7.com/arun1729/cog/llms.txt Starts an HTTP server to make the graph queryable over the network. ```APIDOC ## Serving a Graph Over HTTP The `serve()` method starts an HTTP server to make the graph queryable over the network. ### Method `serve(port=8080, writable=False, share=False)` ### Parameters - **port** (int) - Optional - The port to serve the graph on. Defaults to 8080. - **writable** (bool) - Optional - Whether to allow write operations. Defaults to False. - **share** (bool) - Optional - Whether to enable public sharing via CogDB relay. Defaults to False. ### Request Example ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Serve the graph (read-only by default) g.serve(port=8080) # Allow write operations g.serve(port=8080, writable=True) # Serve multiple graphs on the same port g1 = Graph("users") g2 = Graph("products") g1.serve(port=8080) g2.serve(port=8080) # Both accessible at /{graph_name}/ # Public sharing via CogDB relay g.serve(port=8080, share=True) print(g.share_url()) # https://abc123.s.cogdb.io/ # Stop serving g.stop() ``` ``` -------------------------------- ### Start Graph Traversal with v() Source: https://context7.com/arun1729/cog/llms.txt Initiate graph traversals using the `v()` method. Call `v()` without arguments to start from all vertices, or provide a vertex ID to begin from a specific point in the graph. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") g.put("alice", "status", "active") # Start from a specific vertex g.v("alice").out("follows").all() # {'result': [{'id': 'bob'}]} # Start from all vertices g.v().has("status", "active").all() # {'result': [{'id': 'alice'}]} ``` -------------------------------- ### Serve Graph Over HTTP Source: https://context7.com/arun1729/cog/llms.txt Starts an HTTP server to make the graph queryable remotely. By default, it's read-only. Set `writable=True` to enable write operations. Multiple graphs can be served on the same port by accessing them via their name in the URL path. Public sharing is possible with `share=True`. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Serve the graph (read-only by default) g.serve(port=8080) # Allow write operations g.serve(port=8080, writable=True) # Serve multiple graphs on the same port g1 = Graph("users") g2 = Graph("products") g1.serve(port=8080) g2.serve(port=8080) # Both accessible at /{graph_name}/ # Public sharing via CogDB relay g.serve(port=8080, share=True) print(g.share_url()) # https://abc123.s.cogdb.io/ # Stop serving g.stop() ``` -------------------------------- ### Paginate Graph Results with limit() and skip() Source: https://context7.com/arun1729/cog/llms.txt Control result pagination using `limit()` to set the number of items per page and `skip()` to define the starting point. Useful for handling large datasets. ```python from cog.torque import Graph g = Graph("data") for i in range(10): g.put(f"item{i}", "type", "record") # Get first 3 results g.v().limit(3).all() ``` ```python # Skip first 5, get next 3 g.v().skip(5).limit(3).all() ``` ```python # Pagination pattern page_size = 3 page_num = 2 g.v().skip(page_num * page_size).limit(page_size).all() ``` -------------------------------- ### Count Outgoing Vertices Source: https://github.com/arun1729/cog/blob/master/README.md Starting from a specific vertex ('bob'), this query follows all outgoing edges and counts the number of connected vertices. It's an efficient way to get a cardinality. ```python g.v("bob").out().count() ``` -------------------------------- ### Traverse Outgoing Edges and Vertices Source: https://github.com/arun1729/cog/blob/master/README.md Starting from a specific vertex ('bob'), this query follows all outgoing edges and lists the connected vertices. It demonstrates basic graph traversal. ```python g.v("bob").out().all() ``` -------------------------------- ### Filter outgoing edges by string prefix Source: https://github.com/arun1729/cog/blob/master/README.md Starting from a specific vertex, traverse outgoing 'follows' edges and filter the results to include only those starting with 'f'. ```python g.v("emily").out("follows").filter(func=lambda x: x.startswith("f")).all() ``` -------------------------------- ### Breadth-First Search (BFS) traversal Source: https://github.com/arun1729/cog/blob/master/README.md Perform a Breadth-First Search starting from a vertex, exploring level by level up to a specified maximum depth. ```python g.v("alice").bfs(predicates="follows", max_depth=2).all() ``` -------------------------------- ### Depth-First Search (DFS) traversal Source: https://github.com/arun1729/cog/blob/master/README.md Perform a Depth-First Search starting from a vertex, exploring deeply before backtracking, up to a specified maximum depth. ```python g.v("alice").dfs(predicates="follows", max_depth=3).all() ``` -------------------------------- ### Get All Results with all() Source: https://context7.com/arun1729/cog/llms.txt Retrieve all vertices from a traversal using `all()`. Can optionally include edge information by passing `'e'` as an argument. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("charlie", "follows", "bob") # Get all results g.v("bob").inc("follows").all() ``` ```python # Include edge information g.v("bob").inc().all('e') ``` -------------------------------- ### Bidirectional BFS traversal Source: https://github.com/arun1729/cog/blob/master/README.md Perform a BFS traversal considering edges in both directions ('both') from a starting vertex. ```python g.v("bob").bfs(direction="both", max_depth=2).all() ``` -------------------------------- ### Get Graph Structure with graph() Source: https://context7.com/arun1729/cog/llms.txt Format traversal results into nodes and links suitable for visualization libraries like D3.js using the `graph()` method. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Get graph structure for D3.js visualization result = g.v("alice").out("follows").out("follows").graph() ``` -------------------------------- ### Get Embedding Statistics Source: https://github.com/arun1729/cog/blob/master/README.md Retrieve statistics about the loaded embeddings, including the total count and dimensionality. ```python g.embedding_stats() ``` -------------------------------- ### Getting Embedding Statistics Source: https://context7.com/arun1729/cog/llms.txt Retrieves statistics about the stored embeddings in a graph. ```APIDOC ## Getting Embedding Statistics The `embedding_stats()` method returns information about stored embeddings. ### Method `embedding_stats()` ### Parameters None ### Response Example ```json { "count": 2, "dimensions": 4 } ``` ``` -------------------------------- ### Get Embedding Statistics Source: https://context7.com/arun1729/cog/llms.txt Retrieves statistics about stored embeddings in a graph. Ensure embeddings are added using `put_embedding` before calling this method. ```python from cog.torque import Graph g = Graph("vectors") g.put_embedding("word1", [0.1, 0.2, 0.3, 0.4]) g.put_embedding("word2", [0.5, 0.6, 0.7, 0.8]) g.embedding_stats() # {'count': 2, 'dimensions': 4} ``` -------------------------------- ### Create and Query a Graph in Python Source: https://github.com/arun1729/cog/blob/master/README.md Demonstrates creating a graph, adding data using 'put', and performing basic queries with Torque. The graph can also be served over HTTP. ```python from cog.torque import Graph # Create a graph and add data g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") g.put("bob", "status", "active") # Query g.v("alice").out("follows").all() # → {'result': [{'id': 'bob'}]} g.v().has("status", "active").all() # → {'result': [{'id': 'bob'}]} g.v("alice").out("follows").out("follows").all() # → {'result': [{'id': 'charlie'}]} # Serve your graph over HTTP g.serve() # Now queryable at http://localhost:8080 # Expose to the internet with ngrok # $ ngrok http 8080 # Query your graph from anywhere: https://your-ngrok-url.ngrok.io ``` -------------------------------- ### Load and show an existing visualization Source: https://github.com/arun1729/cog/blob/master/README.md Load a previously saved visualization by its tag using `getv()` and then display it with `show()`. ```python g.getv('follows').show() ``` -------------------------------- ### Create or Load a CogDB Graph Source: https://context7.com/arun1729/cog/llms.txt Instantiate a `Graph` object to create a new graph database or load an existing one. Configuration options include custom data directories, path prefixes, and flush intervals for performance tuning. ```python from cog.torque import Graph # Create a new graph (or load existing) g = Graph("social") # With custom configuration g = Graph("mydb", cog_home="my_data", cog_path_prefix="/var/lib") # Performance tuning - flush every 100 writes for bulk inserts g = Graph("mydb", flush_interval=100) # Manual flush mode for maximum speed g = Graph("mydb", flush_interval=0) g.put_batch(large_dataset) g.sync() # Flush when done ``` -------------------------------- ### Show graph visualization Source: https://github.com/arun1729/cog/blob/master/README.md Visualize the graph interactively in Jupyter/Colab or open a browser window from the command line. Requires the `show()` method. ```python g.v().out("follows").show() ``` -------------------------------- ### Serve a graph over the network Source: https://github.com/arun1729/cog/blob/master/README.md Create a graph, add data, and serve it over HTTP using the `serve()` method. This allows remote access to the graph. ```python from cog.torque import Graph # Create and serve a graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") g.serve(port=8080) ``` -------------------------------- ### Listing and Switching Graphs Source: https://context7.com/arun1729/cog/llms.txt Manages multiple graphs using `ls()` and `use()` methods. ```APIDOC ## Listing and Switching Graphs The `ls()` and `use()` methods manage multiple graphs. ### Method `ls()` Lists all available graphs. ### Method `use(graph_name)` Switches the current graph context to the specified graph. ### Request Example ```python from cog.torque import Graph g = Graph("default") # List all graphs g.ls() # ['default', 'social', 'products'] # Switch to a different graph g.use("social").v("alice").all() ``` ``` -------------------------------- ### Configure Graph Instance with CogConfig Source: https://context7.com/arun1729/cog/llms.txt Utilizes `CogConfig` to provide isolated configuration settings for a graph instance. This allows for custom `COG_HOME` and `COG_PATH_PREFIX` directories, separating application data. ```python from cog.config import CogConfig from cog.torque import Graph # Create custom configuration cfg = CogConfig( COG_HOME="my_app_data", COG_PATH_PREFIX="/var/lib/myapp" ) # Use configuration with graph g = Graph("mydb", config=cfg) ``` -------------------------------- ### Creating Persistent Views with view() Source: https://context7.com/arun1729/cog/llms.txt Creates a named, persistent HTML visualization that can be saved and shared. ```APIDOC ## Creating Persistent Views with view() The `view()` method creates a named, persistent HTML visualization that can be saved and shared. ### Method `view(name)` ### Parameters - **name** (str) - Required - The name for the persistent view. ### Response - **url** (str) - The URL to the saved HTML view. ### Request Example ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Create and persist a view view = g.v().tag("from").out("follows").tag("to").view("social_network") print(view.url) # file:///path/to/cog_home/views/social_network.html # List all saved views g.lsv() # ['social_network'] # Load and show existing view g.getv('social_network').show() ``` ``` -------------------------------- ### List and Switch Between Graphs Source: https://context7.com/arun1729/cog/llms.txt Manages multiple graphs using `ls()` to list available graphs and `use()` to switch the current graph context. This allows for organizing and accessing different datasets within the same CogDB instance. ```python from cog.torque import Graph g = Graph("default") # List all graphs g.ls() # ['default', 'social', 'products'] # Switch to a different graph g.use("social").v("alice").all() ``` -------------------------------- ### Performance tuning for bulk inserts Source: https://github.com/arun1729/cog/blob/master/README.md Control graph flush behavior for performance tuning during bulk inserts. Options include flushing every write (default), auto-flushing at intervals, or manual flushing with `sync()`. ```python # Default: flush every write (safest) g = Graph("mydb") # Fast mode: flush every 100 writes (auto-enables async) g = Graph("mydb", flush_interval=100) # Manual flush only (fastest for bulk loads) g = Graph("mydb", flush_interval=0) g.put_batch(large_dataset) g.sync() # Flush when done ``` -------------------------------- ### Using CogConfig Source: https://context7.com/arun1729/cog/llms.txt Provides isolated configuration for each graph instance. ```APIDOC ## Using CogConfig The `CogConfig` class provides isolated configuration for each graph instance. ### Method `CogConfig(COG_HOME=None, COG_PATH_PREFIX=None)` ### Parameters - **COG_HOME** (str) - Optional - Specifies the directory for Cog data. - **COG_PATH_PREFIX** (str) - Optional - Specifies a path prefix for Cog data. ### Request Example ```python from cog.config import CogConfig from cog.torque import Graph # Create custom configuration cfg = CogConfig( COG_HOME="my_app_data", COG_PATH_PREFIX="/var/lib/myapp" ) # Use configuration with graph g = Graph("mydb", config=cfg) ``` ``` -------------------------------- ### Navigate Back with `back()` Source: https://context7.com/arun1729/cog/llms.txt Use `back()` to return to vertices previously saved with `tag()`. This preserves the traversal context from the tagged point. ```python from cog.torque import Graph g = Graph("paths") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Return to tagged position result = g.v("alice").tag("start").out("follows").out("follows").back("start").all() # {'result': [{'start': 'alice', 'id': 'alice'}]} ``` -------------------------------- ### List all available views Source: https://github.com/arun1729/cog/blob/master/README.md List all saved graph visualizations (views) using the `lsv()` method. ```python g.lsv() ``` -------------------------------- ### Customize graph visualization Source: https://github.com/arun1729/cog/blob/master/README.md Customize the graph visualization by adjusting height, width, and color theme using parameters in the `show()` method. ```python g.v().out("follows").show(height=600, width=800, dark=True) ``` -------------------------------- ### Follow Incoming Edges Source: https://context7.com/arun1729/cog/llms.txt Use `inc()` to traverse incoming edges to a vertex. This is useful for finding which vertices point to a specific vertex. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("charlie", "follows", "bob") g.put("dani", "follows", "bob") # Who follows Bob? g.v("bob").inc("follows").all() # {'result': [{'id': 'alice'}, {'id': 'charlie'}, {'id': 'dani'}]} ``` ```python # Follow edges in reverse g.v("bob").inc().all() # All incoming edges # {'result': [{'id': 'alice'}, {'id': 'charlie'}, {'id': 'dani'}]} ``` -------------------------------- ### Create Graph from CSV Source: https://github.com/arun1729/cog/blob/master/README.md Load data into a new graph from a CSV file. Specify the primary key column for unique identification. ```python from cog.torque import Graph g = Graph("books") g.load_csv('test/test-data/books.csv', "book_id") ``` -------------------------------- ### Breadth-First Search with bfs() Source: https://context7.com/arun1729/cog/llms.txt Perform breadth-first traversal using `bfs()`. Useful for finding shortest paths in unweighted graphs. Supports depth limits, specific depth retrieval, stopping at a target, and bidirectional traversal. ```python from cog.torque import Graph g = Graph("network") g.put("alice", "knows", "bob") g.put("alice", "knows", "charlie") g.put("bob", "knows", "dani") g.put("dani", "knows", "eve") # BFS with depth limit g.v("alice").bfs(predicates="knows", max_depth=2).all() ``` ```python # Only vertices at specific depth g.v("alice").bfs(max_depth=2, min_depth=2).all() ``` ```python # Stop at target vertex g.v("alice").bfs(until=lambda v: v == "dani").all() ``` ```python # Bidirectional traversal g.v("bob").bfs(direction="both", max_depth=2).all() ``` -------------------------------- ### Connect to and query a remote graph Source: https://github.com/arun1729/cog/blob/master/README.md Connect to a graph served over the network using `Graph.connect()` and query it using standard Cog methods as if it were local. ```python from cog.torque import Graph # Connect to remote graph remote = Graph.connect("http://localhost:8080/social") # Query just like a local graph remote.v("alice").out("follows").all() ``` -------------------------------- ### Create Persistent HTML Graph Views Source: https://context7.com/arun1729/cog/llms.txt Generates a named, persistent HTML visualization of a graph view that can be saved and shared. Use `lsv()` to list saved views and `getv()` to load and display them. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Create and persist a view view = g.v().tag("from").out("follows").tag("to").view("social_network") print(view.url) # file:///path/to/cog_home/views/social_network.html # List all saved views g.lsv() # ['social_network'] # Load and show existing view g.getv('social_network').show() ``` -------------------------------- ### Persist graph visualization to HTML Source: https://github.com/arun1729/cog/blob/master/README.md Save the graph visualization to an HTML file using the `view()` method. The output URL points to the generated file. ```python g.v().tag("from").out("follows").tag("to").view("follows").url ``` -------------------------------- ### Load GloVe Embeddings Source: https://context7.com/arun1729/cog/llms.txt Loads pre-trained GloVe word embeddings from a file. Useful for NLP tasks and semantic analysis. Can limit the number of embeddings loaded. ```python from cog.torque import Graph g = Graph("nlp") # Load GloVe embeddings (one-liner!) count = g.load_glove("glove.6B.100d.txt", limit=50000) print(f"Loaded {count} embeddings") # Now use semantic search g.k_nearest("machine", k=5).all() ``` -------------------------------- ### Depth-First Search with dfs() Source: https://context7.com/arun1729/cog/llms.txt Perform depth-first traversal using `dfs()`. Explores deeply before backtracking. Supports depth control, direction specification, and custom stop conditions. ```python from cog.torque import Graph g = Graph("tree") g.put("root", "child", "a") g.put("root", "child", "b") g.put("a", "child", "a1") g.put("a", "child", "a2") g.put("b", "child", "b1") # DFS traversal g.v("root").dfs(predicates="child", max_depth=3).all() ``` ```python # DFS with direction control g.v("a1").dfs(direction="inc", max_depth=2).all() ``` ```python # DFS with custom stop condition g.v("root").dfs(until=lambda v: v.startswith("b")).all() ``` -------------------------------- ### Interactive Graph Display with show() Source: https://context7.com/arun1729/cog/llms.txt Renders traversal results as an interactive D3.js graph in Jupyter notebooks or browsers. ```APIDOC ## Interactive Graph Display with show() The `show()` method renders the traversal result as an interactive D3.js graph in Jupyter notebooks or browsers. ### Method `show(height=None, width=None, dark=False)` ### Parameters - **height** (int) - Optional - The height of the visualization. - **width** (int) - Optional - The width of the visualization. - **dark** (bool) - Optional - Whether to use a dark theme for the visualization. ### Request Example ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Show interactive visualization g.v().out("follows").show() # Customize appearance g.v().out("follows").show(height=600, width=800, dark=True) ``` ``` -------------------------------- ### Skip and limit traversal results Source: https://github.com/arun1729/cog/blob/master/README.md Skip the first N vertices and then limit the results to the next M vertices using `skip()` and `limit()`. ```python g.v().skip(2).limit(2).all() ``` -------------------------------- ### Navigate back to a tagged vertex Source: https://github.com/arun1729/cog/blob/master/README.md Return to a previously tagged vertex in the traversal path using the `back()` method, preserving the path history. ```python g.v("alice").tag("start").out("follows").out("follows").back("start").all() ``` -------------------------------- ### Load N-Triples RDF Data Source: https://context7.com/arun1729/cog/llms.txt Imports data in the RDF N-Triples format. Suitable for knowledge graphs and semantic data. ```python from cog.torque import Graph g = Graph("knowledge") # Load N-Triples file (format: subject predicate object) g.load_triples("/path/to/data.nt", "knowledge") # Query loaded data g.v().has("type", "Person").all() ``` -------------------------------- ### Load Gensim Model Embeddings Source: https://context7.com/arun1729/cog/llms.txt Imports embeddings from Gensim Word2Vec or FastText models. Requires a trained or loaded Gensim model object. ```python from cog.torque import Graph from gensim.models import Word2Vec # Train or load a Gensim model model = Word2Vec(sentences, vector_size=100, window=5, min_count=1) g = Graph("custom_embeddings") count = g.load_gensim(model) print(f"Loaded {count} embeddings") ``` -------------------------------- ### Load GloVe Embeddings Source: https://github.com/arun1729/cog/blob/master/README.md Load pre-trained word embeddings from a GloVe file into CogDB. This is a convenient one-liner for initializing embeddings. ```python # Load GloVe embeddings (one-liner!) count = g.load_glove("glove.6B.100d.txt", limit=50000) print(f"Loaded {count} embeddings") ``` -------------------------------- ### Scan Vertices and Edges with scan() Source: https://context7.com/arun1729/cog/llms.txt Retrieve a sample of vertices or edges from the graph using `scan()`. The second argument specifies whether to scan edges ('e'). ```python from cog.torque import Graph g = Graph("data") g.put("alice", "follows", "bob") g.put("bob", "status", "active") # Scan vertices (default) g.scan(3) ``` ```python # Scan edges g.scan(10, 'e') ``` -------------------------------- ### CogDB HTTP API Endpoints Source: https://context7.com/arun1729/cog/llms.txt Illustrates common HTTP API endpoints for interacting with a served CogDB graph. These include endpoints for status, statistics, query execution, mutations, and batch operations. ```bash # Get server status page (HTML) curl http://localhost:8080/ # Get graph status page curl http://localhost:8080/social/ # Get graph statistics (JSON) curl http://localhost:8080/social/stats # Execute a Torque query curl -X POST http://localhost:8080/social/query \ -H "Content-Type: application/json" \ -d '{"q": "v(\"alice\").out(\"follows\").all()"}' # Write operations (requires writable=True) curl -X POST http://localhost:8080/social/mutate \ -H "Content-Type: application/json" \ -d '{"op": "put", "args": ["alice", "knows", "charlie"]}' # Batch insert curl -X POST http://localhost:8080/social/mutate \ -H "Content-Type: application/json" \ -d '{"op": "put_batch", "args": [["a","r","b"],["c","r","d"]]}' ``` -------------------------------- ### Load Graph from Edgelist File Source: https://github.com/arun1729/cog/blob/master/README.md Load graph data from an edgelist file. This format typically represents connections between vertices. ```python from cog.torque import Graph g = Graph(graph_name="people") g.load_edgelist("/path/to/edgelist", "people") ``` -------------------------------- ### Bulk insert using put_batch Source: https://github.com/arun1729/cog/blob/master/README.md Insert multiple triples into the graph efficiently using `put_batch()`. This is significantly faster for large datasets compared to individual `put()` calls. ```python from cog.torque import Graph g = Graph("people") # Insert multiple triples at once - significantly faster for large graphs g.put_batch([ ("alice", "follows", "bob"), ("bob", "follows", "charlie"), ("charlie", "follows", "alice"), ("alice", "likes", "pizza"), ("bob", "likes", "tacos"), ]) ``` -------------------------------- ### List incoming vertices Source: https://github.com/arun1729/cog/blob/master/README.md Retrieve all vertices that have incoming edges to a specified vertex using the `inc()` method. ```python g.v("bob").inc().all() ``` -------------------------------- ### Load Edge List Data Source: https://context7.com/arun1729/cog/llms.txt Imports graph data from a simple edge list file, defining connections between vertices. Can specify a custom predicate. ```python from cog.torque import Graph g = Graph("network") # Load edge list (format: vertex1 vertex2) g.load_edgelist("/path/to/edges.txt", "network") # Or with custom predicate g.load_edgelist("/path/to/edges.txt", "network", predicate="connects") ``` -------------------------------- ### Connect to Remote CogDB Graphs Source: https://context7.com/arun1729/cog/llms.txt Establishes a connection to a remote CogDB server using its URL. Once connected, graphs can be queried locally. Supports connections via direct URLs, ngrok, or CogDB share URLs. ```python from cog.torque import Graph # Connect to remote graph remote = Graph.connect("http://localhost:8080/social") # Query just like a local graph remote.v("alice").out("follows").all() # {'result': [{'id': 'bob'}]} # Via ngrok or share URL remote = Graph.connect("https://abc123.ngrok.io/my_graph") remote.v().count() ``` -------------------------------- ### Update CogDB Configuration Source: https://github.com/arun1729/cog/blob/master/README.md Modify CogDB configuration settings, such as the home directory, before initializing a Cog instance. This allows for custom storage locations. ```python from cog import config config.COG_HOME = "app1_home" data = ('user_data:id=1', '{"firstname":"Hari","lastname":"seldon"}') cog = Cog(config) cog.create_or_load_namespace("test") cog.create_table("db_test", "test") cog.put(data) scanner = cog.scanner() for r in scanner: print r ``` -------------------------------- ### Connecting to Remote Graphs Source: https://context7.com/arun1729/cog/llms.txt Connects to a remote CogDB server using the `Graph.connect()` class method. ```APIDOC ## Connecting to Remote Graphs The `Graph.connect()` class method connects to a remote CogDB server. ### Method `Graph.connect(url)` ### Parameters - **url** (str) - Required - The URL of the remote CogDB server. ### Response - **Graph** - A Graph object representing the remote graph. ### Request Example ```python from cog.torque import Graph # Connect to remote graph remote = Graph.connect("http://localhost:8080/social") # Query just like a local graph remote.v("alice").out("follows").all() # {'result': [{'id': 'bob'}]} # Via ngrok or share URL remote = Graph.connect("https://abc123.ngrok.io/my_graph") remote.v().count() ``` ``` -------------------------------- ### Export Graph Data to File Source: https://context7.com/arun1729/cog/llms.txt Writes all graph triples to a file in various formats like N-Triples, CSV, or TSV. Supports strict W3C N-Triples format. ```python from cog.torque import Graph g = Graph("data") g.put("alice", "knows", "bob") # Export as N-Triples (default) g.export("graph.nt") # Export as CSV g.export("graph.csv", fmt="csv") # Export as TSV g.export("graph.tsv", fmt="tsv") # W3C strict N-Triples format g.export("graph.nt", strict=True) ``` -------------------------------- ### Load Graph from N-Triples File Source: https://github.com/arun1729/cog/blob/master/README.md Load graph data from an N-Triples file, a serialization format for RDF. This format represents graph data as subject-predicate-object triples. ```python from cog.torque import Graph g = Graph(graph_name="people") g.load_triples("/path/to/triples.nt", "people") ``` -------------------------------- ### Query Followers of a Vertex Source: https://github.com/arun1729/cog/blob/master/README.md Retrieve the 'follows' relationship for a specified vertex. ```python f.v().has('name','bob').out('follows').all() ``` -------------------------------- ### Export All Triples with triples() Source: https://context7.com/arun1729/cog/llms.txt Retrieve all triples (subject, predicate, object) from the graph as a list of tuples using the `triples()` method. ```python from cog.torque import Graph g = Graph("data") g.put("alice", "follows", "bob") g.put("bob", "status", "active") # Get all triples g.triples() ``` -------------------------------- ### Query Followers of Another Vertex Source: https://github.com/arun1729/cog/blob/master/README.md Retrieve the 'follows' relationship for a different specified vertex. ```python f.v().has('name','fred').out('follows').all() ``` -------------------------------- ### Display Interactive Graph Visualization Source: https://context7.com/arun1729/cog/llms.txt Renders graph traversal results as an interactive D3.js graph. This is useful for in-browser or Jupyter notebook visualizations. Customize height, width, and theme using optional parameters. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Show interactive visualization g.v().out("follows").show() # Customize appearance g.v().out("follows").show(height=600, width=800, dark=True) ``` -------------------------------- ### Find k-Nearest Neighbors in Graph Source: https://github.com/arun1729/cog/blob/master/README.md Search for the k most similar vertices to a given vertex within the graph. ```python # Search within graph vertices g.v().k_nearest("orange", k=2).all() ``` -------------------------------- ### BFS traversal with depth range Source: https://github.com/arun1729/cog/blob/master/README.md Perform a BFS traversal and filter results to include only vertices at a specific depth range using `min_depth` and `max_depth`. ```python # Only vertices at exactly depth 2 g.v("alice").bfs(max_depth=2, min_depth=2).all() ``` -------------------------------- ### BFS traversal until a target is met Source: https://github.com/arun1729/cog/blob/master/README.md Perform a BFS traversal that stops when a specified condition (e.g., reaching a target vertex) is met, using the `until` predicate. ```python g.v("alice").bfs(until=lambda v: v == "fred").all() ``` -------------------------------- ### Insert Triples using put Source: https://github.com/arun1729/cog/blob/master/README.md Use the 'put' method to insert individual triples (node-edge-node) into the graph. This is suitable for adding structured relationships. ```python from cog.torque import Graph g = Graph("people") g.put("alice","follows","bob") g.put("bob","follows","fred") g.put("bob","status","cool_person") g.put("charlie","follows","bob") g.put("charlie","follows","dani") g.put("dani","follows","bob") g.put("dani","follows","greg") g.put("dani","status","cool_person") g.put("emily","follows","fred") g.put("fred","follows","greg") g.put("greg","status","cool_person") g.put("bob","score","5") g.put("greg","score","10") g.put("alice","score","7") g.put("dani","score","100") ``` -------------------------------- ### Load CSV Data into Graph Source: https://context7.com/arun1729/cog/llms.txt Imports data from a CSV file, using a specified column as the vertex ID. Useful for structured data sources. ```python from cog.torque import Graph g = Graph("books") # Load CSV with specified ID column g.load_csv('books.csv', "book_id") # Query the loaded data - find books with rating > 4.0 g.v().out("average_rating", func=lambda x: float(x) > 4.0).inc().out("title").all() ``` -------------------------------- ### Find k-Nearest Neighbors Directly Source: https://github.com/arun1729/cog/blob/master/README.md Search for the k most similar embeddings directly, without needing to specify a vertex via `g.v()`. ```python # Or search ALL embeddings directly (no g.v() needed) g.k_nearest("orange", k=2).all() ``` -------------------------------- ### Count Results with count() Source: https://context7.com/arun1729/cog/llms.txt Obtain the number of vertices in the current traversal using the `count()` method. Useful for aggregation and statistics. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("charlie", "follows", "bob") g.put("dani", "follows", "bob") # Count followers g.v("bob").inc("follows").count() ``` ```python # Count all vertices g.v().count() ``` -------------------------------- ### Follow Outgoing Edges Source: https://context7.com/arun1729/cog/llms.txt Use `out()` to traverse outgoing edges from a vertex. Specify an edge type to filter the traversal. ```python from cog.torque import Graph g = Graph("people") g.put("alice", "follows", "bob") g.put("alice", "knows", "charlie") g.put("bob", "follows", "dani") # Follow all outgoing edges g.v("alice").out().all() # {'result': [{'id': 'bob'}, {'id': 'charlie'}]} ``` ```python # Follow specific edge type g.v("alice").out("follows").all() # {'result': [{'id': 'bob'}]} ``` ```python # Chain traversals - friends of friends g.v("alice").out("follows").out("follows").all() # {'result': [{'id': 'dani'}]} ``` ```python # Follow multiple edge types g.v("alice").out(["follows", "knows"]).all() # {'result': [{'id': 'bob'}, {'id': 'charlie'}]} ``` -------------------------------- ### Combine Graph Traversal with Similarity Search Source: https://github.com/arun1729/cog/blob/master/README.md Find vertices that match a specific graph property (e.g., type 'citrus') and are also similar to a reference embedding above a certain threshold. ```python # Find citrus fruits similar to orange g.v().has("type", "citrus").sim("orange", ">", 0.8).all() ``` -------------------------------- ### Store Vector Embeddings Source: https://context7.com/arun1729/cog/llms.txt Stores vector embeddings for text strings using `put_embedding` for individual entries or `put_embeddings_batch` for efficient bulk insertion. ```python from cog.torque import Graph g = Graph("fruits") # Store embeddings manually g.put("orange", "type", "citrus") g.put("tangerine", "type", "citrus") g.put("apple", "type", "pome") g.put_embedding("orange", [0.9, 0.8, 0.2, 0.1]) g.put_embedding("tangerine", [0.85, 0.75, 0.25, 0.15]) g.put_embedding("apple", [0.5, 0.5, 0.5, 0.5]) # Batch insert embeddings g.put_embeddings_batch([ ("banana", [0.2, 0.3, 0.8, 0.7]), ("mango", [0.3, 0.4, 0.7, 0.6]), ]) ``` -------------------------------- ### Sort Graph Vertices with order() Source: https://context7.com/arun1729/cog/llms.txt Sort vertices by their IDs using the `order()` method. Supports both ascending (default) and descending order. ```python from cog.torque import Graph from cog.torque import ASC, DESC g = Graph("data") g.put("charlie", "type", "user") g.put("alice", "type", "user") g.put("bob", "type", "user") # Ascending order (default) g.v().order().all() ``` ```python # Descending order g.v().order(DESC).all() ``` -------------------------------- ### Insert JSON data using putj Source: https://github.com/arun1729/cog/blob/master/README.md Insert data from JSON strings using 'putj'. This method is useful for bulk loading or when data is already in JSON format, allowing for nested relationships. ```python f = Graph("followers") f.putj('{"name" : "bob", "status" : "cool_person", "follows" : ["fred", "dani"]}') f.putj('{"_id": "1", "name" : "fred", "status" : "cool_person", "follows" : ["alice", "greg"]}') ``` -------------------------------- ### Insert JSON Documents with putj() Source: https://context7.com/arun1729/cog/llms.txt Use `putj()` to insert JSON objects, which are automatically decomposed into triples. A unique identifier is assigned to each object, or you can specify an `_id` for updates. ```python from cog.torque import Graph g = Graph("users") # Insert JSON document g.putj('{"name": "bob", "status": "active", "skills": ["python", "sql"]}') # Insert with explicit _id for updates g.putj('{"_id": "user1", "name": "alice", "department": "engineering"}') # Nested objects are automatically decomposed g.putj(''' { "name": "charlie", "location": { "city": "Toronto", "country": "Canada" }, "projects": ["api", "frontend"] } ''') # Query the inserted data result = g.v().has("name", "bob").out("skills").all() # {'result': [{'id': 'python'}, {'id': 'sql'}]} ``` -------------------------------- ### Tag Vertices for Reference Source: https://context7.com/arun1729/cog/llms.txt Use `tag()` to assign a name to the current set of vertices during traversal. This name can be used later with `back()` or in the results. ```python from cog.torque import Graph g = Graph("social") g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") # Tag vertices during traversal result = g.v("alice").tag("person").out("follows").tag("friend").out("follows").tag("fof").all() # {'result': [{'person': 'alice', 'friend': 'bob', 'id': 'charlie', 'fof': 'charlie'}]} ``` ```python # Multiple tags at different traversal points g.v("alice").tag("start").out("follows").out("follows").tag("end").all() ``` -------------------------------- ### HTTP API Endpoints Source: https://context7.com/arun1729/cog/llms.txt Available HTTP endpoints when a graph is served. ```APIDOC ## HTTP API Endpoints When a graph is served, these HTTP endpoints are available: ### Get server status page (HTML) ```bash curl http://localhost:8080/ ``` ### Get graph status page ```bash curl http://localhost:8080/social/ ``` ### Get graph statistics (JSON) ```bash curl http://localhost:8080/social/stats ``` ### Execute a Torque query ```bash curl -X POST http://localhost:8080/social/query \ -H "Content-Type: application/json" \ -d '{"q": "v(\"alice\").out(\"follows\").all()"}' ``` ### Write operations (requires writable=True) ```bash curl -X POST http://localhost:8080/social/mutate \ -H "Content-Type: application/json" \ -d '{"op": "put", "args": ["alice", "knows", "charlie"]}' ``` ### Batch insert ```bash curl -X POST http://localhost:8080/social/mutate \ -H "Content-Type: application/json" \ -d '{"op": "put_batch", "args": [["a","r","b"],["c","r","d"]]}' ``` ``` -------------------------------- ### Load Embeddings from Gensim Model Source: https://github.com/arun1729/cog/blob/master/README.md Load word embeddings from a Gensim Word2Vec model into CogDB. Ensure the Gensim model is already loaded. ```python from gensim.models import Word2Vec model = Word2Vec(sentences) count = g.load_gensim(model) ``` -------------------------------- ### Query Books by Average Rating Source: https://github.com/arun1729/cog/blob/master/README.md Retrieve titles of books with an average rating greater than 4.0 using a lambda function for filtering. ```python g.v().out("average_rating", func=lambda x: float(x) > 4.0).inc().out("title").all() ``` -------------------------------- ### Filter vertices by string prefix Source: https://github.com/arun1729/cog/blob/master/README.md Filter a set of vertices based on a condition applied to their IDs, using a lambda function with `filter()`. ```python g.v().filter(func=lambda x: x.startswith("d")).all() ``` -------------------------------- ### Include Edges in Results Source: https://github.com/arun1729/cog/blob/master/README.md Retrieve vertices that have a specific outgoing edge ('follows' to 'fred') and include the edge information in the results. The 'inc()' method modifies the output to contain edge details. ```python g.v().has("follows", "fred").inc().all('e') ``` -------------------------------- ### Stop CogDB Server Source: https://github.com/arun1729/cog/blob/master/README.md Use this command to gracefully stop the CogDB server process. ```python g.stop() ``` -------------------------------- ### Unique Vertex Traversal Source: https://context7.com/arun1729/cog/llms.txt Use `unique()` to ensure each vertex appears only once in the traversal results. This is useful for avoiding duplicate processing of nodes. ```gremlin g.v().out().all() ``` ```gremlin g.v().out().unique().all() ``` -------------------------------- ### Find k-Nearest Vertices by Embedding Similarity Source: https://context7.com/arun1729/cog/llms.txt Finds the k most similar vertices to a given vertex based on embedding similarity. Can be used on the entire graph or within traversal results. ```python from cog.torque import Graph g = Graph("semantic") # Setup with embeddings g.put_embedding("cat", [0.9, 0.1, 0.3]) g.put_embedding("dog", [0.85, 0.15, 0.35]) g.put_embedding("car", [0.1, 0.9, 0.2]) # Find similar items g.k_nearest("cat", k=2).all() # {'result': [{'id': 'cat'}, {'id': 'dog'}]} # Search within traversal results g.v().has("type", "animal").k_nearest("cat", k=3).all() ``` -------------------------------- ### Limit traversal results Source: https://github.com/arun1729/cog/blob/master/README.md Limit the number of vertices returned in a traversal to the first N results using the `limit()` method. ```python g.v().limit(3).all() ``` -------------------------------- ### Bidirectional traversal Source: https://github.com/arun1729/cog/blob/master/README.md Follow edges in both outgoing and incoming directions from a specified vertex using the `both()` method. ```python g.v("bob").both("follows").all() ``` -------------------------------- ### Insert a Single Triple with put() Source: https://context7.com/arun1729/cog/llms.txt Use the `put()` method to insert a single subject-predicate-object triple into the graph. This method supports method chaining for inserting multiple related triples efficiently. ```python from cog.torque import Graph g = Graph("people") # Insert relationships (subject, predicate, object) g.put("alice", "follows", "bob") g.put("bob", "follows", "charlie") g.put("charlie", "follows", "alice") # Insert properties g.put("alice", "status", "active") g.put("bob", "score", "85") g.put("alice", "department", "engineering") # Method chaining g.put("dani", "follows", "alice").put("dani", "status", "new") ``` -------------------------------- ### Custom Filtering with Lambda Source: https://context7.com/arun1729/cog/llms.txt Use `filter()` with a lambda function to apply custom logic for filtering vertices based on their IDs or other properties. ```python from cog.torque import Graph g = Graph("data") g.put("alice", "score", "95") g.put("bob", "score", "78") g.put("charlie", "score", "82") # Filter by ID pattern g.v().filter(func=lambda x: x.startswith("a")).all() # {'result': [{'id': 'alice'}]} ``` ```python # Filter numeric values g.v().out("score").filter(func=lambda x: int(x) > 80).inc().all() # {'result': [{'id': 'alice'}, {'id': 'charlie'}]} ``` ```python # Complex filtering g.v().filter(func=lambda x: len(x) <= 3).all() # {'result': [{'id': 'bob'}]} ``` -------------------------------- ### Query Vertices by Property Source: https://github.com/arun1729/cog/blob/master/README.md Find all vertices that have a specific property ('status') with a given value ('cool_person'). This is a common filtering operation in graph databases. ```python g.v().has("status", 'cool_person').all() ``` -------------------------------- ### Scan Vertices Source: https://github.com/arun1729/cog/blob/master/README.md Retrieve a limited number of vertices from the graph using the 'scan' method. The argument specifies the maximum number of vertices to return. ```python g.scan(3) ```