Author: alien

  • Khóa học miễn phí OrientDB – Useful Resources nhận dự án làm có lương

    OrientDB – Useful Resources



    The following resources contain additional information on OrientDB. Please use them to get more in-depth knowledge on this.

    Useful Video Courses

    42 Lectures 8.5 hours

    34 Lectures 7 hours

    Most Popular

    73 Lectures 7.5 hours

    31 Lectures 1 hours

    Best Seller

    71 Lectures 2.5 hours

    Most Popular

    20 Lectures 49 mins


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Python Interface nhận dự án làm có lương

    OrientDB – Python Interface



    OrientDB driver for Python uses the binary protocol. PyOrient is the git hub project name which helps to connect OrientDB with Python. It works with OrientDB version 1.7 and later.

    The following command is used to install PyOrient.

    pip install pyorient
    

    You can use the script file named demo.py to do the following tasks −

    • Create a client instance means create a connection.

    • Create DB named DB_Demo.

    • Open DB named DB_Demo.

    • Create class my_class.

    • Create properties id, and name.

    • Insert record into my class.

    //create connection
    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect( "admin", "admin" )
    
    //create a databse
    client.db_create( db_name, pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_MEMORY )
    
    //open databse
    client.db_open( DB_Demo, "admin", "admin" )
    
    //create class
    cluster_id = client.command( "create class my_class extends V" )
    
    //create property
    cluster_id = client.command( "create property my_class.id Integer" )
    cluster_id = client.command( "create property my_class.name String" )
    
    //insert record
    client.command("insert into my_class ( ''id'',''’name'' ) values( 1201, ''satish'')")
    

    Execute the above script using the following command.

    $ python demo.py
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Upgrading nhận dự án làm có lương

    OrientDB – Upgrading



    While upgrading, you have to consider the version number and the format. There are three types of formats – MAJOR, MINOR, PATCH.

    • MAJOR version entails incompatible API changes.

    • MINOR version entails functionality in a backward-compatible manner.

    • PTCH version entails backward-compatible bug fixes.

    To synchronize between minor and major versions, you may need to export and import the databases. Sometimes you many need to migrate the database from LOCAL to PLOCAL and need to migrate the graph to RidBag.

    Migrate from LOCAL Storage Engine to PLOCAL

    Starting from version 1.5.x OrientDB comes with a brand new storage engine: PLOCAL (Paginated LOCAL). It”s persistent like the LOCAL, but stores information in a different way. Following points show the comparison between PLOCAL and LOCAL −

    • In PLOCAL Records are stored in cluster files, while with LOCAL was split between cluster and data-segments.

    • PLOCAL is more durable than LOCAL because of the append-on-write mode.

    • PLOCAL has minor contention locks on writes, which means more concurrency.

    • PLOCAL doesn”t use Memory Mapping techniques (MMap) so the behavior is more “predictable”.

    To migrate your LOCAL storage to the new PLOCAL, you need to export and re-import the database using PLOCAL as storage engine. Following is the procedure.

    Step 1 − Open a new shell (Linux/Mac) or a Command Prompt (Windows).

    Step 2 − Export the database using the console. Follow the given command to export database demo into demo.json.gzip file.

    $ bin/console.sh (or bin/console.bat under Windows)
    orientdb> CONNECT DATABASE local:/temp/demo admin admin
    orientdb> EXPORT DATABASE /temp/demo.json.gzip
    orientdb> DISCONNECT
    

    Step 3 − On a local filesystem, create a new database using the “plocal” engine −

    orientdb> CREATE DATABASE plocal:/temp/newdb admin admin plocal graph
    

    Step 4 − Import the old database to the new one.

    orientdb> IMPORT DATABASE /temp/demo.json.gzip -preserveClusterIDs=true
    orientdb> QUIT
    

    If you access the database in the same JVM, remember to change the URL from “local:” to “plocal:”

    Migrate Graph to RidBag

    As of OrientDB 1.7, the RidBag is a default collection that manages adjacency relations in graphs. While the older database managed by an MVRB-Tree are fully compatible, you can update your database to the more recent format.

    You can upgrade your graph via console or using the ORidBagMigration class.

    • Connect to database CONNECT plocal:databases/<graphdb-name>

    • Run upgrade graph command


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Studio nhận dự án làm có lương

    OrientDB – Studio



    OrientDB provides a web UI to carry out database operations through GUI. This chapter explains the different options available in OrientDB.

    Studio Homepage

    Studio is a web interface for the administration of OrientDB that comes in bundle with the OrientDB distribution.

    First, you need to start the OrientDB server using the following command.

    $ server.sh
    

    If you run OrientDB in your machine, the web interface can be accessed via the URL −

    http://localhost:2480
    

    If the command is executed successfully, following will be the output on screen.

    Administration of OrientDB

    Connect to an Existing Database

    To login, select a database from the databases list and use any database user. By default (username/password) reader/reader can read records from the database, writer/writer can read, create, update and delete records, while admin/admin has all rights.

    Drop an Existing Database

    Select a database from the databases list and click the trash icon. Studio will open a confirmation popup where you have to insert the Server User and Server Password.

    Then click the “Drop database” button. You can find the server credentials in the $ORIENTDB_HOME/config/orientdb-server-config.xml file.

    <users>
       <user name = "root" password = "pwd" resources = "*" />
    </users>
    

    Create a New Database

    To create a new database, click the “New DB” button from the homepage.

    New Database

    Following information is needed to create a new database −

    • Database name
    • Database type (Document/Graph)
    • Storage type (plocal/memory)
    • Server user
    • Server password

    You can find the server credentials in the $ORIENTDB_HOME/config/orientdbserver-config.xml file.

    <users>
       <user name = "root" password = "pwd" resources = "*" />
    </users>
    

    Once created, Studio will automatically login to the new database.

    Execute a Query

    Studio supports auto recognition of the language you”re using between those supported: SQL and Gremlin. While writing, use the auto-complete feature by pressing Ctrl + Space.

    The following shortcuts are available in the query editor −

    • Ctrl + Return − To execute the query or just click the Run button.

    • Ctrl/Cmd + Z − To undo changes.

    • Ctrl/Cmd + Shift + Z − To redo changes.

    • Ctrl/Cmd + F − To search in the editor.

    • Ctrl/Cmd + / − To toggle a comment.

    The following screenshot shows how to execute a query.

    Execute a Query

    By clicking any @rid value in the result-set, you will go into document edit mode if the record is a Document, otherwise you will go into vertex edit.

    You can bookmark your queries by clicking the star icon in the results-set or in the editor. To browse bookmarked queries, click the Bookmarks button. Studio will open the bookmarks list on the left, where you can edit/delete or rerun queries.

    Bookmarks Query

    Studio saves the executed queries in the Local Storage of the browser. In the query settings, you can configure how many queries studio will keep in history. You can also search a previously executed query, delete all the queries from the history, or delete a single query.

    Edit Vertex

    To edit the vertex of the graph, go to the Graph section. Then run the following query.

    Select From Customer
    

    On successfully running the query, following be the output screenshot. Select the particular vertex in the graph canvas to edit.

    Graph Canvas

    Select the edit symbol on the particular vertex. You will get the following screen which contains the options to edit the vertex.

    Edit Symbol

    Schema Manager

    OrientDB can work in schema-less mode, schema mode or a mix of both. Here we”ll discuss the schema mode. Click on the Schema section on the top of web UI. You will get the following screenshot.

    Schema Mode

    Create a New Class

    To create a new Class, just click the New Class button. Following screenshot will appear. You will have to provide the following information as shown in the screenshot to create the new class.

    Create New Class

    View All Indexes

    When you want to have an overview of all indexes created in your database, just click he all indexes button in the Schema UI. This will provide a quick access to some information about indexes (name, type, properties, etc.) and you can drop or rebuild them from here.

    View All Indexes

    Edit Class

    Click on any class on the schema section, you will get the following screenshot.

    Edit Class

    While editing a class, you can add a property or add a new index.

    Add a Property

    Click the New Property button to add property. You will get the following screenshot.

    You have to provide the following details as shown in the screenshot to add property.

    Add Property

    Add an Index

    Click the New Index button. You will get the following screenshot. You have to provide the following details as shown in the screenshot to add an index.

    Add an Index

    Graph Editor

    Click the graph section. Not only can you visualize your data in a graph style but you can also interact with the graph and modify it.

    To populate the graph area, type a query in the query editor or use the functionality Send To Graph from the Browse UI.

    Graph Editor

    Add Vertices

    To add a new Vertex in your Graph Database and in the Graph Canvas area, you have to press the button Add Vertex. This operation is done in two steps.

    In the first step, you have to choose the class for the new Vertex and then click Next.

    Add Vertex

    In the second step, you have to insert the field values of the new vertex. You can also add custom fields as OrientDB supports schema-less mode. To make the new vertex persistent, click ‘Save changes’ and the vertex will be saved into the database and added to the canvas area.

    New Vertex

    Delete Vertices

    Open the circular menu by clicking on the Vertex that you want to delete. Open the submenu by hovering the mouse to the menu entry more (…) and then click the trash icon.

    Remove Vertices from Canvas

    Open the circular menu, open the sub-menu by hovering the mouse to the menu entry more (…) and then click the eraser icon.

    Inspect Vertices

    If you want to take a quick look to the Vertex property, click to the eye icon.

    Inspect Vertex

    Security

    Studio 2.0 includes the new Security Management, where you can manage Users and Roles in a graphical way.

    Users

    You can perform the following actions to manage the database users −

    • Search Users
    • Add Users
    • Delete Users
    • Edit User: roles can be edited in-line, for name, status and password click the Edit button
    database users

    Add Users

    To add a new User, click the Add User button, complete the information for the new user (name, password, status, roles) and then save to add the new user to the database.

    Add Users

    Roles

    You can perform the following actions to manage the database roles −

    • Search Role
    • Add Role
    • Delete Role
    • Edit Role
    Database Roles

    Add Role

    To add a new User, click the Add Role button, complete the information for the new role (name, parent role, mode) and then save to add the new role to the database.

    Add Roles

    Add Rule to a Role

    To add a new security rule for the selected role, click the Add Rule button. This will ask you the string of the resource that you want to secure. Then you can configure the CRUD permissions on the newly created resource.

    Add Role

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Java Interface nhận dự án làm có lương

    OrientDB – Java Interface



    Similar to RDBMS, OrientDB supports JDBC. For this, first we need to configure the environment for JDBC programming. Following is the procedure to create a connection between your application and database.

    First, we need to download the JDBC Driver. Visit the following link to download OrientDB-JDBC.

    Following are the basic five steps to achieve OrientDB-jdbc connectivity.

    • Load JDBC driver
    • Create Connection
    • Create statement
    • Execute statement
    • Close connection

    Example

    Try the following example to understand OrientDB-JDBC connectivity. Let us consider we have an employee table which contains the following fields and its types.

    Sr.No. Field Name Type
    1 Id Integer
    2 Name String
    3 Salary Integer
    4 Join date Date

    You can create a Schema (table) by executing the following commands.

    CREATE DATABASE PLOCAL:/opt/orientdb/databases/testdb
    CREATE CLASS Employee
    CREATE PROPERTY Customer.id integer
    CREATE PROPERTY Customer.name String
    CREATE PROPERTY Customer.salary integer
    CREATE PROPERTY Customer.join_date date
    

    After executing all the commands, you will get the Employee table with the following fields, employee name with id, age, and join_date fields.

    Save the following code into OrientJdbcDemo.java file.

    import com.orientechnologies.common.log.OLogManager;
    import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.BeforeClass;
    
    import java.io.File;
    import java.sql.DriverManager;
    import java.util.Properties;
    
    import static com.orientechnologies.orient.jdbc.OrientDbCreationHelper.createSchemaDB;
    import static com.orientechnologies.orient.jdbc.OrientDbCreationHelper.loadDB;
    import static java.lang.Class.forName;
    
    public abstract class OrientJdbcDemo {
    
       protected OrientJdbcConnection conn;
    
       public static void main(String ar[]){
    
          //load Driver
          forName(OrientJdbcDriver.class.getName());
          String dbUrl = "memory:testdb";
          ODatabaseDocumentTx db = new ODatabaseDocumentTx(dbUrl);
          String username = "admin";
          String password = "admin";
          createSchemaDB(db);
          loadDB(db, 20);
          dbtx.create();
    
          //Create Connection
          Properties info = new Properties();
          info.put("user", username);
          info.put("password", password);
          conn = (OrientJdbcConnection) DriverManager.getConnection("jdbc:orient:" + dbUrl, info);
    
          //create and execute statement
          Statement stmt = conn.createStatement();
          int updated = stmt.executeUpdate("INSERT into emplyoee
             (intKey, text, salary, date) values (''001'',''satish'',''25000'',''"
              + date.toString() + "'')");
    
          int updated = stmt.executeUpdate("INSERT into emplyoee
             (intKey, text, salary, date) values (''002'',''krishna'',''25000'',''"
             + date.toString() + "'')");
    
          System.out.println("Records successfully inserted");
    
          //Close Connection
          if (conn != null && !conn.isClosed())
             conn.close();
       }
    }
    

    The following command is used to compile the above program.

    $ javac –classpath:.:orientdb-jdbc-1.0-SNAPSHOT.jar OrientJdbcDemo.java
    $ java –classpath:.:orientdb-jdbc-1.0-SNAPSHOT.jar OrientJdbcDemo
    

    If the above command is executed successfully, you will get the following output.

    Records Successfully Inserted
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Security nhận dự án làm có lương

    OrientDB – Security



    Like RDBMS, OrientDB also provides security based on well-known concepts, users, and roles. Each database has its own users and each user has one or more roles. Roles are the combination of working modes and set of permissions.

    Users

    By default OrientDB maintains three different users for all database in the server −

    • Admin − This user has access to all functions on the database without limitation.

    • Reader − This user is a read-only user. The reader can query any records in the database, but can”t modify or delete them. It has no access to internal information, such as the users and roles themselves.

    • Writer − This user is the same as the user reader, but it can also create, update, and delete records.

    Working with Users

    When you are connected to a database, you can query the current users on the database by using SELECT queries on the OUser class.

    orientdb> SELECT RID, name, status FROM OUser
    

    If the above query is executed successfully, you will get the following output.

    ---+--------+--------+--------
    #  | @CLASS | name   | status
    ---+--------+--------+--------
    0  | null   | admin  | ACTIVE
    1  | null   | reader | ACTIVE
    2  | null   | writer | ACTIVE
    ---+--------+--------+--------
    3 item(s) found. Query executed in 0.005 sec(s).
    

    Creating a New User

    To create a new user, use the INSERT command. Remember, in doing so, you must set the status to ACTIVE and give it a valid role.

    orientdb> INSERT INTO OUser SET
                   name = ''jay'',
                   password = ''JaY'',
                   status = ''ACTIVE'',
                   roles = (SELECT FROM ORole WHERE name = ''reader'')
    

    Updating Users

    You can change the name for the user with the UPDATE statement.

    orientdb> UPDATE OUser SET name = ''jay'' WHERE name = ''reader''
    

    In the same way, you can also change the password for the user.

    orientdb> UPDATE OUser SET password = ''hello'' WHERE name = ''reader''
    

    OrientDB saves the password in a hash format. The trigger OUserTrigger encrypts the password transparently before it saves the record.

    Disabling Users

    To disable a user, use UPDATE to switch its status from ACTIVE to SUSPENDED. For instance, if you want to disable all users except for admin, use the following command −

    orientdb> UPDATE OUser SET status = ''SUSPENDED'' WHERE name <> ''admin''
    

    Roles

    A role determines what operations a user can perform against a resource. Mainly, this decision depends on the working mode and the rules. The rules themselves work differently, depending on the working mode.

    Working with Roles

    When you are connected to a database, you can query the current roles on the database using SELECT queries on the ORole class.

    orientdb> SELECT RID, mode, name, rules FROM ORole
    

    If the above query is executed successfully, you will get the following output.

    --+------+----+--------+-------------------------------------------------------
    # |@CLASS|mode| name   | rules
    --+------+----+--------+-------------------------------------------------------
    0 | null | 1  | admin  | {database.bypassRestricted = 15}
    1 | null | 0  | reader | {database.cluster.internal = 2, database.cluster.orole = 0...
    2 | null | 0  | writer | {database.cluster.internal = 2, database.cluster.orole = 0...
    --+------+----+--------+-------------------------------------------------------
    3 item(s) found.  Query executed in 0.002 sec(s).
    

    Creating New Roles

    To create a new role, use the INSERT statement.

    orientdb> INSERT INTO ORole SET name = ''developer'', mode = 0
    

    Working with Modes

    Where rules determine what users belonging to certain roles can do on the databases, working modes determine how OrientDB interprets these rules. There are two types of working modes, designated by 1 and 0.

    • Allow All But (Rules) − By default it is the super user mode. Specify exceptions to this using the rules. If OrientDB finds no rules for a requested resource, then it allows the user to execute the operation. Use this mode mainly for power users and administrators. The default role admin uses this mode by default and has no exception rules. It is written as 1 in the database.

    • Deny All But (Rules) − By default this mode allows nothing. Specify exceptions to this using the rules. If OrientDB finds rules for a requested resource, then it allows the user to execute the operation. Use this mode as the default for all classic users. The default roles, reader and writer, use this mode. It is written as 0 in the database.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Performance Tuning nhận dự án làm có lương

    OrientDB – Performance Tuning



    In this chapter, you can get some general tips on how to optimize your application that uses OrientDB. There are three ways to increase the performance for different types of database.

    • Document Database Performance Tuning − It uses a technique that helps avoid document creation for every new document.

    • Object Database Performance Tuning − It uses the generic techniques to improve performance.

    • Distributed Configuration Tuning − It uses different methodologies to improve performance in distributed configuration.

    You can achieve generic performance tuning by changing the Memory, JVM, and Remote connection settings.

    Memory Settings

    There are different strategies in memory setting to improve performance.

    Server and Embedded Settings

    These settings are valid for both Server component and the JVM where the Java application is run using OrientDB in Embedded mode, by directly using plocal.

    The most important thing on tuning is assuring the memory settings are correct. What can make a real difference is the right balancing between the heap and the virtual memory used by Memory Mapping, especially on large datasets (GBs, TBs and more) where the inmemory cache structures count less than raw IO.

    For example, if you can assign maximum 8GB to the Java process, it”s usually better assigning small heap and large disk cache buffer (off-heap memory).

    Try the following command to increase the heap memory.

    java -Xmx800m -Dstorage.diskCache.bufferSize=7200 ...
    

    The storage.diskCache.bufferSize setting (with old “local” storage it was file.mmap.maxMemory) is in MB and tells how much memory to use for Disk Cache component. By default it is 4GB.

    NOTE − If the sum of maximum heap and disk cache buffer is too high, it could cause the OS to swap with huge slowdown.

    JVM Settings

    JVM settings are encoded in server.sh (and server.bat) batch files. You can change them to tune the JVM according to your usage and hw/sw settings. Add the following line in server.bat file.

    -server -XX:+PerfDisableSharedMem
    

    This setting will disable writing debug information about the JVM. In case you need to profile the JVM, just remove this setting.

    Remote Connections

    There are many ways to improve performance when you access the database using a remote connection.

    Fetching Strategy

    When you work with a remote database you have to pay attention to the fetching strategy used. By default, OrientDB client loads only the record contained in the resultset. For example, if a query returns 100 elements, but if you cross these elements from the client, then OrientDB client lazily loads the elements with one more network call to the server for each missed record.

    Network Connection Pool

    Each client, by default, uses only one network connection to talk with the server. Multiple threads on the same client share the same network connection pool.

    When you have multiple threads, there could be a bottleneck since a lot of time is spent waiting for a free network connection. This is the reason why it is important to configure the network connection pool.

    The configuration is very simple, just 2 parameters −

    • minPool − It is the initial size of the connection pool. The default value is configured as global parameters “client.channel.minPool”.

    • maxPool − It is the maximum size the connection pool can reach. The default value is configured as global parameters “client.channel.maxPool”.

    If all the pool connections are busy, then the client thread will wait for the first free connection.

    Example command of configuration by using database properties.

    database = new ODatabaseDocumentTx("remote:localhost/demo");
    database.setProperty("minPool", 2);
    database.setProperty("maxPool", 5);
    
    database.open("admin", "admin");
    

    Distributed Configuration Tuning

    There are many ways to improve performance on distributed configuration.

    Use Transactions

    Even when you update graphs, you should always work in transactions. OrientDB allows you to work outside of them. Common cases are read-only queries or massive and nonconcurrent operations can be restored in case of failure. When you run on distributed configuration, using transactions helps to reduce latency. This is because the distributed operation happens only at commit time. Distributing one big operation is much efficient than transferring small multiple operations, because of the latency.

    Replication vs Sharding

    OrientDB distributed configuration is set to full replication. Having multiple nodes with the same copy of database is important for scale reads. In fact, each server is independent on executing reads and queries. If you have 10 server nodes, the read throughput is 10x.

    With writes, it”s the opposite: having multiple nodes with full replication slows down the operations, if the replication is synchronous. In this case, sharding the database across multiple nodes allows you to scale up writes, because only a subset of nodes are involved on write. Furthermore, you could have a database bigger than one server node HD.

    Scale up on Writes

    If you have a slow network and you have a synchronous (default) replication, you could pay the cost of latency. In fact when OrientDB runs synchronously, it waits at least for the writeQuorum. This means that if the writeQuorum is 3, and you have 5 nodes, the coordinator server node (where the distributed operation is started) has to wait for the answer from at least 3 nodes in order to provide the answer to the client.

    In order to maintain the consistency, the writeQuorum should be set to the majority. If you have 5 nodes the majority is 3. With 4 nodes, it is still 3. Setting the writeQuorum to 3 instead of 4 or 5 allows to reduce the latency cost and still maintain the consistency.

    Asynchronous Replication

    To speed things up, you can set up Asynchronous Replication to remove the latency bottleneck. In this case, the coordinator server node executes the operation locally and gives the answer to the client. The entire replication will be in the background. In case the quorum is not reached, the changes will be rolled back transparently.

    Scale up on Reads

    If you already set the writeQuorum to the majority of nodes, you can leave the readQuorum to 1 (the default). This speeds up all the reads.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Caching nhận dự án làm có lương

    OrientDB – Caching



    Caching is a concept that will create a copy of the database table structure providing a comfortable environment for the user applications. OrientDB has several caching mechanisms at different levels.

    The following illustration gives an idea about what caching is.

    Caching Mechanisms

    In the above illustration DB1, DB2, DB3 are the three different database instances used in an application.

    Level-1 cache is a Local cache which stores all the entities known by a specific session. If you have three transactions in this session, it will hold all entities used by all three transactions. This cache gets cleared when you close the session or when you perform the “clear” method. It reduces the burden of the I/O operations between the application and the database and in turn increases the performance.

    Level-2 cache is a Real cache that works by using third party provider. You can have full control over the contents of the cache, i.e. you will be able to specify which entries should be removed, which ones should be stored longer and so on. It is a full shared cache among multiple threads.

    Storage model is nothing but storage device that is disk, memory, or remote server.

    How Cache Works in OrientDB?

    OrientDB caching provides different methodologies in different environments. Caching is mainly used for faster database transactions, reducing the processing time of a transaction and increasing the performance. The following flow diagrams show how caching works in local mode and client-server mode.

    Local Mode (Embedded Database)

    The following flow diagram tells you how the record is in-between storage and used application in the local mode i.e., when your database server is in your localhost.

    Embedded Database

    When the client application asks for a record OrientDB checks for the following −

    • If a transaction has begun, then it searches inside the transaction for changed records and returns it if found.

    • If the local cache is enabled and contains the requested record, then returns it.

    • If at this point the record is not in cache, then asks for it to the Storage (disk, memory).

    Client Server Mode (Remote Database)

    The following flow diagram tells you how the record is in-between storage and used application in the client-server mode i.e., when your database server is in remote location.

    Remote Database

    When the client application asks for a record, OrientDB checks for the following −

    • If a transaction has begun, then it searches inside the transaction for changed records and returns it if found.

    • If the local cache is enabled and contains the requested record, then returns it.

    • At this point, if the record is not in cache, then asks for it to the Server through a TCP/IP call.

    • In the server, if the local cache is enabled and contains the requested record, then returns it.

    • At this point, still the record is not cached in the server, then asks for it to the Storage (disk, memory).


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Logging nhận dự án làm có lương

    OrientDB – Logging



    OrientDB uses the Java Logging framework bundled with Java Virtual Machine. OrientDB”s default log format is managed by OLogFormatter class.

    The following statement is the basic syntax of logging command.

    <date> <level> <message> [<requester>]
    

    Following are the details about the options in the above syntax.

    <date> − It is the log date in the following format: yyyy-MM-dd HH:mm:ss:SSS.

    <level> − It is the logging level as 5 chars output.

    <message> − It is the text of log, it can be of any size.

    [<class>] − It is the Java class that is logged (optional).

    Supported levels are those contained in the JRE class java.util.logging.Level. They are −

    • SEVERE (highest value)
    • WARNING
    • INFO
    • CONFIG
    • FINE
    • FINER
    • FINEST (lowest value)

    By default, two loggers are installed −

    • Console, as the output of the shell/command prompt that starts the application/server. Can be changed by setting the variable ‘log.console.level’.

    • File, as the output to the log files. Can be changed by setting the ‘log.file.level’.

    Configure Logging

    The logging strategies and policies can be configured using a file following the Java.

    syntax − Java Logging configuration.

    Example

    Copy the following content from orientdb-server-log.properties file and put it in the $ORIENTDB_HOME/config file.

    # Specify the handlers to create in the root logger
    # (all loggers are children of the root logger)
    # The following creates two handlers
    handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler
    # Set the default logging level for the root logger
    .level = ALL
    
    # Set the default logging level for new ConsoleHandler instances
    java.util.logging.ConsoleHandler.level = INFO
    # Set the default formatter for new ConsoleHandler instances
    java.util.logging.ConsoleHandler.formatter =
       com.orientechnologies.common.log.OLogFormatter
    
    # Set the default logging level for new FileHandler instances
    java.util.logging.FileHandler.level = INFO
    # Naming style for the output file
    java.util.logging.FileHandler.pattern =../log/orient-server.log
    # Set the default formatter for new FileHandler instances
    java.util.logging.FileHandler.formatter = com.orientechnologies.common.log.OLogFormatter
    # Limiting size of output file in bytes:
    java.util.logging.FileHandler.limit = 10000000
    # Number of output files to cycle through, by appending an
    # integer to the base file name:
    java.util.logging.FileHandler.count = 10
    

    To tell the JVM where the properties file is placed, you need to set the “java.util.logging.config.file” system property to it. For example, use the following command −

    $ java -Djava.util.logging.config.file=mylog.properties ...
    

    Set the logging level

    To change the logging level without modifying the logging configuration, just set the “log.console.level” and “log.file.level” system variables to the requested levels.

    Logging at Startup

    Following are the procedures to set logging at startup level in different ways.

    In the Server Configuration

    Open the file orientdb-server-config.xml and add or update these lines at the end of the file inside the <properties> section −

    <entry value = "fine" name = "log.console.level" />
    <entry value = "fine" name = "log.file.level" />
    

    In Server.sh (or .bat) Script

    Set the system property “log.console.level” and “log.file.level” to the levels you want using the -D parameter of java.

    $ java -Dlog.console.level = FINE ...
    

    Logging at Run-time

    Following are the procedures to set logging at startup level in different ways.

    By Using Java Code

    The system variable can be set at startup using the System.setProperty() API. The following code snippet is the syntax to set logging level using Java code.

    public void main(String[] args){
       System.setProperty("log.console.level", "FINE");
       ...
    }
    

    On Remote Server

    Execute a HTTP POST against the URL: /server/log.<type>/<level>, where −

    • <type> can be “console” or “file”
    • <level> is one of the supported levels

    Example

    The following example uses cURL to execute a HTTP POST command against OrientDB Server. Server”s “root” user and password were used, replace with your own password.

    Enable the finest tracing level to console −

    curl -u root:root -X POST http://localhost:2480/server/log.console/FINEST
    

    Enable the finest tracing level to file −

    curl -u root:root -X POST http://localhost:2480/server/log.file/FINEST
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí OrientDB – Hooks nhận dự án làm có lương

    OrientDB – Hooks



    OrientDB Hooks are nothing but triggers in the database terminology that enable internal events before and after each CRUD operations in the user applications. You can use hooks to write custom validation rules, to enforce security, or to arrange external events like replicating against a relational DBMS.

    OrientDB supports two kinds of hooks −

    Dynamic Hook − Triggers, which can be built at class level and/or Document level.

    Java (Native) Hook − Triggers, which can be built using Java classes.

    Dynamic Hooks

    Dynamic hooks are more flexible than Java hooks, because they can be changed at runtime and can run per document if needed, but are slower than Java hooks.

    To execute hooks against your documents, first allow your classes to extend OTriggered base class. Later, define a custom property for the interested event. Following are the available events.

    • onBeforeCreate − Called before creating a new document.

    • onAfterCreate − Called after creating a new document.

    • onBeforeRead − Called before reading a document.

    • onAfterRead − Called after reading a document.

    • onBeforeUpdate − Called before updating a document.

    • onAfterUpdate − Called after updating a document.

    • onBeforeDelete − Called before deleting a document.

    • onAfterDelete − Called after deleting a document.

    Dynamic Hooks can call −

    • Functions, written in SQL, Javascript or any language supported by OrientDB and JVM.

    • Java static methods.

    Class Level Hooks

    Class level hooks are defined for all the documents that relate to a class. Following is an example to set up a hook that acts at class level against Invoice documents.

    CREATE CLASS Invoice EXTENDS OTriggered
    ALTER CLASS Invoice CUSTOM onAfterCreate = invoiceCreated
    

    Let”s create the function invoiceCreated in Javascript that prints in the server console the invoice number created.

    CREATE FUNCTION invoiceCreated "print(''\nInvoice created: '' + doc.field (''number''));"
    LANGUAGE Javascript
    

    Now try the hook by creating a new Invoice document.

    INSERT INTO Invoice CONTENT {number: 100, notes: ''This is a test}
    

    If this command is executed successfully, you will get the following output.

    Invoice created: 100
    

    Document Level Hook

    You can define a special action only against one or more documents. To do this, allow your class to extend OTriggered class.

    For example let us execute a trigger, as Javascript function, against an existent Profile class, for all the documents with property account = ”Premium”. The trigger will be called to prevent deletion of documents.

    ALTER CLASS Profile SUPERCLASS OTriggered UPDATE Profile
    SET onBeforeDelete = ''preventDeletion'' WHERE account = ''Premium''
    

    Let”s create the preventDeletion() Javascript function.

    CREATE FUNCTION preventDeletion "throw new java.lang.RuntimeException(''Cannot
    delete Premium profile '' + doc)" LANGUAGE Javascript
    

    And then test the hook by trying to delete a ‘Premium’ account.

    DELETE FROM #12:1
    java.lang.RuntimeException: Cannot delete Premium profile
    profile#12:1{onBeforeDelete:preventDeletion,account:Premium,name:Jill} v-1
    (<Unknown source>#2) in <Unknown source> at line number 2
    

    JAVA Hooks

    One common use case for OrientDB Hooks (triggers) is to manage created and updated dates for any or all classes. For example, you can set a CreatedDate field whenever a record is created and set an UpdatedDate field whenever a record is updated, and do it in a way where you implement the logic once at the database layer and never have to worry about it again at the application layer.

    Before creating, you will have to download orientdb-core.jar file by visit the following link . And later copy that jar file into the folder where you want to store the Java source file.

    Create Hook File

    Create a Java file named HookTest.java, which will test the Hook mechanism using Java language.

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.StringReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.locks.ReentrantLock;
    import com.orientechnologies.orient.core.hook.ODocumentHookAbstract;
    import com.orientechnologies.orient.core.hook.ORecordHook;
    import com.orientechnologies.orient.core.hook.ORecordHookAbstract;
    import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener;
    import com.orientechnologies.orient.core.db.ODatabase;
    import com.orientechnologies.orient.core.record.ORecord;
    import com.orientechnologies.orient.core.record.impl.ODocument;
    
    public class HookTest extends ODocumentHookAbstract implements ORecordHook {
       public HookTest() {
    
       }
    
       @Override
       public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() {
          return DISTRIBUTED_EXECUTION_MODE.BOTH;
       }
       public RESULT onRecordBeforeCreate( ODocument iDocument ) {
          System.out.println("Ran create hook");
          return ORecordHook.RESULT.RECORD_NOT_CHANGED;
       }
       public RESULT onRecordBeforeUpdate( ODocument iDocument ) {
          System.out.println("Ran update hook");
          return ORecordHook.RESULT.RECORD_NOT_CHANGED;
       }
    }
    

    The above sample code prints the appropriate comment every time you create or update a record of that class.

    Let”s add one more hook file setCreatedUpdatedDates.java as follows −

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.StringReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.locks.ReentrantLock;
    import com.orientechnologies.orient.core.hook.ODocumentHookAbstract;
    import com.orientechnologies.orient.core.hook.ORecordHook;
    import com.orientechnologies.orient.core.hook.ORecordHookAbstract;
    import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener;
    import com.orientechnologies.orient.core.db.ODatabase;
    import com.orientechnologies.orient.core.record.ORecord;
    import com.orientechnologies.orient.core.record.impl.ODocument;
    
    public class setCreatedUpdatedDates extends ODocumentHookAbstract implements ORecordHook {
       public setCreatedUpdatedDates() {
    
       }
    
       @Override
       public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() {
          return DISTRIBUTED_EXECUTION_MODE.BOTH;
       }
       public RESULT onRecordBeforeCreate( ODocument iDocument ) {
          if ((iDocument.getClassName().charAt(0) == ''t'') || (iDocument.getClassName().charAt(0)==''r'')) {
             iDocument.field("CreatedDate", System.currentTimeMillis() / 1000l);
             iDocument.field("UpdatedDate", System.currentTimeMillis() / 1000l);
             return ORecordHook.RESULT.RECORD_CHANGED;
          } else {
             return ORecordHook.RESULT.RECORD_NOT_CHANGED;
          }
       }
    
       public RESULT onRecordBeforeUpdate( ODocument iDocument ) {
          if ((iDocument.getClassName().charAt(0) == ''t'') || (iDocument.getClassName().charAt(0)==''r'')) {
             iDocument.field("UpdatedDate", System.currentTimeMillis() / 1000l);
             return ORecordHook.RESULT.RECORD_CHANGED;
          } else {
             return ORecordHook.RESULT.RECORD_NOT_CHANGED;
          }
       }
    }
    

    What the above code does is look for any class that starts with the letters ‘r’ or ‘t’ and sets CreatedDate and UpdatedDate when the record gets created and sets just UpdatedDate every time the record gets updated.

    Compile Java Hooks

    Compile Java code by using the following command. Note: Keep the downloaded jar file and these Java files into the same folder.

    $ jar cf hooks-1.0-SNAPSHOT.jar *.java
    

    Move Compiled Code to Where OrientDB Server Can Find It

    You need to copy the finished .jar file to the directory where your OrientDB server will look for them. This means the ‘./lib’ folder under your OrientDB Server root directory will look like this −

    $ cp hooks-1.0-SNAPSHOT.jar "$ORIENTDB_HOME/lib"
    

    Enable Test Hook in the OrientDB Server Configuration File

    Edit $ORIENTDB_HOME/config/orientdb-server-config.xml and add the following section near the end of the file.

       <hooks>
          <hook class = "HookTest" position = "REGULAR"/>
       </hooks>
       ...
    </orient-server>
    

    Restart OrientDB Server

    Once you restart OrientDB Server, the hook you defined in orientdb-server-config.xml is now active. Launch an OrientDB console, connect it to your database, and run the following command −

    INSERT INTO V SET ID = 1;
    

    If this command is executed successfully, you will get the following output.

    Ran create hook
    

    Now run the following command −

    UPDATE V SET ID = 2 WHERE ID = 1;
    

    If this command is executed successfully, you will get the following output.

    Ran update hook
    

    Enable Real Hook in the OrientDB Server Configuration File

    Edit $ORIENTDB_HOME/config/orientdb-server-config.xml and change the hooks section as follows −

       <hooks>
          <hook class="setCreatedUpdatedDates" position="REGULAR"/>
       </hooks>
       ...
    </orient-server>
    

    Restart OrientDB Server

    Create a new class that starts with the letter ‘r’ or ‘t’ −

    CREATE CLASS tTest EXTENDS V;
    

    Now insert a record −

    INSERT INTO tTest SET ID = 1
    SELECT FROM tTest
    

    If this command is executed successfully, you will get the following output.

    ----+-----+------+----+-----------+-----------
    #   |@RID |@CLASS|ID  |CreatedDate|UpdatedDate
    ----+-----+------+----+-----------+-----------
    0   |#19:0|tTest |1   |1427597275 |1427597275
    ----+-----+------+----+-----------+-----------
    

    Even though you did not specify values to set for CreatedDate and UpdatedDate, OrientDB has set these fields automatically for you.

    Next you need to update the record using the following command −

    UPDATE tTest SET ID = 2 WHERE ID = 1;
    SELECT FROM tTest;
    

    If this command is executed successfully, you will get the following output.

    ----+-----+------+----+-----------+-----------
    #   |@RID |@CLASS|ID  |CreatedDate|UpdatedDate
    ----+-----+------+----+-----------+-----------
    0   |#19:0|tTest |2   |1427597275 |1427597306
    ----+-----+------+----+-----------+-----------
    

    You can see that OrientDB has changed the UpdatedDate but has let the CreatedDate remain unchanged.

    OrientDB Java Hooks can be an extremely valuable tool to help automate work you would otherwise have to do in application code. As many DBAs are not always Java experts, hopefully the information contained in this tutorial will give you a head start and make you feel comfortable with the technology, empowering you to successfully create database triggers as the need arises.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc