PYTHON HELP

Grakn Python (How It Works: A Guide for Developers)

Jordi Bardia
Jordi Bardia
February 26, 2025
Share:

Introduction

In today's coding world, databases are changing to keep up with what new apps need. We still use old-school relational databases, but now we also have cool stuff like Object-Relational Mapping (ORM). This lets coders work with databases using fancy programming tricks instead of boring old SQL. This new way makes it easier to handle data and keep the code in good shape. We've also got NoSQL databases now. These are great for dealing with messy data and work well for big data and quick number crunching.

Cloud-native databases are shaking things up too. They give us flexible, trustworthy, and managed services so we don't have to worry so much about taking care of the tech behind it all. NewSQL graph databases mix the good parts of SQL and NoSQL. They give us the reliability of relational databases and the flexibility of NoSQL, which works for lots of modern apps. By bringing all these database types together in new ways of coding, we can create solutions that work well, grow, and change with the times in our data-crazy world. Grakn may now be known as TypeDB, but it still serves its purpose: management and querying of knowledge graphs. In this article, we are going to learn more about Grakn(TypeDB) and how we can integrate it with IronPDF, an indispensable tool when generating and manipulating PDFs programmatically.

What is Grakn?

Grakn (now TypeDB), created by Grakn Labs, is the knowledge graph database for managing and analyzing complex networks of data. At the core lie the capabilities to model complicated relationships among existing data and provide advanced reasoning over persisted data. Grakn's intelligent language, Graql, will enable one to query and manipulate data with accuracy—supporting the development of intelligent systems that can derive great, valuable insights from complex datasets. By leveraging the Grakn core features, organizations can manage data structures understanding with a very powerful, intelligent knowledge representation.

Grakn Python (How It Works: A Guide for Developers): Figure 1 - TypeDB webpage

Its search language Graql, is made to work with the Grakn knowledge graph data model letting users change data in detailed and subtle ways. Because it can grow sideways and deal with big data sets, TypeDB fits well in areas like money, health care, drug discovery, and online safety where grasping and dealing with tricky graph data structure is key.

Installation and Configuring Grakn in Python

Installing Grakn

For Python developers looking to use Grakn (TypeDB), you need to install the typedb-driver library. This official client lets you interact with TypeDB. Here's the command that allows you to install this library with pip:

pip install typedb-driver
PYTHON

Set Up the TypeDB Server

Before you begin writing code, make sure your TypeDB server is up and running. You can obtain TypeDB by installing it from the TypeDB website and adhering to the setup guidelines for your operating system.

You can then use this command to start the TypeDB server:

typedb server
PYTHON

Using Grakn in Python

Python Code to Interact with TypeDB

Here's a simple illustration showing how to establish a connection with a TypeDB server, set up a schema, and carry out fundamental tasks like inserting information and retrieving it.

Creating a Database Schema

The following part of the program is dedicated to setting up a database structure. The code names the database as "example_db" and opens it in SCHEMA mode, which permits changes to the structure. In this mode, it starts a transaction of type WRITE to make these changes. A query is defined to outline the structure, creating a type called a person with two attributes: name and age. The name attribute is of type string, and the age attribute is of type long integer. Once the structure is defined, the transaction is saved to the database to make these modifications permanent.

from typedb.driver import TypeDB, SessionType, TransactionType, TypeDBOptions, TypeDBCredential
# Connect to TypeDB server
client = TypeDB.core_driver("localhost:1729")
# Create a database (if not already created)
database_name = "example_db"
client.databases().create(database_name)  # Ensure the database is created
with client.session(database_name, SessionType.SCHEMA) as session:
    with session.transaction(TransactionType.WRITE) as transaction:
        transaction.query.define("""
        define
        person sub entity, owns name, owns age;
        name sub attribute, value string;
        age sub attribute, value long;
        """)
        transaction.commit()
PYTHON

Inserting Data

After the schema is established, the script goes on to insert data into the database. To do this, a new session is opened in DATA mode, which is the most appropriate for data operations. The write transaction is first carried out in this session and an insert query is issued to include a new entity of type person with the name "Alice" and age 30. The data, when inserted, makes the transaction finalized and the database changes are updated.

from typedb.driver import TypeDB, SessionType, TransactionType, TypeDBOptions, TypeDBCredential
# Connect to TypeDB server
client = TypeDB.core_driver("localhost:1729")
# Insert data into the database
with client.session(database_name, SessionType.DATA) as session:
    with session.transaction(TransactionType.WRITE) as transaction:
        # Create a person entity using the logical inference of typeDB
        transaction.query.insert("""
        insert $p isa person, has name "Alice", has age 30;
        """)
        transaction.commit()
PYTHON

Querying Data

The last step that we will do is to get the needed information by asking a question to the database. The script opens a new session in DATA mode and starts a read transaction using TransactionType.READ. It then fetches the details of people who have the name "Alice". The match clause determines that the entities of type person have to have the name specified, and the fetch clause gets their name and age attributes. The results are then processed to extract the name and age values from each result. This information is displayed on the console.

from typedb.driver import TypeDB, SessionType, TransactionType, TypeDBOptions, TypeDBCredential
# Connect to TypeDB server
client = TypeDB.core_driver("localhost:1729")
# Query the data from the database
with client.session(database_name, SessionType.DATA) as session:
    with session.transaction(TransactionType.READ) as transaction:
        # Simple Query language for persons with name "Alice"
        results = list(transaction.query.fetch(f"""
        match 
        $p isa person, has name $fn;
        $fn = 'Alice';
        fetch 
        $p: name, age;
        """))
        for result in results:
            person_name = result.get('p')['name'][0]['value']
            person_age = result.get('p')['age'][0]['value']
            print(f"Person Name: {person_name}, Age: {person_age}")
PYTHON

Output

Grakn Python (How It Works: A Guide for Developers): Figure 2 - Console output from querying the database

Closing the Client Connection

When all data operations are performed, the script closes the client connection using client.close(). This step assures that resources are being released properly and no further interactions with the TypeDB server are attempted.
In general, this code presents a straightforward way of establishing a connection to a TypeDB server, defining a schema, inserting data, querying that data, and cleanly shutting down the connection.

from typedb.driver import TypeDB, SessionType, TransactionType, TypeDBOptions, TypeDBCredential
# Connect to TypeDB server
client = TypeDB.core_driver("localhost:1729")
# Close the client connection
client.close()
PYTHON

Introducing IronPDF

Grakn Python (How It Works: A Guide for Developers): Figure 3 - IronPDF for Python webpage

IronPDF for Python is a library that can help you programmatically create and handle PDF files. It includes a depth of functionality for creating PDFs from HTML, merging two or more PDF files, and using existing PDFs with text, images, and annotations. IronPDF, on the other hand, gives users a way to convert HTML pages or web content into high-quality PDFs, which can be used for creating reports, invoices, and other documents that have a fixed layout.

The library provides advanced features that include content extracting, document encryption, and page layout customization. Document generation workflows can be automated by infusing IronPDF with Python applications and thus developers can improve the overall functionality of their additions by making them robust in terms of PDF handling capabilities.

Installing the IronPDF Library

Use pip to install packages that allow Python to enable IronPDF capability.

pip install ironpdf
PYTHON

Integrating Grakn TypeDB with IronPDF

The use of TypeDB and IronPDF in the Python environment makes the generation, management, and other PDF-related documentation based on the data complexly structured in a Grakn (TypeDB) database more efficient. Here’s a step-by-step overview of how you might accomplish this integration:

from typedb.driver import TypeDB, SessionType, TransactionType, TypeDBOptions, TypeDBCredential
from ironpdf import *     import warnings
warnings.filterwarnings('ignore')
# Ensure that you have replaces the string with your own license key
License.LicenseKey = "YOUR LICENSE KEY GOES HERE";
data=[]
# Connect to TypeDB server
client = TypeDB.core_driver("localhost:1729")
# Create a database (if not already created)
database_name = "example_db"
# Query the data from the database
with client.session(database_name, SessionType.DATA) as session:
    with session.transaction(TransactionType.READ) as transaction:
        # Query for persons with name "Alice"
        results = list(transaction.query.fetch(f"""
        match 
        $fn == 'Alice';
        $p isa person, has name $fn;
       fetch
       $p: name, age;
        """)
        )
        for result in results:
            person_Name = result.get('p')['name'][0]['value']
            person_age = result.get('p')['age'][0]['value']
            data.append({"name": person_Name, "age": person_age})
# Close the client connection
client.close()
html_to_pdf = ChromePdfRenderer()
content = "<h1>Person Report</h1>"
for item in data:
    content += f"<p>Name: {item['name']}, Age: {item['age']}</p>"
pdf_document = html_to_pdf.RenderHtmlAsPdf(content)
pdf_document.SaveAs("output.pdf")
PYTHON

This code example shows how to use TypeDB and IronPDF in Python to get data from a TypeDB database and create a PDF report. First, it connects to a local TypeDB server and searches for entities named "Alice" to get back their names and ages. The results are printed to the console. After closing the TypeDB client connection, the code uses IronPDF's ChromePdfRenderer to convert HTML content into a PDF. The HTML content that includes a report of persons which consists of their names and ages has been retrieved and saved as "output.pdf" after it was converted to a PDF document. The snippets also contain warning suppression and an empty license key that is set for IronPDF which may be the case for the library to work without license warnings.

Output

Grakn Python (How It Works: A Guide for Developers): Figure 4 - Outputted PDF from the previous code

Licensing

A licensing key is needed to allow the code to work without a watermark. You can register for a free trial license at this link. Note that you are not required to present a credit card to get one. You only need to provide your email address to register for the free trial version.

Grakn Python (How It Works: A Guide for Developers): Figure 5 - IronPDF licensing plan

Conclusion

Grakn (now TypeDB) with IronPDFis a strong solution for managing and analyzing huge data volumes derived from PDF documents. This would be achieved by taking advantage of robust IronPDF capabilities in extracting and manipulating data in PDFs and using powerful Grakn graph database features in modeling intricate relationships and executing enhanced reasoning. In this respect, you now have the power to compose such a workflow that changes unstructured document data into structured and queryable data.

In the process, it simplifies extracting valuable insights from PDFs, enhancing their querying and analysis capability against the data with increased precision. Grakn's high-level data management, when combined with the IronPDF processing of PDFs, empowers better ways of handling information toward better decision-making and insight into complex datasets. IronSoftware also provides a variety of libraries that make it easier for you to create programs for a range of operating systems and platforms, including Windows, Android, MAC, Linux, etc.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he says it’s one of his favorite aspects of working with Iron Software. Jordi grew up in Miami, Florida and studied Computer Science and Statistics at University of Florida.
< PREVIOUS
HTTPX Python (How It Works: A Guide for Developers)
NEXT >
scikit-image Python (How It Works: A Guide for Developers)

Ready to get started? Version: 2025.3 just released

View Licenses >