Quickstart: Create an Azure Cosmos DB graph database with PHP and the Azure portal
APPLIES TO:
Gremlin
In this quickstart, you create and use an Azure Cosmos DB Gremlin (Graph) API database by using PHP and the Azure portal.
Azure Cosmos DB is Microsoft's multi-model database service that lets you quickly create and query document, table, key-value, and graph databases, with global distribution and horizontal scale capabilities. Azure Cosmos DB provides five APIs: Core (SQL), MongoDB, Gremlin, Azure Table, and Cassandra.
You must create a separate account to use each API. In this article, you create an account for the Gremlin (Graph) API.
This quickstart walks you through the following steps:
- Use the Azure portal to create an Azure Cosmos DB for Gremlin (Graph) API account and database.
- Clone a sample Gremlin API PHP console app from GitHub, and run it to populate your database.
- Use Data Explorer in the Azure portal to query, add, and connect data in your database.
Prerequisites
- An Azure subscription. If you don't have an Azure subscription, create an Azure free account before you begin. Alternatively, you can try Azure Cosmos DB for free without an Azure subscription.
- PHP 5.6 or newer installed.
- Composer open-source dependency management tool for PHP installed.
Create a Gremlin (Graph) database account
First, create a Gremlin (Graph) database account for Azure Cosmos DB.
In the Azure portal, select Create a resource from the left menu.
On the New page, select Databases > Azure Cosmos DB.
On the Select API Option page, under Gremlin (Graph), select Create.
On the Create Azure Cosmos DB Account - Gremlin (Graph) page, enter the following required settings for the new account:
- Subscription: Select the Azure subscription that you want to use for this account.
- Resource Group: Select Create new, then enter a unique name for the new resource group.
- Account Name: Enter a unique name between 3-44 characters, using only lowercase letters, numbers, and hyphens. Your account URI is gremlin.azure.com appended to your unique account name.
- Location: Select the Azure region to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.
For this quickstart, you can leave the other fields and tabs at their default values. Optionally, you can configure more details for the account. See Optional account settings.
Select Review + create, and then select Create. Deployment takes a few minutes.
When the Your deployment is complete message appears, select Go to resource.
You go to the Overview page for the new Azure Cosmos DB account.
Optional account settings
Optionally, you can also configure the following settings on the Create Azure Cosmos DB Account - Gremlin (Graph) page.
On the Basics tab:
Setting Value Description Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode. Apply Azure Cosmos DB free tier discount Apply or Do not apply With Azure Cosmos DB free tier, you get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier. Note
You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you don't see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.
On the Global Distribution tab:
Setting Value Description Geo-redundancy Enable or Disable Enable or disable global distribution on your account by pairing your region with a pair region. You can add more regions to your account later. Multi-region Writes Enable or Disable Multi-region writes capability allows you to take advantage of the provisioned throughput for your databases and containers across the globe. Note
The following options aren't available if you select Serverless as the Capacity mode:
- Apply Free Tier Discount
- Geo-redundancy
- Multi-region Writes
Other tabs:
- Networking: Configure access from a virtual network.
- Backup Policy: Configure either periodic or continuous backup policy.
- Encryption: Use either a service-managed key or a customer-managed key.
- Tags: Tags are name/value pairs that enable you to categorize resources and view consolidated billing by applying the same tag to multiple resources and resource groups.
Add a graph
On the Azure Cosmos DB account Overview page, select Add Graph.
Fill out the New Graph form. For this quickstart, use the following values:
- Database id: Enter sample-database. Database names must be between 1 and 255 characters, and can't contain
/ \ # ?
or a trailing space. - Database Throughput: Select Manual, so you can set the throughput to a low value.
- Database Max RU/s: Change the throughput to 400 request units per second (RU/s). If you want to reduce latency, you can scale up throughput later.
- Graph id: Enter sample-graph. Graph names have the same character requirements as database IDs.
- Partition key: Enter /pk. All Cosmos DB accounts need a partition key to horizontally scale. To learn how to select an appropriate partition key, see Use a partitioned graph in Azure Cosmos DB.
- Database id: Enter sample-database. Database names must be between 1 and 255 characters, and can't contain
Select OK. The new graph database is created.
Get the connection keys
Get the Azure Cosmos DB account connection keys to use later in this quickstart.
On the Azure Cosmos DB account page, select Keys under Settings in the left navigation.
Copy and save the following values to use later in the quickstart:
- The first part (Azure Cosmos DB account name) of the .NET SDK URI.
- The PRIMARY KEY value.
Clone the sample application
Now, switch to working with code. Clone a Gremlin API app from GitHub, set the connection string, and run the app to see how easy it is to work with data programmatically.
In git terminal window, such as git bash, create a new folder named git-samples.
mkdir "C:\git-samples"
Switch to the new folder.
cd "C:\git-samples"
Run the following command to clone the sample repository and create a copy of the sample app on your computer.
git clone https://github.com/Azure-Samples/azure-cosmos-db-graph-php-getting-started.git
Optionally, you can now review the PHP code you cloned. Otherwise, go to Update your connection information.
Review the code
This step is optional. If you're interested in learning how the database resources are created in the code, you can review the following snippets. The snippets are all taken from the connect.php file in the C:\git-samples\azure-cosmos-db-graph-php-getting-started folder.
The Gremlin
connection
is initialized in the beginning of theconnect.php
file, using the$db
object.$db = new Connection([ 'host' => '<your_server_address>.graphs.azure.com', 'username' => '/dbs/<db>/colls/<coll>', 'password' => 'your_primary_key' ,'port' => '443' // Required parameter ,'ssl' => TRUE ]);
A series of Gremlin steps execute, using the
$db->send($query);
method.$query = "g.V().drop()"; ... $result = $db->send($query); $errors = array_filter($result); }
Update your connection information
Open the connect.php file in the C:\git-samples\azure-cosmos-db-graph-php-getting-started folder.
In the
host
parameter, replace<your_server_address>
with the Azure Cosmos DB account name value you saved from the Azure portal.In the
username
parameter, replace<db>
and<coll>
with your database and graph name. If you used the recommended values ofsample-database
andsample-graph
, it should look like the following code:'username' => '/dbs/sample-database/colls/sample-graph'
In the
password
parameter, replaceyour_primary_key
with the PRIMARY KEY value you saved from the Azure portal.The
Connection
object initialization should now look like the following code:$db = new Connection([ 'host' => 'testgraphacct.graphs.azure.com', 'username' => '/dbs/sample-database/colls/sample-graph', 'password' => '2Ggkr662ifxz2Mg==', 'port' => '443' // Required parameter ,'ssl' => TRUE ]);
Save the connect.php file.
Run the console app
In the git terminal window,
cd
to the azure-cosmos-db-graph-php-getting-started folder.cd "C:\git-samples\azure-cosmos-db-graph-php-getting-started"
Use the following command to install the required PHP dependencies.
composer install
Use the following command to start the PHP application.
php connect.php
The terminal window displays the vertices being added to the graph.
If you experience timeout errors, check that you updated the connection information correctly in Update your connection information, and also try running the last command again.
Once the program stops, press Enter.
Review and add sample data
You can now go back to Data Explorer in the Azure portal, see the vertices added to the graph, and add more data points.
In your Azure Cosmos DB account in the Azure portal, select Data Explorer, expand sample-database and sample-graph, select Graph, and then select Execute Gremlin Query.
In the Results list, notice the new users added to the graph. Select ben, and notice that they're connected to robin. You can move the vertices around by dragging and dropping, zoom in and out by scrolling the wheel of your mouse, and expand the size of the graph with the double-arrow.
Add a new user. Select the New Vertex button to add data to your graph.
Enter a label of person.
Select Add property to add each of the following properties. You can create unique properties for each person in your graph. Only the id key is required.
Key Value Notes id ashley The unique identifier for the vertex. If you don't specify an id, one is generated for you. gender female tech java Note
In this quickstart you create a non-partitioned collection. However, if you create a partitioned collection by specifying a partition key during the collection creation, then you need to include the partition key as a key in each new vertex.
Select OK.
Select New Vertex again and add another new user.
Enter a label of person.
Select Add property to add each of the following properties:
Key Value Notes id rakesh The unique identifier for the vertex. If you don't specify an id, one is generated for you. gender male school MIT Select OK.
Select Execute Gremlin Query with the default
g.V()
filter to display all the values in the graph. All the users now show in the Results list.As you add more data, you can use filters to limit your results. By default, Data Explorer uses
g.V()
to retrieve all vertices in a graph. You can change to a different graph query, such asg.V().count()
, to return a count of all the vertices in the graph in JSON format. If you changed the filter, change the filter back tog.V()
and select Execute Gremlin Query to display all the results again.Now you can connect rakesh and ashley. Ensure ashley is selected in the Results list, then select the edit icon next to Targets at lower right.
In the Target box, type rakesh, and in the Edge label box type knows, and then select the check mark.
Now select rakesh from the results list, and see that ashley and rakesh are connected.
You've completed the resource creation part of this quickstart. You can continue to add vertexes to your graph, modify the existing vertexes, or change the queries.
You can review the metrics that Azure Cosmos DB provides, and then clean up the resources you created.
Review SLAs in the Azure portal
The Azure portal monitors your Azure Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.
To review metrics and SLAs:
Select Metrics in your Azure Cosmos DB account's navigation menu.
Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.
Review the metrics on the other tabs.
Clean up resources
When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:
In the Azure portal Search bar, search for and select Resource groups.
From the list, select the resource group you created for this quickstart.
On the resource group Overview page, select Delete resource group.
In the next window, enter the name of the resource group to delete, and then select Delete.
This action deletes the resource group and all resources within it, including the Azure Cosmos DB for Gremlin (Graph) account and database.
Next steps
In this quickstart, you learned how to create an Azure Cosmos DB for Gremlin (Graph) account and database, clone and run a PHP app, and work with your database using the Data Explorer. You can now build more complex queries and implement powerful graph traversal logic using Gremlin.
Feedback
Submit and view feedback for