Prism Examples

These examples use the Python Protobuf bindings and a Polypheny-DB instance with Prism 2.3. Save the developer guide’s client as prism_client.py. Put each example in the same directory and run it in the same virtual environment with the same connection settings.

Use a development instance and an account that can create and drop namespaces. Each example creates its own namespace and attempts to drop it on exit. If the default name is already in use, set namespace to an unused lowercase SQL identifier such as prism_demo_2.

Inspect document collection metadata

Use NamespacesRequest to discover document namespaces, then send EntitiesRequest for the selected namespace. The pattern symptoms% selects collection names starting with symptoms. Inspect the Entity oneof before reading a collection, and check Protobuf field presence before parsing the sample JSON.

The example uses mongo as the language name for MongoQL. Run db.createCollection(...) before the first insert. An insert that triggers automatic collection creation can fail and leave an empty collection behind. The query returns documents in a DocumentFrame.

Save and run this example as document_metadata.py.

import json

from org.polypheny.prism import namespace_meta_requests_pb2 as catalog

from prism_client import open_session


namespace = "prism_collection_demo"
with open_session() as client:
    with client.execute(f"CREATE DOCUMENT NAMESPACE {namespace}"):
        pass
    try:
        for statement in (
            'db.createCollection("symptoms")',
            'db.symptoms.insertOne({"patient_id": 7, "address": {"city": "Basel"}})',
            'db.symptoms.insertOne({"patient_id": 8})',
            'db.symptoms.insertOne({"patient_id": 9, "address": null})',
        ):
            with client.execute(statement, language="mongo", namespace=namespace):
                pass

        namespaces = client.call(
            "namespaces_request",
            catalog.NamespacesRequest(namespace_type="DOCUMENT"),
            "namespaces_response",
        )
        document_names = {item.namespace_name for item in namespaces.namespaces}
        if namespace not in document_names:
            raise RuntimeError(f"Document namespace {namespace} was not listed")

        result = client.call(
            "entities_request",
            catalog.EntitiesRequest(namespace_name=namespace, entity_pattern="symptoms%"),
            "entities_response",
        )
        for entity in result.entities:
            if entity.WhichOneof("Entity") != "document":
                continue
            collection = entity.document
            print(f"{collection.namespace_name}.{collection.collection_name}")
            for field in collection.fields:
                print(f"{field.field_path}: {field.type_name}, optional={field.is_optional}")
            if collection.HasField("sample_document_json"):
                sample = json.loads(collection.sample_document_json)
                print("Sample patient_id:", sample["patient_id"])
            for index in collection.document_indexes:
                print(f"Index: {index.field_path}, {index.index_type}, unique={index.unique}")

        with client.execute(
            "db.symptoms.find({})",
            language="mongo",
            namespace=namespace,
            fetch_size=1,
        ) as statement:
            for frame in client.frames(statement, fetch_size=1):
                if frame.WhichOneof("result") != "document_frame":
                    raise RuntimeError("Expected a document frame")
                for document in frame.document_frame.documents:
                    entries = document.entries
                    patient_id = entries["patient_id"].integer.integer
                    address = entries.get("address")
                    if address is None:
                        print(f"Patient {patient_id} has no address field")
                    elif address.WhichOneof("value") == "null":
                        print(f"Patient {patient_id} has a null address")
                    else:
                        city = address.document.entries["city"].string.string
                        print(f"Patient {patient_id} lives in {city}")
    finally:
        with client.execute(f"DROP NAMESPACE {namespace}"):
            pass

The metadata reports patient_id with type int and optional=False, and address.city with type string and optional=True. Any of the inserted documents can appear as the sample. Index entries depend on what the storage adapter reports.

The query returns all three documents. In Python, use entries.get("address") to check whether the key exists. For a present key, inspect ProtoValue.value to distinguish an explicit null from a nested document.

The collection metadata reference explains sampling, nested path escaping, and how to interpret compound indexes. You can make the same request through the Python connector or the JDBC driver.

Decode graph results

In Prism 2.3, a Cypher projection mixing graph and scalar columns returns tabular frames. A projection consisting entirely of graph-typed columns returns flat graph frames. To distinguish the graph result formats and value types, inspect Frame.result for each page and ProtoValue.value for each tabular cell. The example requests one source row per page and shows node and edge values, an ordered path, and flat graph elements.

Save and run this example as graph_results.py.

from org.polypheny.prism.value_pb2 import ProtoEdge

from prism_client import open_session


def show_projection(client, namespace, query):
    with client.execute(query, language="cypher", namespace=namespace, fetch_size=1) as statement:
        for frame in client.frames(statement, fetch_size=1):
            result_kind = frame.WhichOneof("result")
            if result_kind == "graph_frame":
                for element in frame.graph_frame.element:
                    print("Graph element:", element.WhichOneof("element"))
            elif result_kind == "relational_frame":
                for row in frame.relational_frame.rows:
                    graph_value, label = row.values
                    value_kind = graph_value.WhichOneof("value")
                    if value_kind == "node":
                        name = graph_value.node.properties["name"].string.string
                        print(f"Node: {name}, scalar: {label.string.string}")
                    elif value_kind == "edge":
                        edge = graph_value.edge
                        direction = ProtoEdge.Direction.Name(edge.direction)
                        print(f"{label.string.string}: {', '.join(edge.labels)} ({direction})")
                    elif value_kind == "path":
                        names = [
                            node.properties["name"].string.string
                            for node in graph_value.path.nodes
                        ]
                        print(f"{label.string.string}: {' → '.join(names)}")
                    else:
                        raise RuntimeError(f"Unexpected graph value {value_kind}")
            else:
                raise RuntimeError(f"Unexpected result frame {result_kind}")


namespace = "prism_graph_demo"
with open_session() as client:
    if client.server_api_version < (2, 3):
        raise RuntimeError("Mixed graph projections require Prism 2.3 or later")
    with client.execute(f"CREATE GRAPH NAMESPACE {namespace}"):
        pass
    try:
        with client.execute(
            "CREATE (:Person {name: 'Ada'})-[:KNOWS]->"
            "(:Person {name: 'Lin'})-[:KNOWS]->(:Person {name: 'Sam'})",
            language="cypher",
            namespace=namespace,
        ):
            pass
        show_projection(client, namespace, "MATCH (n:Person) RETURN n, n.name ORDER BY n.name")
        show_projection(
            client,
            namespace,
            "MATCH (:Person)-[r:KNOWS]->(:Person) RETURN r, 'Edge' AS label",
        )
        show_projection(
            client,
            namespace,
            "MATCH p=(:Person {name: 'Ada'})-[:KNOWS*1..3]->(:Person {name: 'Sam'}) "
            "RETURN p, 'Path' AS label",
        )
        show_projection(client, namespace, "MATCH (n:Person) RETURN n")
    finally:
        with client.execute(f"DROP NAMESPACE {namespace}"):
            pass

The first projection prints Ada, Lin, and Sam in separate rows. The second reports the two KNOWS edges and their stored direction. The third prints Path: Ada → Lin → Sam in traversal order. The final projection emits three node entries in a flat graph result.

© Polypheny GmbH. All Rights Reserved.