×
Community Blog Learning How to Use OrientDB's Intuitive Module OrientJS

Learning How to Use OrientDB's Intuitive Module OrientJS

In this tutorial, you will setup OrientDB on Alibaba Cloud and explore how you can use OrientJS together with OrientDB.

By Dassi Orleando, Alibaba Cloud Community Blog author.

OrientDB is an open-source multi-model non-relational database that can be used together with several different types of models, including Graph, Document, Key-Value, GeoSpatial and Reactive. In addition, thanks to its module OrientJS, OrientDB can also be used to manage queries in a way very similar to how relational databases with SQL syntax do so.

In this article, you will be learning how you can use the official OrientDB NodeJS module called OrientJS, which can help you be able to manage queries like how you would with a relational database with typical SQL syntax.

Prerequisites

This tutorial can be said to be of medium difficulty. As such, for this tutorial, you'll need to have some relevant background knowledge. Also, it is also a prerequisite that you have some things set up before you continue on with this tutorial. Specifically, you'll need the following:

  1. A general understanding of how the Linux command line interface functions.
  2. A general understanding of the Alibaba Cloud's ECS security groups.
  3. Java (specifically, 1.7 or later) is installed, and the relevant environment variables are also set up.
  4. A general understanding of JavaScript.

Installing OrientDB on Alibaba Cloud ECS

As the first leg of this tutorial, we'll need to create an Alibaba Cloud Elastic Compute Service (ECS) instance. For this tutorial, we will be creating an ECS instance that has Ubuntu installed, has a one-core processor and 512 MB memory. Then, you'll want to log on to your instance either by using SSH or through the Alibaba Cloud console. To learn how to do that, if you don't already know, check out this guide.

Next, we'll need to install the appropriate binary package. We can first download the latest stable release of OrientDB, which so happens to be 3.0.21 at the time of writing this article, corresponding to our operating system. Alternatively, rather than downloading from the website manually, you can try using the following command below to download OrientDB 3.0.21:

curl  https://s3.us-east-2.amazonaws.com/orientdb3/releases/3.0.21/orientdb-3.0.21.tar.gz

After it is downloaded, the zipped file named orientdb-3.0.21.tar.gz will be in the directory where you originally entered the curl command. Now, after that, you'll want to extract the content of the zipped file and move it to an appropriate directory under the environment variable ORIENTDB_HOME. Here are the corresponding commands according to the current version:

  • tar -xvzf orientdb-3.0.21.tar.gz: used to unzip the folder
  • cp -r orientdb-3.0.21 /opt: used to copy the entire folder to the /opt directory

The content of /etc/environment should be as follows:

JAVA_HOME=/usr/lib/jvm/java-8-oracle
ORIENTDB_HOME=/opt/orientdb-3.0.21
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games :$ORIENTDB_HOME/bin" 

Knowing that you have Java 1.7 or later installed-which was a prerequisite of this tutorial-and that you have added a swap space to your instance installed with Ubuntu-that is, in the case that it's a fresh instance server and you haven't done it yet.

Note: After you have updated OrientDB-if you need to-you should source this file so that the new OrientDB executables get available in the terminal. The command to use for this is: source /etc/environment.

Now, you'll need to edit the orientdb.sh file located in ORIENTDB_HOME/bin by entering the location-which is, of course, ORIENTDB_HOME-of OrientDB directory in lieu of the ORIENTDB_DIR and also the system user we'd like to use instead of USER_YOU_WANT_ORIENTDB_RUN_WITH.

With your OrientDB installation being fully function, you can use the following commands to control your OirentDB server:

  • orientdb.sh status: used to check whether the server is running or not
  • orientdb.sh start: used to start OrientDB server
  • orientdb.sh stop: used to shut down OrientDB

Most of the time, you'll need to have a very secure installation for the production environment. That is, you'll need a secure installation of OrientDB in which not just any user would have permission to start or stop the database at their own will. With that said, in the OrientDB bin/orientdb.sh file, there is the possibility to enter the administration user in place of USER_YOU_WANT_ORIENTDB_RUN_WITH. Doing so means that the user will be the only one to have full right on OriendDB most sensible commands-as an administrator.

If you'd like to learn more of this kind of stuff, check out OrientDB's documentation.

Now that now of those things are complerte, let's continue to press on. You can test your installation by running with the orientdb.sh start command, and you can access the portal, specifically the OrientDB Studio, at either one fo these addresses, http://our_ecs_ip:2480 or http://localhost:2480, as shown in the following screenshot:

1

To connect yourself to OrientDB and access the dashboard, you'll need to define your users at the very end of the file $ORIENTDB_HOME/config/orientdb-server-config.xml as described here.

Next, don't forget to configure your instance security group for your port 2480, which it's the port for the OrientDB Studio port.

Note: You'll want to configure it to be accessible from outside. You'll want to add more security measures on top of this, of course.

Below is the output of the configuration for our testing instance:

2

Setting up OrientJs

The OrientJS module of OrientDB can be described as the official OrientDB driver for JavaScript projects. It happens to be widely used among NodeJS developers-and rightfully so. As any other package, of course, just a single command is needed to install it through using the node package manager. More specifically, to install it locally, you run the npm install orientjs command.

Then, after OrientJS is installed and initialized, you'll be able to do a lot of things, including the following:

Initializing the OrientJS

The first step that we need to do to get OrientJS and OrientDB to work well with each other is to initialize the server API. Doing so is important because it allows OreintJS to interact with the OrientDB server API. This is because it needs the database user to be connected with the host of OrientDB server and its port.

// Initializing the Server API
var server = OrientDB({
  host:       'localhost',
  port:       2424,
  username:   'admin',
  password:   'admin'
});

Note: In this case, we're using admin:admin for the user credentials. But this should be changed to whatever corresponding credentials you have set for your OrientDB configuration file.

Listing the Databases

The next leg of this tutorial is to perform a single query using OrientJS to list all the databases that you've created so far to this point. Following this, we're displaying each database name and type as it's normally returning a DB object.

// Databases listing
server.list()
  .then(list => {
    console.log(list.length + ' databases created so far');

    list.forEach(db => {
      console.log(db.name + ' - ' + db.type);
    });
  });

Creating a Database

Now, let's move on to creating a database from the server API. This is relatively simple. This operation can also be done throught a single command that returns a promise with the database object we just created.

Here's the content of the OrientJs typescript types relative to the create function:

/**
 * Create a database with the given name / config.
 *
 * @param  config The database name or configuration object.
 * @promise {Db}                  The database instance
 */
create(name: string | DbConfig): Promise<Db>;

It's clearly stated that the create operation can be completed by providing to this function either the configuration object or simply the database name. However, in the second case, shown below, the default values are going to be selected for missing fields. Here's how to create a database with a configuration object:

// Creating a database
server.create({
    name:     'NewDatabase',
    type:     'graph',
    storage:  'plocal',
  }).then(dbCreated => {
    console.log('Database ' + dbCreated.name + ' created successfully');
  });

Using an existing Database

After the database is created-alternaitvely, of course, this can be for an existing database, which we didn't just create-you can get the instance to do more operations later on. You can use the following method to initialize a database instance:

var db = server.use('NewDatabase');

Starting from the version 2.1.11, it is also possible to use the ODatabase class to initialize the Server API and immediately get connected to a database. Here's the syntax to do all of that:

var ODatabase = require('orientjs').ODatabase;
var db = new ODatabase({
  host:     'localhost',
  port:     2424,
  username: 'admin',
  password: 'admin',
  name:     'NewDatabase'
});

console.log('Connected to: ' + db.name);

Record API

After the database instance is initialized, you can fetch and manipulate saved records-that is, information saved in our database-through using the Record ID (RID) of the database.

Note: The record ID is a unique value, and therefore there is no need to create one more field referencing the primary key as we would have to do for any typical SQL-based relational database.

The syntax of the record ID is as follows: #<cluster>:<position>. For this code,

  • cluster: Serves as the cluster identifier. It directly refers to the cluster record to which the cluster belongs. When it comes to the values that this parameter may be, a positive number indicates a persistent record, whereas a negative number indicates a temporary record.
  • position: Specifies the absolute record position into the cluster.

Now, let's fetch a single record by its RID:

db.record.get('#1:1')
  .then(
    function(article) {
        console.log('Loaded article:', article);
      }
  );

Now that we've fetched a record, let's go over some operations you can do. First there's the delete operation. Generally speaking, deleting a record is relatively straightforward and can be done with the following code:

db.record.delete('#1:1');

Next, there's the update operation. Updating a record is a bit more complex, but still all right in my mind. It can be done after the corresponding data that you want to update has been loaded. Below shows how you can implement the update function:

db.record.get('#1:1')
  .then(function(article) {
    article.title = 'New Title';
    db.record.update(article)
      .then(function() {
        console.log("Article updated successfully");
      });
  });

Note: You'll want to consider the following this when you use this code.

- The an asterisk (#) prefix is required to recognize a Record ID.
- When creating a new record, OrientDB selects the cluster to store it using a configurable strategy, which can be the default strategy, the round-robin one, or a balanced or local strategy.
- Also, note that, in our example, #1:1 represents the RID. 

The Class API

A database derivative object is specially used to access, create, or manipulate classes. To be, more specific, when we say "class" what we mean is db.class. For example, here's the method that we can use to create a class:

// Creating a new class(Article) using the Class API
var Article = db.class.create('Article');

Retrieving an existing class can be done like following:

var Article = db.class.get('Article');

Let's note that they are all returning promises, an aware style would be to perform further actions once the promises resolved. To return the list of all saved classes into the current database we're connected to, we simply apply this following code:

// List all the database classes
db.class.list()
  .then(
    function(classes){
      console.log(classes.length + ' existing classes into ' + db.name);

      classes.forEach(cl => {
        console.log(cl.name);
      });
    }
  );

Next, there's the creation operation. Creating a class is a good thing to know before fully designing your database structure, once done we need to perform some operations over the properties as listing them, creating more, updating or dropping some. We should correctly load the class to work on before manipulating its properties.

Listing the Article's class properties will look like this:

db.class.get('Article').then(function(Article) {
  Article.property.list()
  .then(
    function(properties) {
       console.log(Article.name + ' has the properties: ', properties);
    }
 );
});

Creating properties is done almost with the same syntax:

db.class.get('Article').then(function(Article) {
  Article.property.create([{
    name: 'title',
    type: 'String'
  },{
    name: 'content',
    type: 'String'
  }]).then(
    function(properties) {
      console.log("Successfully created properties");
    }
  );
});

You only need to configure one property for the class. You won't need to set many property configurations. Now let's perform some actions:

First, let's delete a property by its name:

db.class.get('Article').then(function(Article) {
  Article.property.drop('peroperty_to_drop').then(function(){
    console.log('Property deleted successfully.');
 });
});

Then, let's rename a property:

db.class.get('Article').then(function(Article) {
  Article.property.rename('old_name', 'new_name').then(function(p) {
    console.log('Property renamed successfully');
 });
});

For more information about the Class API, here's the full documentation to read.

Querying with OrientDB

Querying is one of the most important operations provided by any database engine in order to better manage our data, OrientDB allows us to perform queries in either one of two ways. You can either issue direct SQL requests or using Query Builder to implicitly build queries in NodeJs.

// Find articles viewed 200 times
var numberViews = 200;
db.query(
   'SELECT title, content FROM Article '
   + 'WHERE number_views = :numberViews,
   { params: { numberViews: numberViews, } }
).then(function(articles) {
   console.log(articles);
});

In the query above, we're looking for articles that have been viewed two hundred times. This query is relatively easy to perform. The way we order the engine with this possibility to use more interesting SQL syntax with operators like AND, OR, LIKE, so forth. This possibility to use parametrized requests (easier) instead of fully building an SQL string by concatenating the request sub-strings and parameters (fastidious). More details about OrientDB SQL syntax can be found here.

Instead of fully writing your SQL query, you can alternatively use Query Builder instead. Query Builder functions by allowing you to call some specific methods that are performing query internally through the Database API actions. Here's the same query we did with SQL but now with Query Builder:

var numberViews = 200;
var query = db.select('title, content').from('Article')
  .where({ "number_views": numberViews })
  .all();

Events

In OrientDB, events serve as callbacks methods you can run whenever your queries end or start. They are useful for debugging queries, as well as logging, profiling or performing some special tasks to regulate your data. Events are database dependent, meaning that each event is attached to a single database and requires the use of the Database API for its creation. When it comes to using this API, you can use the db.on() function. The example below will be logging every single query sent to OrientDB server using beginQuery event: (Alternatively, for ending a query, you can use endQuery.)

db.on("beginQuery", function(queryObj) {
  console.log('DEBUG: ', queryObj);
});

Conclusion

In this tutorial, we've seen how to setup OrientDB on an Alibaba Cloud ECS instance and have also explored how to use OrientJS together with OrientDB.

0 0 0
Share on

Alibaba Clouder

1,510 posts | 243 followers

You may also like

Comments