[JAVA] How to use OrientJS and OrientDB together

In this tutorial, we will set up ** OrientDB ** on ** Alibaba Cloud ** and explore how to use OrientJS with ** OrientDB **.


This tutorial is of medium difficulty. Therefore, this tutorial requires some relevant background knowledge. It is also a major premise to make some settings before proceeding with this tutorial. Specifically, you need the following:

  1. Functions of Linux command line interface General understanding of.
  2. General understanding of Alibaba Cloud's ECS Security Group. 3, Java (specifically 1.7 or later) is installed, and related environment variables are also set. Being. 4, General understanding of JavaScript.

Installing OrientDB on Alibaba Cloud ECS

As a first step in this tutorial, [Create] an Alibaba Cloud Elastic Compute Service (ECS) instance (https://www.alibabacloud. com / help / ja / doc-detail / 25424.htm # task_zjx_p1f_5db) You need to. In this tutorial, you will install Ubuntu and create an ECS instance with a one-core processor and 512MB of memory. Then use SSH or log on to your instance through the Alibaba Cloud console. If you don't know how to do this yet, check out this Guide (https://www.alibabacloud.com/help/ja/doc-detail/25425.htm).

Next, you need to install the appropriate binary package. First, download the latest stable release of OrientDB. Alternatively, instead of manually downloading from the website, use the following command to download OrientDB 3.0.21 You can also try it.

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

When the download is complete, you will find a zip file named ʻorientdb-3.0.21.tar.gz in the directory where you first entered the curl command. Then unzip the contents of the zip file and change to the appropriate directory under the environment variable ʻORIENTDB_HOME. The corresponding commands according to the current version are as follows.

-- tar -xvzf orientdb-3.0.21.tar.gz: Unzip the folder. --cp -r orientdb-3.0.21 / opt: Used to copy the entire folder to the / opt directory. The contents of / etc / environment are as follows.

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games :$ORIENTDB_HOME/bin" 

If you have Java 1.7 or later installed, which is a prerequisite for this tutorial, and you have added swap space to your Ubuntu-installed instance, that is, your new instance server and not yet installed.

Note: After updating OrientDB, you need to source this file if necessary to make the new OrientDB executable available in your terminal. The command used for this is: source / etc / environment.

Now enter the location of the OrientDB directory of ʻORIENTDB_HOME instead of ʻORIENTDB_DIR (of course ʻORIENTDB_HOME) and the system user you want to use instead of ʻUSER_YOU_WANT_ORIENTDB_RUN_WITH, and find ʻORIENTDB_HOME / bin. You need to edit the sh file.

With the OrientDB installation fully functional, you can control the OirentDB server with the following command:

--ʻOrientdb.sh status: Used to check if the server is running. --ʻOrientdb.sh start: Used to start the OrientDB server. --ʻOrientdb.sh stop`: Used to shut down OrientDB.

In most cases, a very secure installation is required in a production environment. This means that you need a secure OrientDB installation where no user has the authority to start or stop the database on their own initiative. Therefore, in the ʻOrientDB bin / orientdb.sh file, you can enter the admin user instead of ʻUSER_YOU_WANT_ORIENTDB_RUN_WITH. Doing so means that as an administrator you will be the only user with full rights to OriendDB's most sensible commands.

If you want to know more about this kind, see the OrientDB documentation (http://orientdb.com/docs/3.0.x/?spm=a2c65.11461447.0.0.4e462b3eZyH0hD).

Now that we've done all this, let's move on. You can test the installation by running the ʻorientdb.sh startcommand. You can access the portal, especially OrientDB Studio, from either thehttp: // our_ecs_ip: 2480 or http: // localhost: 2480` address, as shown in the screenshot below.


To connect to OrientDB and access the dashboard, click here (https://orientdb.com/docs/2.0/orientdb.wiki/Security.html?spm=a2c65.11461447.0.0.4e462b3eZyH0hD#orientdb-server You must define the user at the end of the $ ORIENTDB_HOME / config / oritdenb-server-config.xml file as described in -security).

Next, don't forget to set the instance security group on port 2480 (OrientDB Studio port).

Note: Must be configured for external access.

Below is the output of the test instance settings.


OrientJs settings

The OrientJS module of OrientDB can be written as the official OrientDB driver for JavaScript projects. It's widely used by NodeJS developers. Of course, like any other package, you only need one command to install using node package manager .. Specifically, to install locally, run the npm install orientjs command.

And once OrientJS is installed and initialized, you will be able to:

Initialization of OrientJS

The first step in getting OrientJS and OrientDB to work together is to initialize the server API. Doing this is important to allow OreintJS to interact with OrientDB's server API. This is because the database user must be connected to the OrientDB server host and its port.

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

Note: In this case, we are using ʻadmin: admin` for user credentials. However, this needs to be changed to the corresponding credentials set in the OrientDB configuration file.

List of databases

The next step in this tutorial is to run a single query using OrientJS to list all the databases you have created so far. This is followed by displaying the name and type of each database, which would normally return a DB object.

// Databases listing
  .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 the database from the server API. This is relatively easy. You can also do this with a single command that returns an appointment with the database object you just created.

Below is the content of the OrientJs types associated with 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 is specified that the create operation is completed by providing this function with a configuration object or simply the database name. However, in the second case shown below, the default value will be chosen for the missing field. This section describes how to create a database using configuration objects.

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

Use existing database

After the database is created, you can retrieve the instance later to do more. To initialize an instance of the database, use the following method.

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

Starting with version 2.1.11, you can also use the ODatabase class to initialize the Server API and connect to the database immediately. The syntax for that is as follows:

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

Once the database instance is initialized, the stored records, that is, the information stored in the database, can be retrieved and manipulated using the database's Record ID (RID) ().

Note: The record ID is a unique value, so you don't need to create another field that references the primary key, as you would in a typical SQL-based relational database.

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

--cluster: Functions as a cluster identifier. It directly references the cluster record to which the cluster belongs. Positive values for this parameter indicate permanent records, and negative values indicate temporary records. --position: Specifies the absolute position of the record in the cluster. Here, let's specify the RID of the record to get one record.

    function(article) {
        console.log('Loaded article:', article);

Now that we have the record, let's take a look at some of the operations. First is the delete operation. In general, deleting a record is relatively easy and can be done with the following code:


Next is the update operation. Updating records is a bit complicated, but it's still fine for me. You can do this after the corresponding data you want to update is loaded. The implementation method of the update function is shown below.

  .then(function(article) {
    article.title = 'New Title';
      .then(function() {
        console.log("Article updated successfully");

Note: Consider the following when using 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. 

Class API

Database derived objects are specially used to access, create, and manipulate classes. Specifically, when we say "class", we mean db.class. For example, here is a method for creating a class.

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

To get an existing class:

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

Note that these all return promises. Once the promise is resolved, the style will be more conscious of taking action. To return a list of all the classes stored in the currently connected database, apply the following code.

// List all the database classes
      console.log(classes.length + ' existing classes into ' + db.name);

      classes.forEach(cl => {

Next is the create operation. Creating classes is something you should know before you fully design your database structure. We must properly load the class we are working with before manipulating the property.

The list of Article class properties looks like this:

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

Property creation is done in much the same syntax.

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

You only need to set one property for the class. You don't have to set many properties. Now let's perform some actions.

First, let's delete the property by name.

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

Next, let's change the property name.

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 on the Class API, see this document (https://orientdb.com/docs/last/OrientJS-Class-Classes.html?spm=a2c65.11461447.0.0.4e462b3eZyH0hD).

Query in OrientDB

Queries are one of the most important operations that the database engine provides to better manage your data, and OrientDB allows you to query in one of two ways. Either issue the SQL request directly or use Query Builder to implicitly build the query in NodeJs is.

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

The query above is looking for an article that has been viewed 200 times. This query is relatively easy to execute. A way to take advantage of this possibility to issue instructions to the engine is to use more interesting SQL syntax using operators such as AND, OR, and LIKE. This possibility (easier) of using a parametricized request instead of concatenating the request substrings and parameters to completely construct the SQL string. Learn more about OrientDB's SQL syntax here.

Instead of writing the SQL query completely, you can use the Query Builder instead. Query Builder (https://querybuilder.js.org/?spm=a2c65.11461447.0.0.4e462b3eZyH0hD) allows you to call specific methods that are internally querying through database API actions. To do. Here we are running the same query in Query Builder as we did in SQL.

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

event information

In OrientDB, events act as callback methods that can be executed at the end or start of a query. Events are useful for debugging queries and performing special tasks for logging, profiling, and coordinating data. The event depends on the database. That is, each event is attached to a single database and you must use the Database API to create it. If you want to use this API, use the db.on () function. The following example uses the BeginQuery event to log all queries sent to the OrientDB server. (You can also use ʻendQuery` to end the query).

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


In this tutorial, we've seen how to set up OrientDB on an Alibaba Cloud ECS instance, but we've also explored how to use OrientJS with OrientDB.

Recommended Posts

How to use OrientJS and OrientDB together
How to use @Builder and @NoArgsConstructor together
How to use StringBurrer and Arrays.toString.
How to use EventBus3 and ThreadMode
How to use equality and equality (how to use equals)
How to set up and use kapt
How to use substring and substr methods
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
[Java] How to use FileReader class and BufferedReader class
[Ruby] How to use gsub method and sub method
How to use Segmented Control and points to note
How to use scope and pass processing (Jakarta)
[Java] How to use Calendar class and Date class
[Java] How to use Map
How to use Chain API
[Rails] How to use enum
How to use java Optional
How to use JUnit (beginner)
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use java class
How to use Swift UIScrollView
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Ruby: How to use cookies
How to use dependent :: destroy
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation
How to use RealSense with ubuntu 20.04 and ROS Noetic
How to use Java variables
[Rails] How to use authenticate_user!