Category: orientdb

  • 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 – Sequences nhận dự án làm có lương

    OrientDB – Sequences



    Sequences is a concept used in auto increment mechanism and it is introduced in OrientDB v2.2. In database terminology, sequence is a structure that manages the counter field. Simply said sequences are mostly used when you need a number that always increments. It supports two types−

    ORDERED − Each time the pointer calls the .next method that returns a new value.

    CACHED − The sequence will cache ‘N’ items on each node. To call each item we use .next(), which is preferred when the cache contains more than one item.

    Create Sequence

    Sequence is usually used to auto increment the id value of a person. Like other SQL concepts of OrientDB it also preforms similar operations as Sequence in RDBMS.

    The following statement is the basic syntax to create sequences.

    CREATE SEQUENCE <sequence> TYPE <CACHED|ORDERED> [START <start>]
    [INCREMENT <increment>] [CACHE <cache>]
    

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

    <Sequence> − Local name for sequence.

    TYPE − Defines the sequence type ORDERED or CACHED.

    START − Defines the initial value.

    INCREMENT − Defines the increment for each .next method call.

    CACHE − Defines the number of value to pre-cache, in the event that you used to cache sequence type.

    Let us create a sequence named ‘seqid’ which starts with number 1201. Try the following queries to implement this example with sequence.

    CREATE SEQUENCE seqid START 1201
    

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

    Sequence created successfully
    

    Try the following query to use sequence ‘seqid’ to insert the id value of Account table.

    INSERT INTO Account SET id = sequence(''seqid'').next()
    

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

    Insert 1 record(s) in 0.001000 sec(s)
    

    Alter Sequence

    Alter sequence is a command used to change the properties of a sequence. It will modify all the sequence options except sequence type.

    The following statement is the basic syntax to alter sequence.

    ALTER SEQUENCE <sequence> [START <start-point>]
    [INCREMENT <increment>] [CACHE <cache>]
    

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

    <Sequence> − Defines the sequence you want to change.

    START − Defines the initial value.

    INCREMENT − Defines the increment for each .next method call.

    CACHE − Defines the number of value to pre-cache in the event that you used to cache sequence type.

    Try the following query to alter the start value from ‘1201 to 1000’ of a sequence named seqid.

    ALTER SEQUENCE seqid START 1000
    

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

    Altered sequence successfully
    

    Drop Sequence

    Drop sequence is a command used to drop a sequence.

    The following statement is the basic syntax to drop a sequence.

    DROP SEQUENCE <sequence>
    

    Where <Sequence> defines the sequence you want to drop.

    Try the following query to drop a sequence named ‘seqid’.

    DROP SEQUENCE seqid
    

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

    Sequence dropped successfully
    

    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 – Create Edge nhận dự án làm có lương

    OrientDB – Create Edge



    In OrientDB, the concept Edge works like a relation between vertices with the help of some properties. Edges and vertices are the main components of a graph database. It applies polymorphism on Edges. The base class for an Edge is E. While implementing edges, if source or destination vertices are missing or don’t exist, then the transaction will be rollback.

    The following statement is the basic syntax of Create Edge Command.

    CREATE EDGE <class> [CLUSTER <cluster>] FROM <rid>|(<query>)|[<rid>]* TO <rid>|(<query>)|[<rid>]*
         [SET <field> = <expression>[,]*]|CONTENT {<JSON>}
         [RETRY <retry> [WAIT <pauseBetweenRetriesInMs]] [BATCH <batch-size>]
    

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

    <class> − Defines the class name for the edge.

    <cluster> − Defines the cluster in which you want to store the edge.

    JSON − Provides JSON content to set as the record.

    RETRY − Defines the number of retries to attempt in the event of conflict.

    WAIT − Defines the time to delay between retries in milliseconds.

    BATCH − Defines whether it breaks the command down into smaller blocks and the size of the batches.

    Example

    Execute the following query to create an edge E between two vertices #9:0 and #14:0.

    orientdb> CREATE EDGE FROM #11:4 TO #13:2
    

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

    Created edge ''[e[#10:0][#9:0->#14:0]]'' in 0.012000 sec(s)
    

    Execute the following query to create a new edge type and an edge of new type.

    orientdb> CREATE CLASS E1 EXTENDS E
    orientdb> CREATE EDGE E1 FROM #10:3 TO #11:4
    

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

    Created edge ''[e[#10:1][#10:3->#11:4]]'' in 0.011000 sec(s)
    

    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 – Delete Edge nhận dự án làm có lương

    OrientDB – Delete Edge



    Delete edge command is used to remove the database. This is equivalent of the delete command, with the addition of checking and maintaining consistency with vertices by removing all cross-references to the edge from both ‘in’ and ‘out’ vertex properties.

    The following statement is the basic syntax of Delete Edge command.

    DELETE EDGE
       ( <rid>
          |
          [<rid> (, <rid>)*]
          |
          ( [ FROM (<rid> | <select_statement> ) ] [ TO ( <rid> | <select_statement> ) ] )
          |
          [<class>]
       (
          [WHERE <conditions>]
          [LIMIT <MaxRecords>]
          [BATCH <batch-size>]
       ))
    
    

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

    FROM − Defines the starting point vertex of the edge to delete.

    To − Defines the ending point vertex of the edge to delete.

    WHERE − Defines the filtering conditions.

    LIMIT − Defines the maximum number of edges to delete.

    BATCH − Defines the block size for the operation.

    Example

    Try the following examples to learn how to delete edges.

    Execute the following query to delete the edge between two vertices (#11:2, #11:10). But there might be a chance that might exist one or more edges between two vertices. So that we are using the date property for proper functionality. This query will delete the edges which are created on ”2015-01-15” and later.

    orientdb {db = demo}> DELETE EDGE FROM #11:2 TO #11:10 WHERE date >= "2012-01-15"
    

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

    Delete record(s) ''2'' in 0.00200 sec(s)
    

    Execute the following query to delete edges starting from the vertex ‘#11:5’ to the vertex ‘#11:10’ and which are related to ‘class = Customer’.

    orientdb {db = demo}> DELETE EDGE FROM #11:5 TO #11:10 WHERE @class = ''Customer''
    

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

    Delete record(s) ''2'' in 0.00200 sec(s)
    

    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 – Functions nhận dự án làm có lương

    OrientDB – Functions



    This chapter explains the complete reference of different types of functions in OrientDB. The following table defines the list of functions, which are categorized by their functionality.

    Graph Functions

    Try some graph functions along with the following queries.

    Execute the following query to get all the outgoing vertices from all the vehicle vertices.

    orientdb {db = demo}>SELECT out() from Vehicle
    

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

    ---+----------+---------
     # | @class   | out
    ---+----------+---------
     0 | Vehicle  | #11:2
     1 | Vehicle  | #13:1
     2 | Vehicle  | #13:4
    ---+----------+---------
    

    Execute the following query to get both incoming and outgoing vertices from the vertex #11:3.

    orientdb {db = demo}>SELECT both() FROM #11:3
    

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

    ---+----------+--------+-------
     # | @class   | out    | in
    ---+----------+--------+-------
     0 | Vehicle  | #13:2  | #10:2
     ---+----------+-------+-------
    

    Math Functions

    Try some math functions using the following queries.

    Execute the following query to get the sum of salaries of all employees.

    orientdb {db = demo}>SELECT SUM(salary) FROM Employee
    

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

    ---+----------+---------
     # | @CLASS   | sum
    ---+----------+---------
     0 | null     | 150000
    ---+----------+---------
    

    Execute the following query to get the average salary of all employees.

    orientdb {db = demo}>SELECT avg(salary) FROM Employee
    

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

    ---+----------+---------
     # | @CLASS   | avg
    ---+----------+---------
     0 | null     | 25
    ---+----------+---------
    

    Collections Functions

    Try some collection functions using the following queries.

    Execute the following query to get a set of teachers, teaching class 9th.

    orientdb {db = demo}>SELECT ID, set(teacher.id) AS teacherID from classess where class_id = 9
    

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

    ---+----------+--------+--------------------------
     # | @CLASS   | id     | TeacherID
    ---+----------+--------+--------------------------
     0 | null     | 9     |   1201, 1202, 1205, 1208
    ---+----------+-------+---------------------------
    

    Misc Functions

    Try some Misc functions using the following queries.

    Execute the following query to learn how to execute if expression.

    orientdb {db = demo}> SELECT if(eval("name = ''satish''"), "My name is satish",
    "My name is not satish") FROM Employee
    

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

    ----+--------+-----------------------
    #   |@CLASS  | IF
    ----+--------+-----------------------
    0   |null    |My name is satish
    1   |null    |My name is not satish
    2   |null    |My name is not satish
    3   |null    |My name is not satish
    4   |null    |My name is not satish
    ----+--------+------------------------
    

    Execute the following query to get system date.

    orientdb {db = demo}> SELECT SYSDATE() FROM Employee
    

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

    ----+--------+-----------------------
    #   |@CLASS  | SYSDATE
    ----+--------+-----------------------
    0   |null    |2016-02-10 12:05:06
    1   |null    |2016-02-10 12:05:06
    2   |null    |2016-02-10 12:05:06
    3   |null    |2016-02-10 12:05:06
    4   |null    |2016-02-10 12:05:06
    ----+--------+------------------------
    

    By using this function thoroughly you can easily manipulate the OrientDB data.


    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 – Update Edge nhận dự án làm có lương

    OrientDB – Update Edge



    Update edge command is used to update edge records in the current database. This is equivalent to actual update command in addition to checking and maintaining graph consistency with vertices, in the event that you update the out and in properties.

    The following statement is the basic syntax of Update Edge Command.

    UPDATE EDGE <edge>
       [SET|INCREMENT|ADD|REMOVE|PUT <field-name> = <field-value> [,]*]|[CONTENT|MERGE <JSON>]
       [RETURN <returning> [<returning-expression>]]
       [WHERE <conditions>]
       [LOCK default|record]
       [LIMIT <max-records>] [TIMEOUT <timeout>]
    

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

    <edge> − Defines the edge that you want to update. You can choose between Class that updates edges by class, Cluster that updates edges by cluster, using CLUSTER prefix, or Record ID that updating edges by record ID.

    SET − Updates the field to the given values.

    INCREMENT − Increments the given field by the value.

    ADD − Defines an item to add to a collection of fields.

    REMOVE − Defines an item to remove from a collection of fields.

    PUT − Defines an entry to put into map fields.

    RETURN − Defines the expression you want to return after running the update.

    WHERE − Defines the filter condition.

    LOCK − Defines how the record locks between the load and updates.

    LIMIT − Defines the maximum number of records.

    Example

    Let us consider an example of updating the edge named ‘address’ in the person class by taking data from the address table having area Id = 001, and the person name = Krishna.

    orientdb> UPDATE EDGE address SET out = (SELECT FROM Address WHERE areaID = 001)
    WHERE name = ''krishna''
    

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

    Updated edge ''[address[#10:3][#11:3->#14:2]]'' in 0.012000 sec(s)
    

    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 – Indexes nhận dự án làm có lương

    OrientDB – Indexes



    Index is a pointer which points to a location of data in the database. Indexing is a concept used to quickly locate the data without having to search every record in a database. OrientDB supports four index algorithms and several types within each.

    The four types of index are −

    SB-Tree Index

    It provides a good mix of features available from other index types. Better to use this for general utility. It is durable, transactional and supports range queries. It is default index type. The different type plugins that support this algorithm are −

    • UNIQUE − These indexes do not allow duplicate keys. For composite indexes, this refers to the uniqueness of the composite keys.

    • NOTUNIQUE − These indexes allow duplicate keys.

    • FULLTEXT − These indexes are based on any single word of text. You can use them in queries through the CONTAINSTEXT operator.

    • DICTIONARY − These indexes are similar to those that use UNIQUE, but in the case of duplicate keys, they replace the existing record with the new record.

    Hash Index

    It performs faster and is very light in disk usage. It is durable, transactional, but does not support range queries. It works like HASHMAP, which makes it faster on punctual lookups and it consumes less resources than other index types. The different type plugins that support this algorithm are −

    • UNIQUE_HASH_INDEX − These indexes do not allow duplicate keys. For composite indexes, this refers to the uniqueness of the composite keys.

    • NOTUNIQUE_HASH_INDEX − These indexes allow duplicate keys.

    • FULLTEXT_HASH_INDEX − These indexes are based on any single word of text. You can use them in queries through the CONTAINSTEXT operator.

    • DICTIONARY_HASH_INDEX − These indexes are similar to those that use UNIQUE_HASH_INDEX, but in cases of duplicate keys, they replace the existing record with the new record.

    Lucene Full Text Index

    It provides good full-text indexes, but cannot be used to index other types. It is durable, transactional, and supports range queries.

    Lucene Spatial Index

    It provides good spatial indexes, but cannot be used to index other types. It is durable, transactional, and supports range queries.

    Creating Indexes

    Create index is a command to create an index on a particular schema.

    The following statement is the basic syntax to create an index.

    CREATE INDEX <name> [ON <class-name> (prop-names)] <type> [<key-type>]
    [METADATA {<metadata>}]
    

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

    <name> − Defines the logical name for the index. You can also use the <class.property> notation to create an automatic index bound to a schema property. <class> uses the class of the schema and <property> uses the property created in the class.

    <class-name> − Provides the name of the class that you are creating the automatic index to index. This class must exist in the database.

    <prop-names> − Provides the list of properties, which you want the automatic index to index. These properties must already exist in schema.

    <type> − Provides the algorithm and type of index that you want to create.

    <key-type> − Provides the optional key type with automatic indexes.

    <metadata> − Provides the JSON representation.

    Example

    Try the following query to create automatic index bound to the property ‘ID’ of the user sales_user.

    orientdb> CREATE INDEX indexforID ON sales_user (id) UNIQUE
    

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

    Creating index...
    Index created successfully with 4 entries in 0.021000 sec(s)
    

    Querying Indexes

    You can use select query to get the records in the index.

    Try the following query to retrieve the keys of index named ‘indexforId’.

    SELECT FROM INDEX:indexforId
    

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

    ----+------+----+-----
    #   |@CLASS|key |rid
    ----+------+----+-----
    0   |null  |1   |#11:7
    1   |null  |2   |#11:6
    2   |null  |3   |#11:5
    3   |null  |4   |#11:8
    ----+------+----+-----
    

    Drop Indexes

    If you want to drop a particular index, you can use this command. This operation does not remove linked records.

    The following statement is the basic syntax to drop an index.

    DROP INDEX <name>
    

    Where <name> provides the name of the index you want to drop.

    Try the following query to drop an index named ‘ID’ of user sales_user.

    DROP INDEX sales_users.Id
    

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

    Index dropped successfully
    

    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 – Transactions nhận dự án làm có lương

    OrientDB – Transactions



    Like RDBMS, OrientDB supports transactions ACID properties. A transaction comprises a unit of work performed within a database management system. There are two main reasons to maintain transactions in a database environment.

    • To allow concurrent recovery from failures and keep a database consistent even in case of system failures.

    • To provide isolation between programs accessing a database concurrently.

    By default, the database transaction must follow ACID properties such as Atomic, Consistent, Isolated, and Durable properties. But OrientDB is an ACID compliant database, which means it does not contradict or negate the concept ACID, but it changes its perception while handling the NoSQL database. Take a look at how ACID properties work along with NoSQL database.

    Atomic − When you do something to change the database the change should work or fail as a whole.

    Consistent − The database should remain consistent.

    Isolated − If other transaction executions are executing at the same time, then the user will not be able to see the records in concurrent execution.

    Durable − If the system crashes (hardware or software), the database itself should be able to take a backup.

    Database transaction can be achieved by using Commit and Rollback commands.

    Commit

    Commit means closing the transaction by saving all changes to the database. Rollback means recover the database state to the point where you opened the transaction.

    The following statement is the basic syntax of the COMMIT database command.

    COMMIT
    

    Note − You can use this command only after connecting to a particular database and after beginning the transaction.

    Example

    In this example, we will use the same database named ‘demo’ that we created in an earlier chapter of this tutorial. We will see the operation of commit transaction and store a record using transactions.

    You need to first start the transaction using the following BEGIN command.

    orientdb {db = demo}> BEGIN
    

    Insert a record into an employee table with the values id = 12 and name = satish.P using the following command.

    orientdb> INSERT INTO employee (id, name) VALUES (12, ''satish.P'')
    

    You can use the following command to commit the transaction.

    orientdb> commit
    

    If this transaction successfully committed, you will get the following output.

    Transaction 2 has been committed in 4ms
    

    Rollback

    Rollback means recovering the database state to the point where you opened the transaction.

    The following statement is the basic syntax of the ROLLBACK database command.

    ROLLBACK
    

    Note − You can use this command only after connecting to a particular database and after beginning the transaction.

    Example

    In this example, we will use the same database named ‘demo’ that we created in an earlier chapter of the tutorial. We will see the operation of rollback transaction and store a record using transactions.

    You have to first start the transaction using the following BEGIN command.

    orientdb {db = demo}> BEGIN
    

    Insert a record into an employee table with the values id = 12 and name = satish.P using the following command.

    orientdb> INSERT INTO employee (id, name) VALUES (12, ''satish.P'')
    

    You can use the following command to retrieve the records of the table employee.

    orientdb> SELECT FROM employee WHERE name LIKE ''%.P''
    

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

    ---+-------+--------------------
     # | ID   | name
    ---+-------+--------------------
     0 | 12   | satish.P
    ---+-------+--------------------
    1 item(s) found. Query executed in 0.076 sec(s).
    

    You can use the following command to Rollback this transaction.

    orientdb> ROLLBACK
    

    Check the select query again to retrieve the same record from the Employee table.

    orientdb> SELECT FROM employee WHERE name LIKE ''%.P''
    

    If the Rollback is executed successfully, you will get 0 records found in the output.

    0 item(s) found. Query executed in 0.037 sec(s).
    

    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

  • 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