Orientdb 简明教程
OrientDB - Overview
OrientDB 是一个开源 NoSQL 数据库管理系统。 NoSQL Database 提供了一种存储和检索无关系或非关系数据(指除表格数据之外的数据,比如文档数据或图表数据)的机制。NoSQL 数据库越来越多地在大数据和实时网络应用程序中使用。NoSQL 系统有时也称为“不只是 SQL”,以强调它们可能支持类似 SQL 的查询语言。
OrientDB is an Open Source NoSQL Database Management System. NoSQL Database provides a mechanism for storing and retrieving NO-relation or NON-relational data that refers to data other than tabular data such as document data or graph data. NoSQL databases are increasingly used in Big Data and real-time web applications. NoSQL systems are also sometimes called "Not Only SQL" to emphasize that they may support SQL-like query languages.
OrientDB 也属于 NoSQL 系列。OrientDB 是一个第二代分布式图表数据库,具有一款产品的文档灵活性,并采用 Apache 2 的开源许可。在 OrientDB 之前,市场上已有几个 NoSQL 数据库,其中之一是 MongoDB。
OrientDB also belongs to the NoSQL family. OrientDB is a second generation Distributed Graph Database with the flexibility of Documents in one product with an open source of Apache 2 license. There were several NoSQL databases in the market before OrientDB, one of them being MongoDB.
MongoDB vs OrientDB
MongoDB 和 OrientDB 包含许多常见功能,但引擎从根本上是不同的。MongoDB 是纯文档数据库,而 OrientDB 是混合文档图表引擎。
MongoDB and OrientDB contains many common features but the engines are fundamentally different. MongoDB is pure Document database and OrientDB is a hybrid Document with graph engine.
Features |
MongoDB |
OrientDB |
Relationships |
Uses the RDBMS JOINS to create relationship between entities. It has high runtime cost and does not scale when database scale increases. |
Embeds and connects documents like relational database. It uses direct, super-fast links taken from graph database world. |
Fetch Plan |
Costly JOIN operations. |
Easily returns complete graph with interconnected documents. |
Transactions |
Doesn’t support ACID transactions, but it supports atomic operations. |
Supports ACID transactions as well as atomic operations. |
Query language |
Has its own language based on JSON. |
Query language is built on SQL. |
Indexes |
Uses the B-Tree algorithm for all indexes. |
Supports three different indexing algorithms so that the user can achieve best performance. |
Storage engine |
Uses memory mapping technique. |
Uses the storage engine name LOCAL and PLOCAL. |
OrientDB是第一个多模型开源NoSQL DBMS,它将图的功能和文档的灵活性集合在一个可伸缩的高性能操作数据库中。
OrientDB is the first Multi-Model open source NoSQL DBMS that brings together the power of graphs and flexibility of documents into a scalable high-performance operational database.
OrientDB - Installation
OrientDB安装文件有两种版本可用−
OrientDB installation file is available in two editions −
-
Community Edition − OrientDB community edition is released by Apache under 0.2 license as an open source
-
Enterprise Edition − OrientDB enterprise edition is released as a proprietary software, which is built on community edition. It serves as an extension of the community edition.
本章解释OrientDB社区版的安装过程,因为它开源。
This chapter explains the installation procedure of OrientDB community edition because it is open source.
Prerequisites
社区版和企业版均可在实现Java虚拟机(JVM)的任何操作系统上运行。OrientDB需要Java 1.7或更高版本。
Both community and Enterprise editions can run on any Operating system that implements the Java Virtual Machine (JVM). OrientDB requires Java with 1.7 or later version.
使用以下步骤将OrientDB下载并安装到您的系统中。
Use the following steps to download and install OrientDB into your system.
Step 1 − Download OrientDB Binary Setup File
OrientDB带有内置设置文件,可在您的系统上安装数据库。它为不同的操作系统提供了不同的预编译二进制包(焦油包或ZIP包)。您可以从 Download OrientDB 链接中下载OrientDB文件。
OrientDB comes with built-in setup file to install the database on your system. It provides different pre-compiled binary packages (tarred or zipped packages) for different operating systems. You can download OrientDB files from Download OrientDB link.
以下屏幕截图显示了OrientDB的下载页面。您可以通过单击合适的操作系统图标来下载ZIP或焦油文件。
The following screenshot shows the download page of OrientDB. You can download the zipped or tarred file by clicking the suitable operating system icon.
下载后,您将在 Downloads 文件夹中获取二进制包。
On downloading, you will get the binary package in your Downloads folder.
Step 2 − Extract and Install OrientDB
以下是为不同的操作系统提取和安装OrientDB的过程。
Following is the procedure to extract and install OrientDB for different operating systems.
In Linux
下载后,您将在 Downloads 文件夹中获取 orientdb-community-2.1.9.tar.gz 文件。您可以使用以下命令来提取焦油文件。
After download you will get orientdb-community-2.1.9.tar.gz file in your Downloads folder. You can use the following command to extract the tarred file.
$ tar –zxvf orientdb-community-2.1.9.tar.gz
您可以使用以下命令从 orientdbcommunity-2.1.9 to /opt/orientdb/ 目录移动所有OrientDB库文件。在此,我们使用超级用户命令(sudo),因此您必须提供超级用户密码以执行以下命令。
You can use the following command to move all the OrientDB library files from orientdbcommunity-2.1.9 to /opt/orientdb/ directory. Here we are using super user command (sudo) therefore you have to provide super user password to execute the following command.
$ sudo mv orientdb-community-2.1.9 /opt/orientdb
你可以使用以下命令注册 orientdb 命令和 Orient 服务器。
You can use the following commands to register the orientdb command and the Orient server.
$ export ORIENTDB_HoME = /opt/orientdb
$ export PATH = $PATH:$ORIENTDB_HOME/bin
In Windows
-
After download you will get orientdb-community-2.1.9.zip file in your Downloads folder. Extract the zip file using the zip extractor.
-
Move the extracted folder into the C:\ directory.
-
Create two environmental variables ORIENTDB_HOME and PATH variables with following given values.
ORIENT_HOME = C:\orientdb-community-2.1.9
PATH = C:\orientdb-community-2.1.9\bin
Step 3 − Configuring OrientDB Server as a Service
按照上述步骤,你可以使用 OrientDB 的桌面版本。你可以使用以下步骤以服务形式启动 OrientDB 数据库服务器。该程序根据你的操作系统而不同。
By following the above steps you can use the Desktop version of OrientDB. You can start OrientDB database server as a service by using the following steps. The procedure is different, depending on your operating system.
In Linux
OrientDB 提供了一个名为 orientdb.sh 的脚本文件,用以将数据库作为守护进程运行。你可以在 OrientDB 安装目录的 bin/directory 中找到它,即 $ORIENTDB_HOME/bin/orientdb.sh。
OrientDB provides a script file named orientdb.sh to run the database as a daemon. You can find it in the bin/directory of your OrientDB installation directory that is $ORIENTDB_HOME/bin/orientdb.sh.
在运行脚本文件之前,你必须编辑 orientdb.sh 文件以定义两个变量。一个是 ORIENTDB_DIR ,它定义了安装目录的路径 ( /opt/orientdb ),第二个是 ORIENTDB_USER ,它定义了你希望运行 OrientDB 的用户名,如下所示。
Before running the script file, you have to edit orientdb.sh file for defining two variables. One is ORIENTDB_DIR which defines the path to the installation directory (/opt/orientdb) and the second is ORIENTDB_USER which defines the username you want run OrientDB for as follows.
ORIENTDB_DIR = "/opt/orientdb"
ORIENTDB_USER = "<username you want to run OrientDB>"
使用以下命令将 orientdb.sh 文件复制到 /etc/init.d/ 目录中以初始化和运行脚本。此处我们使用超级用户命令 (sudo),因此你必须提供超级用户密码才能执行以下命令。
Use the following command to copy orientdb.sh file into /etc/init.d/ directory for initializing and running the script. Here we are using super user command (sudo) therefore you have to provide super user password to execute the following command.
$ sudo cp $ORIENTDB_HOME/bin/orientdb.sh /etc/init.d/orientdb
使用以下命令将 control.sh 文件从 OrientDB 安装目录 $ORIENTDB_HOME/bin 复制到系统 bin 目录 /usr/bin ,以访问 Orient DB 的控制台。
Use the following command to copy the console.sh file from OrientDB installation directory that is $ORIENTDB_HOME/bin to the system bin directory that is /usr/bin for accessing the Orient DB’s console.
$ sudo cp $ ORIENTDB_HOME/bin/console.sh /usr/bin/orientdb
使用以下命令以服务形式启动 ORIENTDB 数据库服务器。此处你必须提供你在 orientdb.sh 文件中提到的相应用户的密码来启动服务器。
Use the following command to start the ORIENTDB database server as service. Here you have to provide the respective user’s password which you mention in the orientdb.sh file to start the server.
$ service orientdb start
使用以下命令了解 OrientDB 服务器守护进程正在运行哪个 PID 上。
Use the following command to know on which PID the OrientDB server daemon is running.
$ service orientdb status
使用以下命令停止 OrinetDB 服务器守护进程。此处你必须提供你在 orientdb.sh 文件中提到的相应用户的密码来停止服务器。
Use the following command to stop the OrientDB server daemon. Here you have to provide the respective user’s password, which you mention in the orientdb.sh file to stop the server.
$ service orientdb stop
In Windows
OrientDB 是一个服务器应用程序,因此它必须在启动关闭 Java 虚拟机进程之前执行多项任务。如果你想手动关闭 OrientDB 服务器,则必须执行 shutdown.bat 文件。但是,如果系统在不执行上述脚本的情况下突然关闭,则服务器实例不会正确停止。Windows 中操作系统使用一组特定信号控制的程序称为 services 。
OrientDB is a server application therefore it has to perform several tasks before starting shutting down the Java virtual machine process. If you want to shutdown OrientDB server manually then you have to execute shutdown.bat file. But the server instances do not stop correctly, when the system shuts down suddenly without executing the above script. The programs which are controlled by the operating system with a set of specified signals are called services in Windows.
我们必须使用 Apache Common Daemon ,它允许 Windows 用户将 Java 应用程序包装为 Windows 服务。以下是下载和注册 Apache common daemon 的过程。
We have to use Apache Common Daemon which allow Windows users to wrap Java applications as Windows service. Following is the procedure to download and register Apache common daemon.
-
Click the following link for Apache Common Daemons for windows.
-
Click on common-daemon-1.0.15-bin-windows to download.
-
Unzip the common-daemon-1.0.15-bin-windows directory. After extracting you will find prunsrv.exe and prunmgr.exe files inside the directory. In those − prunsrv.exe file is a service application for running applications as services. prunmgr.exe file is an application used for monitoring and configuring windows services.
-
Go to OrientDB installation folder → create a new directory and name it service.
-
Copy the prunsrv.exe and prunmgr .exe paste it into to the service directory.
-
In order to configure OrientDB as Windows service, you have to execute a short script that uses the prusrv.exe as a Windows service.
-
Before defining the Windows Services, you have to rename prunsrv and prunmgr according to the name of the service. For e.g. OrientDBGraph and OrientDBGraphw respectively. Here OrientDBGraph is the name of the service.
-
Copy the following script into the file named installService.bat and place it into %ORIENTDB_HOME%\service\ directory.
:: OrientDB Windows Service Installation
@echo off
rem Remove surrounding quotes from the first parameter
set str=%~1
rem Check JVM DLL location parameter
if "%str%" == "" goto missingJVM
set JVM_DLL=%str%
rem Remove surrounding quotes from the second parameter
set str=%~2
rem Check OrientDB Home location parameter
if "%str%" == "" goto missingOrientDBHome
set ORIENTDB_HOME=%str%
set CONFIG_FILE=%ORIENTDB_HOME%/config/orientdb-server-config.xml
set LOG_FILE = %ORIENTDB_HOME%/config/orientdb-server-log.properties
set LOG_CONSOLE_LEVEL = info
set LOG_FILE_LEVEL = fine
set WWW_PATH = %ORIENTDB_HOME%/www
set ORIENTDB_ENCODING = UTF8
set ORIENTDB_SETTINGS = -Dprofiler.enabled = true
-Dcache.level1.enabled = false Dcache.level2.strategy = 1
set JAVA_OPTS_SCRIPT = -XX:+HeapDumpOnOutOfMemoryError
rem Install service
OrientDBGraphX.X.X.exe //IS --DisplayName="OrientDB GraphEd X.X.X" ^
--Description = "OrientDB Graph Edition, aka GraphEd, contains OrientDB server
integrated with the latest release of the TinkerPop Open Source technology
stack supporting property graph data model." ^
--StartClass = com.orientechnologies.orient.server.OServerMain
-StopClass = com.orientechnologies.orient.server.OServerShutdownMain ^
--Classpath = "%ORIENTDB_HOME%\lib\*" --JvmOptions
"Dfile.Encoding = %ORIENTDB_ENCODING%; Djava.util.logging.config.file = "%LOG_FILE%";
Dorientdb.config.file = "%CONFIG_FILE%"; -Dorientdb.www.path = "%WWW_PATH%";
Dlog.console.level = %LOG_CONSOLE_LEVEL%; -Dlog.file.level = %LOG_FILE_LEVEL%;
Dorientdb.build.number = "@BUILD@"; -DORIENTDB_HOME = %ORIENTDB_HOME%" ^
--StartMode = jvm --StartPath = "%ORIENTDB_HOME%\bin" --StopMode = jvm
-StopPath = "%ORIENTDB_HOME%\bin" --Jvm = "%JVM_DLL%"
-LogPath = "%ORIENTDB_HOME%\log" --Startup = auto
EXIT /B
:missingJVM
echo Insert the JVM DLL location
goto printUsage
:missingOrientDBHome
echo Insert the OrientDB Home
goto printUsage
:printUsage
echo usage:
echo installService JVM_DLL_location OrientDB_Home
EXIT /B
该脚本需要两个参数 -
The script requires two parameters −
-
The location of jvm.dll, for e.g. C:\ProgramFiles\java\jdk1.8.0_66\jre\bin\server\jvm.dll
-
The location of OrientDB installation for e.g. C:\orientdb-community-2.1.9
-
The service is installed when you execute the OrientDBGraph.exe file (Original prunsrv) and double-click on it.
-
Use the following command to install services into Windows.
> Cd %ORIENTDB_HOME%\service
> installService.bat "C:\Program Files\Java\jdk1.8.0_66\jre\bin\server
\jvm.dll" C:\orientdb-community-2.1.9
打开任务管理器服务,您将看到其中有已注册服务名称的以下屏幕截图。
Open the Task Manager services, you will find the following screenshot with the registered service name is in it.
Step 4 − Verifying OrientDB Installation
此步骤将通过以下步骤验证 OrientDB 数据库服务器安装。
This step verifies the OrientDB database server installation using the following steps.
-
Run the server.
-
Run the console.
-
Run the studio.
这根据操作系统而异。
This is unique according to the operating system.
In Linux
按照给定的步骤验证 Linux 中的 OrientDB 安装。
Follow the given procedure for verifying OrientDB installation in Linux.
Running the server − 您可以使用以下命令启动服务器。
Running the server − You can use the following command to start the server.
$ cd $ORIENTDB_HOME/bin
$ ./server.sh
或者,您可以使用以下命令将 OrientDB 服务器启动为 UNIX 守护程序。
Or you can use the following command to start the OrientDB server as UNIX daemon.
$ service orientdb start
如果安装成功,您将收到以下输出。
If it is installed successfully, you will receive the following output.
.
.` `
, `:.
`,` ,:`
.,. :,,
.,, ,,,
. .,.::::: ```` ::::::::: :::::::::
,` .::,,,,::.,,,,,,`;; .: :::::::::: ::: :::
`,. ::,,,,,,,:.,,.` ` .: ::: ::: ::: :::
,,:,:,,,,,,,,::. ` ` `` .: ::: ::: ::: :::
,,:.,,,,,,,,,: `::, ,, ::,::` : :,::` :::: ::: ::: ::: :::
,:,,,,,,,,,,::,: ,, :. : :: : .: ::: ::: :::::::
:,,,,,,,,,,:,:: ,, : : : : .: ::: ::: :::::::::
` :,,,,,,,,,,:,::, ,, .:::::::: : : .: ::: ::: ::: :::
`,...,,:,,,,,,,,,: .:,. ,, ,, : : .: ::: ::: ::: :::
.,,,,::,,,,,,,: `: , ,, : ` : : .: ::: ::: ::: :::
...,::,,,,::.. `: .,, :, : : : .: ::::::::::: ::: :::
,::::,,,. `: ,, ::::: : : .: ::::::::: ::::::::::
,,:` `,,.
,,, .,`
,,. `, GRAPH DATABASE
`` `.
`` orientdb.com
`
2016-01-20 19:17:21:547 INFO OrientDB auto-config DISKCACHE = 1,
649MB (heap = 494MB os = 4, 192MB disk = 199, 595MB) [orientechnologies]
2016-01-20 19:17:21:816 INFO Loading configuration from:
/opt/orientdb/config/orientdb-server-config.xml... [OServerConfigurationLoaderXml]
2016-01-20 19:17:22:213 INFO OrientDB Server v2.1.9-SNAPSHOT
(build 2.1.x@r; 2016-01-07 10:51:24+0000) is starting up... [OServer]
2016-01-20 19:17:22:220 INFO Databases directory: /opt/orientdb/databases [OServer]
2016-01-20 19:17:22:361 INFO Port 0.0.0.0:2424 busy,
trying the next available... [OServerNetworkListener]
2016-01-20 19:17:22:362 INFO Listening binary connections on 0.0.0.0:2425
(protocol v.32, socket = default) [OServerNetworkListener]
...
2016-01-20 19:17:22:614 INFO Installing Script interpreter. WARN:
authenticated clients can execute any kind of code into the server
by using the following allowed languages:
[sql] [OServerSideScriptInterpreter]
2016-01-20 19:17:22:615 INFO OrientDB Server v2.1.9-SNAPSHOT
(build 2.1.x@r; 2016-01-07 10:51:24+0000) is active. [OServer]
Running the console − 您可以使用以下命令在控制台下运行 OrientDB。
Running the console − You can use the following command to run the OrientDB under console.
$ orientdb
如果安装成功,您将收到以下输出。
If it is installed successfully, you will receive the following output.
OrientDB console v.2.1.9-SNAPSHOT (build 2.1.x@r; 2016-01-07 10:51:24+0000) www.orientdb.com
Type 'help' to display all the supported commands.
Installing extensions for GREMLIN language v.2.6.0
orientdb>
Running the Studio − 启动服务器后,您可以在浏览器中使用以下 URL ( http://localhost:2480/ )。您将看到以下屏幕截图。
Running the Studio − After starting the server you can use the following URL (http://localhost:2480/) on your browser. You will get the following screenshot.
In Windows
按照给定的步骤验证 Windows 中的 OrientDB 安装。
Follow the given procedure for verifying OrientDB installation in Windows.
Running the server − 您可以使用以下命令启动服务器。
Running the server − You can use the following command to start the server.
> cd %ORIENTDB_HOME%\bin
> ./server.bat
如果安装成功,您将收到以下输出。
If it is installed successfully, you will receive the following output.
.
.` `
, `:.
`,` ,:`
.,. :,,
.,, ,,,
. .,.::::: ```` ::::::::: :::::::::
,` .::,,,,::.,,,,,,`;; .: :::::::::: ::: :::
`,. ::,,,,,,,:.,,.` ` .: ::: ::: ::: :::
,,:,:,,,,,,,,::. ` ` `` .: ::: ::: ::: :::
,,:.,,,,,,,,,: `::, ,, ::,::` : :,::` :::: ::: ::: ::: :::
,:,,,,,,,,,,::,: ,, :. : :: : .: ::: ::: :::::::
:,,,,,,,,,,:,:: ,, : : : : .: ::: ::: :::::::::
` :,,,,,,,,,,:,::, ,, .:::::::: : : .: ::: ::: ::: :::
`,...,,:,,,,,,,,,: .:,. ,, ,, : : .: ::: ::: ::: :::
.,,,,::,,,,,,,: `: , ,, : ` : : .: ::: ::: ::: :::
...,::,,,,::.. `: .,, :, : : : .: ::::::::::: ::: :::
,::::,,,. `: ,, ::::: : : .: ::::::::: ::::::::::
,,:` `,,.
,,, .,`
,,. `, GRAPH DATABASE
`` `.
`` orientdb.com
`
2016-01-20 19:17:21:547 INFO OrientDB auto-config DISKCACHE = 1,649MB
(heap = 494MB os = 4, 192MB disk = 199, 595MB) [orientechnologies]
2016-01-20 19:17:21:816 INFO Loading configuration from:
/opt/orientdb/config/orientdb-server-config.xml...
[OServerConfigurationLoaderXml]
...
2016-01-20 19:17:22:615 INFO OrientDB Server v2.1.9-SNAPSHOT
(build 2.1.x@r; 2016-01-07 10:51:24+0000) is active. [OServer]
Running the console − 您可以使用以下命令在控制台下运行 OrientDB。
Running the console − You can use the following command to run OrientDB under console.
> %ORIENTDB_HOME%\bin\console.bat
如果安装成功,您将收到以下输出。
If it is installed successfully, you will receive the following output.
OrientDB console v.2.1.9-SNAPSHOT (build 2.1.x@r; 2016-01-07 10:51:24+0000) www.orientdb.com
Type 'help' to display all the supported commands.
Installing extensions for GREMLIN language v.2.6.0
orientdb\>
Running the Studio − 启动服务器后,您可以在浏览器中使用以下 URL ( http://localhost:2480/ )。您将看到以下屏幕截图。
Running the Studio − After starting the server you can use the following URL (http://localhost:2480/) on your browser. You will get the following screenshot.
OrientDB - Basic Concepts
OrientDB 的主要功能是对多模型对象的支持,即支持文档、图、键/值和真实对象等不同的模型。它包含一个单独的 API 来支持这四个模型。
The main feature of OrientDB is to support multi-model objects, i.e. it supports different models like Document, Graph, Key/Value and Real Object. It contains a separate API to support all these four models.
Document Model
术语文档模型属于 NoSQL 数据库。这意味着数据存储在文档中,并且一组文档称为 Collection 。从技术上讲,文档表示一组键/值对,或称为字段或属性。
The terminology Document model belongs to NoSQL database. It means the data is stored in the Documents and the group of Documents are called as Collection. Technically, document means a set of key/value pairs or also referred to as fields or properties.
OrientDB 使用类、丛集和链接等概念来存储、分组和分析文档。
OrientDB uses the concepts such as classes, clusters, and link for storing, grouping, and analyzing the documents.
下表说明了关系模型、文档模型和 OrientDB 文档模型之间的比较 −
The following table illustrates the comparison between relational model, document model, and OrientDB document model −
Relational Model |
Document Model |
OrientDB Document Model |
Table |
Collection |
Class or Cluster |
Row |
Document |
Document |
Column |
Key/value pair |
Document field |
Relationship |
Not available |
Link |
Graph Model
图数据结构是一个数据模型,它可以以顶点(节点)的形式存储数据,顶点通过边(弧)相互连接。OrientDB 图数据库的构思源自属性图。顶点和边是图模型的主要组成部分。它们包含属性,这可以使它们看起来类似于文档。
A graph data structure is a data model that can store data in the form of Vertices (Nodes) interconnected by Edges (Arcs). The idea of OrientDB graph database came from property graph. The vertex and edge are the main artifacts of the Graph model. They contain the properties, which can make these appear similar to documents.
下表显示了图模型、关系数据模型和 OrientDB 图模型之间的比较。
The following table shows a comparison between graph model, relational data model, and OrientDB graph model.
Relational Model |
Graph Model |
OrientDB Graph Model |
Table |
Vertex and Edge Class |
Class that extends "V" (for Vertex) and "E" (for Edges) |
Row |
Vertex |
Vertex |
Column |
Vertex and Edge property |
Vertex and Edge property |
Relationship |
Edge |
Edge |
The Key/Value Model
键/值模型表示数据可以以键/值对的形式存储,其中值可以是简单类型和复杂类型。它可以支持文档和图形元素作为值。
The Key/Value model means that data can be stored in the form of key/value pair where the values can be of simple and complex types. It can support documents and graph elements as values.
下表说明了关系模型、键/值模型和 OrientDB 键/值模型之间的比较。
The following table illustrates the comparison between relational model, key/value model, and OrientDB key/value model.
Relational Model |
Key/Value Model |
OrientDB Key/Value Model |
Table |
Bucket |
Class or Cluster |
Row |
Key/Value pair |
Document |
Column |
Not available |
Document field or Vertex/Edge property |
Relationship |
Not available |
Link |
The Object Model
此模型由面向对象编程继承,并且支持类型(子类型扩展超类型)之间的 Inheritance 、类型指的是基础类时的 Polymorphism 以及编程语言中使用的对象来自/至的 Direct binding 。
This model has been inherited by Object Oriented programming and supports Inheritance between types (sub-types extends the super-types), Polymorphism when you refer to a base class and Direct binding from/to Objects used in programming languages.
下表说明了关系模型、对象模型和 OrientDB 对象模型之间的比较。
The following table illustrates the comparison between relational model, Object model, and OrientDB Object model.
Relational Model |
Object Model |
OrientDB Object Model |
Table |
Class |
Class or Cluster |
Row |
Object |
Document or Vertex |
Column |
Object property |
Document field or Vertex/Edge property |
Relationship |
Pointer |
Link |
在详细讨论之前,最好了解与 OrientDB 相关的基本术语。以下是一些重要的术语。
Before go ahead in detail, it is better to know the basic terminology associated with OrientDB. Following are some of the important terminologies.
Record
可以从数据库加载和存储的最小单位。记录可以存储在四种类型中。
The smallest unit that you can load from and store in the database. Records can be stored in four types.
-
Document
-
Record Bytes
-
Vertex
-
Edge
Record ID
当 OrientDB 生成记录时,数据库服务器会自动为该记录分配一个单元标识符,称为 RecordID (RID)。RID 看起来像 #<cluster>:<position>。 <cluster> 表示集群标识号,<position> 表示集群中记录的绝对位置。
When OrientDB generates a record, the database server automatically assigns a unit identifier to the record, called RecordID (RID). The RID looks like #<cluster>:<position>. <cluster> means cluster identification number and the <position> means absolute position of the record in the cluster.
Documents
文档是 OrientDB 中可用的最灵活的记录类型。文档是软类型,由具有定义约束的模式类定义,但你也可以在没有任何模式的情况下插入文档,即它也支持无模式模式。
The Document is the most flexible record type available in OrientDB. Documents are softly typed and are defined by schema classes with defined constraint, but you can also insert the document without any schema, i.e. it supports schema-less mode too.
文档可以通过 JSON 格式轻松地导出和导入。例如,看一看以下 JSON 示例文档。它定义了文档详细信息。
Documents can be easily handled by export and import in JSON format. For example, take a look at the following JSON sample document. It defines the document details.
{
"id" : "1201",
"name" : "Jay",
"job" : "Developer",
"creations" : [
{
"name" : "Amiga",
"company" : "Commodore Inc."
},
{
"name" : "Amiga 500",
"company" : "Commodore Inc."
}
]
}
RecordBytes
记录类型与 RDBMS 中的 BLOB 类型相同。OrientDB 可以加载和存储文档记录类型以及二进制数据。
Record Type is the same as BLOB type in RDBMS. OrientDB can load and store document Record type along with binary data.
Vertex
OrientDB 数据库不仅是文档数据库,也是图形数据库。使用顶点和边等新概念以图形的形式存储数据。在图形数据库中,最基本的数据单位是节点,在 OrientDB 中称为顶点。顶点为数据库存储信息。
OrientDB database is not only a Document database but also a Graph database. The new concepts such as Vertex and Edge are used to store the data in the form of graph. In graph databases, the most basic unit of data is node, which in OrientDB is called a vertex. The Vertex stores information for the database.
Edge
存在一种称为边(Edge)的独立记录类型,该类型将一个顶点连接到另一个顶点。边是双向的,并且只能连接两个顶点。OrientDB 中有两种类型的边,一种是常规的,另一种是轻量的。
There is a separate record type called the Edge that connects one vertex to another. Edges are bidirectional and can only connect two vertices. There are two types of edges in OrientDB, one is regular and another one lightweight.
Class
类是一种数据模型类型和从面向对象编程范例中汲取的概念。基于传统的文档数据库模型,数据以集合的形式存储,而在关系数据库模型中,数据存储在表中。OrientDB 遵循文档 API 以及 OPPS 范例。作为一个概念,OrientDB 中的类与关系数据库中的表的关系最密切,但是(与表不同)类可以是无模式的,全模式的或混合的。类可以继承自其他类,从而创建类的树。每个类都有自己的集群,(如果未定义,则默认创建)。
The class is a type of data model and the concept drawn from the Object-oriented programming paradigm. Based on the traditional document database model, data is stored in the form of collection, while in the Relational database model data is stored in tables. OrientDB follows the Document API along with OPPS paradigm. As a concept, the class in OrientDB has the closest relationship with the table in relational databases, but (unlike tables) classes can be schema-less, schema-full or mixed. Classes can inherit from other classes, creating trees of classes. Each class has its own cluster or clusters, (created by default, if none are defined).
Cluster
集群是一个重要的概念,用于存储记录、文档或顶点。简单来说,集群是存储一组记录的地方。默认情况下,OrientDB 将为每个类创建一个集群。一个类的所有记录都存储在具有与类同名的同一集群中。您可以在数据库中创建多达 32,767(2^15-1)个集群。
Cluster is an important concept which is used to store records, documents, or vertices. In simple words, Cluster is a place where a group of records are stored. By default, OrientDB will create one cluster per class. All the records of a class are stored in the same cluster having the same name as the class. You can create up to 32,767(2^15-1) clusters in a database.
CREATE class 是一条用于创建带有特定名称的集群的命令。创建集群后,您可以通过在创建任何数据模型期间指定名称来使用该集群来保存记录。
The CREATE class is a command used to create a cluster with specific name. Once the cluster is created you can use the cluster to save records by specifying the name during the creation of any data model.
Relationships
OrientDB 支持两种类型的关系:引用和嵌入。 Referenced relationships 表示其存储到关系目标对象的直接链接。 Embedded relationships 表示其存储到嵌入记录内的关系。这种关系比引用关系更强。
OrientDB supports two kinds of relationships: referenced and embedded. Referenced relationships means it stores direct link to the target objects of the relationships. Embedded relationships means it stores the relationship within the record that embeds it. This relationship is stronger than the reference relationship.
Database
数据库是访问真实存储的接口。它了解高级概念,例如查询、模式、元数据、索引等。OrientDB 还提供了多个数据库类型。有关这些类型的更多信息,请参阅数据库类型。
The database is an interface to access the real storage. IT understands high-level concepts such as queries, schemas, metadata, indices, and so on. OrientDB also provides multiple database types. For more information on these types, see Database Types.
OrientDB - Data Types
OrientDB 原生支持几种数据类型。以下是完整的表格。
OrientDB supports several data types natively. Following is the complete table on the same.
Sr. No. |
Type |
Description |
1 |
Boolean |
Handles only the values True or False. Java types: java.lang.Boolean Min: 0 Max: 1 |
2 |
Integer |
32-bit signed integers. Java types: java.lang.Interger Min: -2,147,483,648 Max: +2,147,483,647 |
3 |
Short |
Small 16-bit signed integers. Java types: java.lang.short Min: -32,768 Max: 32,767 |
4 |
Long |
Big 64-bit signed integers. Java types: java.lang.Long Min: -263 Max: +263-1 |
5 |
Float |
Decimal numbers. Java types: java.lang.Float : 2-149 Max: (2-2-23)*2,127 |
6 |
Double |
Decimal numbers with high precision. Java types: Java.lang.Double. Min: 2-1074 Max: (2-2-52)*21023 |
7 |
Date-time |
Any date with the precision up to milliseconds. Java types: java.util.Date |
8 |
String |
Any string as alphanumeric sequence of chars. Java types: java.lang.String |
9 |
Binary |
Can contain any value as byte array. Java types: byte[ ] Min: 0 Max: 2,147,483,647 |
10 |
Embedded |
The record is contained inside the owner. The contained record has no RecordId. Java types: ORecord |
11 |
Embedded list |
The records are contained inside the owner. The contained records have no RecordIds and are reachable only by navigating the owner record. Java types: List<objects> Min: 0 Max: 41,000,000 items |
12 |
Embedded set |
The records are contained inside the owner. The contained records have no RecordId and are reachable only by navigating the owner record. Java types: set<objects> Min: 0 Max: 41,000,000 items |
13 |
Embedded map |
The records are contained inside the owner as values of the entries, while the keys can only be strings. The contained records have no RecordId and are reachable only by navigating the owner Record. Java types: Map<String, ORecord> Min: 0 Max: 41,000,000 items |
14 |
Link |
Link to another Record. It’s a common one-to-one relationship Java Types: ORID, <? extends ORecord> Min: 1 Max: 32767:2^63-1 |
15 |
Link list |
Links to other Records. It’s a common one-to-many relationship where only the RecordIds are stored. Java types: List<? Extends ORecord> Min: 0 Max: 41,000,000 items |
16 |
Link set |
Links to other records. It’s a common one-to-many relationship. Java types: Set<? extends ORecord> Min: 0 Max: 41,000,000 items |
17 |
Link map |
Links to other records as value of the entries, while keys can only be strings. It’s a common one-to-many relationship. Only the RecordIds are stored. Java types: Map<String, ? extends Record> Min: 0 Max: 41,000,000 items |
18 |
Byte |
Single byte. Useful to store small 8-bit signed integers. Java types: java.lang.Byte Min: -128 Max: +127 |
19 |
Transient |
Any value not stored on database. |
20 |
Date |
Any date as year, month and day. Java Types: java.util.Date |
21 |
Custom |
Used to store a custom type providing the Marshall and Unmarshall methods. Java types: OSerializableStream Min: 0 Max: x |
22 |
Decimal |
Decimal numbers without rounding. Java types: java.math.BigDecimal |
23 |
LinkBag |
List of RecordIds as specific RidBag. Java types: ORidBag |
24 |
Any |
Not determinate type, used to specify collections of mixed type, and null. |
在以下章节中,将讨论如何在 OrientDB 中使用这些数据类型。
In the following chapters, how to use these data types in OrientDB is discussed.
OrientDB - Console Modes
OrientDB 控制台是一个 Java 应用程序,用于处理 OrientDB 数据库和服务器实例。OrientDB 支持多种控制台模式。
The OrientDB Console is a Java Application made to work against OrientDB databases and Server instances. There are several console modes that OrientDB supports.
Interactive Mode
这是默认模式。通过执行以下脚本 bin/console.sh (或在 MS Windows 系统中执行 bin/console.bat )启动控制台即可。确保有执行权限。
This is the default mode. Just launch the console by executing the following script bin/console.sh (or bin/console.bat in MS Windows systems). Make sure to have execution permission on it.
OrientDB console v.1.6.6 www.orientechnologies.com
Type 'help' to display all the commands supported.
orientdb>
完成此步骤后,控制台就可以接受命令。
Once done, the console is ready to accept commands.
Batch Mode
若要在批处理模式中执行命令,运行以下脚本 bin/console.sh (或在 MS Windows 系统中运行 bin/console.bat ),以分号“;”分隔传入的所有命令。
To execute commands in batch mode run the following bin/console.sh (or bin/console.bat in MS Windows systems) script passing all the commands separated with semicolon ";".
orientdb> console.bat "connect remote:localhost/demo;select * from profile"
或者调用控制台脚本,并传入文本格式的文件名,其中包含要执行的命令列表。命令必须以分号“;”分隔。
Or call the console script passing the name of the file in text format containing the list of commands to execute. Commands must be separated with semicolon ";".
Example
Command.txt 包含您想要通过 OrientDB 控制台执行的命令列表。以下命令接受 command.txt 文件中的命令批。
Command.txt contains the list of commands which you want to execute through OrientDB console. The following command accepts the batch of commands from the command.txt file.
orientdb> console.bat commands.txt
在批处理模式下,通过将“ignoreErrors”变量设置为 true,可以忽略错误,让脚本继续执行。
In batch mode, you can ignore errors to let the script continue the execution by setting the "ignoreErrors" variable to true.
orientdb> set ignoreErrors true
Enable Echo
在管道中运行控制台命令时,你需要显示它们。在开始的时候将“echo”设置为属性,即可启用“echo”命令。以下是 OrientDB 控制台中启用 echo 属性的语法。
When you run console commands in pipeline, you will need to display them. Enable "echo" of commands by setting it as property at the beginning. Following is the syntax to enable echo property in OrientDB console.
orientdb> set echo true
OrientDB - Create Database
OrientDB 数据库的 SQL 参考提供了多个命令,用于创建、修改和删除数据库。
The SQL Reference of the OrientDB database provides several commands to create, alter, and drop databases.
以下语句是 Create Database 命令的基本语法。
The following statement is a basic syntax of Create Database command.
CREATE DATABASE <database-url> [<user> <password> <storage-type> [<db-type>]]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<database-url> - 定义数据库的 URL。URL 包含两部分,一部分是 <mode>,另一部分是 <path>。
<database-url> − Defines the URL of the database. URL contains two parts, one is <mode> and the second one is <path>.
<mode> - 定义模式,即本地模式或远程模式。
<mode> − Defines the mode, i.e. local mode or remote mode.
<path> - 定义到数据库的路径。
<path> − Defines the path to the database.
<user> - 定义连接到数据库的用户。
<user> − Defines the user you want to connect to the database.
<password> - 定义用于连接到数据库的密码。
<password> − Defines the password for connecting to the database.
<storage-type> - 定义存储类型。可以在 PLOCAL 和 MEMORY 中进行选择。
<storage-type> − Defines the storage types. You can choose between PLOCAL and MEMORY.
Example
可以使用以下命令创建一个名为 demo 的本地数据库。
You can use the following command to create a local database named demo.
Orientdb> CREATE DATABASE PLOCAL:/opt/orientdb/databses/demo
如果数据库创建成功,将获得以下输出。
If the database is successfully created, you will get the following output.
Database created successfully.
Current database is: plocal: /opt/orientdb/databases/demo
orientdb {db = demo}>
OrientDB - Alter Database
数据库是一个包含不同属性的重要数据模型,可以根据自己的要求对其进行修改。
Database is a one of the important data models with different attributes that you can modify as per your requirements.
以下语句是 Alter Database 命令的基本语法。
The following statement is the basic syntax of the Alter Database command.
ALTER DATABASE <attribute-name> <attribute-value>
其中 <attribute-name> 定义要修改的属性, <attributevalue> 定义要为此属性设置的值。
Where <attribute-name> defines the attribute that you want to modify and <attributevalue> defines the value you want to set for that attribute.
下表定义了用于修改数据库的支持属性列表。
The following table defines the list of supported attributes for altering a database.
Sr.No. |
Attribute Name |
Description |
1 |
STATUS |
Defines the database’s status between different attributes. |
2 |
IMPORTING |
Sets the importing status. |
3 |
DEFAULTCLUSTERID |
Sets the default cluster using ID. By default it is 2. |
4 |
DATEFORMAT |
Sets the particular date format as default. By default it is "yyyy-MM-dd". |
5 |
DATETIMEFORMAT |
Sets the particular date time format as default. By default it is "yyyy-MM-dd HH:mm:ss". |
6 |
TIMEZONE |
Sets the particular time zone. By default it is Java Virtual Machine’s (JVM’s) default time zone. |
7 |
LOCALECOUNTRY |
Sets the default locale country. By default it is JVM’s default locale country. For example: "GB". |
8 |
LOCALELANGUAGE |
Sets the default locale language. By default it is JVM’s default locale language. For example: "en". |
9 |
CHARSET |
Sets the type of character set. By default it is JVM’s default charset. For example: "utf8". |
10 |
CLUSTERSELECTION |
Sets the default strategy used for selecting the cluster. These strategies are created along with the class creation. Supported strategies are default, roundrobin, and balanced. |
11 |
MINIMUMCLUSTERS |
Sets the minimum number of clusters to create automatically when a new class is created. By default it is 1. |
12 |
CUSTOM |
Sets the custom property. |
13 |
VALIDATION |
Disables or enables the validations for entire database. |
Example
从 OrientDB-2.2 版本开始,添加了新的 SQL 解析器,在某些情况下不允许使用常规语法。因此,在某些情况下,我们必须禁用新的 SQL 解析器 (StrictSQL)。你可以使用以下 Alter database 命令禁用 StrictSQL 解析器。
From the version of OrientDB-2.2, the new SQL parser is added which will not allow the regular syntax in some cases. Therefore, we have to disable the new SQL parser (StrictSQL) in some cases. You can use the following Alter database command to disable the StrictSQL parser.
orientdb> ALTER DATABASE custom strictSQL = false
如果命令执行成功,则会得到以下输出。
If the command is executed successfully, you will get the following output.
Database updated successfully
OrientDB - Backup Database
与 RDBMS 一样,OrientDB 也支持备份和还原操作。在执行备份操作时,它会使用 ZIP 算法将当前数据库的所有文件压缩为 zip 格式。可以通过启用 Automatic-Backup 服务器插件自动使用此功能(备份)。
Like RDBMS, OrientDB also supports the backup and restore operations. While executing the backup operation, it will take all files of the current database into a compressed zip format using the ZIP algorithm. This feature (Backup) can be availed automatically by enabling the Automatic-Backup server plugin.
备份数据库或导出数据库是相同的,但是,根据过程,我们必须知道何时使用备份以及何时使用导出。
Taking backup of a database or exporting a database is the same, however, based on the procedure we have to know when to use backup and when to use export.
在进行备份时,它将创建一个数据库的一致副本,所有进一步的写操作都会被锁定并等待完成备份过程。在此操作中,它将创建一个只读备份文件。
While taking backup, it will create a consistent copy of a database, all further write operations are locked and waiting to finish the backup process. In this operation, it will create a read-only backup file.
如果你在进行备份时需要并发读写操作,你必须选择导出数据库而不是备份数据库。导出不会锁定数据库,并在导出过程中允许并发写入。
If you need the concurrent read and write operation while taking a backup you have to choose exporting a database instead of taking backup of a database. Export doesn’t lock the database and allows concurrent writes during the export process.
以下语句是数据库备份的基本语法。
The following statement is the basic syntax of database backup.
./backup.sh <dburl> <user> <password> <destination> [<type>]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<dburl> − 位于本地或远程位置的数据库 URL,其中包含数据库。
<dburl> − The database URL where the database is located either in the local or in the remote location.
<user> − 指定运行备份的用户名。
<user> − Specifies the username to run the backup.
<password> − 提供特定用户的密码。
<password> − Provides the password for the particular user.
<destination> − 目标文件位置,指定存储备份 zip 文件的位置。
<destination> − Destination file location stating where to store the backup zip file.
<type> − 可选的备份类型。它有以下两个选项之一。
<type> − Optional backup type. It has either of the two options.
-
Default − locks the database during the backup.
-
LVM − uses LVM copy-on-write snapshot in background.
Example
备份 demo 数据库(位于 local file system /opt/orientdb/database/demo 中)到一个名为 sample-demo.zip 的文件,并将其放在当前目录中。
Take a backup of the database demo which is located in the local file system /opt/orientdb/databases/demo into a file named sample-demo.zip and located into the current directory.
你可以使用以下命令备份数据库 demo。
You can use the following command to take a backup of the database demo.
$ backup.sh plocal: opt/orientdb/database/demo admin admin ./backup-demo.zip
Using Console
你也可以使用 OrientDB 控制台完成该操作。在备份特定数据库之前,你必须首先连接到数据库。你可以使用以下命令连接到名为 demo 的数据库。
The same you can do using the OrientDB console. Before taking the backup of a particular database, you have to first connect to the database. You can use the following command to connect to the database named demo.
orientdb> CONNECT PLOCAL:/opt/orientdb/databases/demo admin admin
连接之后,你可以使用以下命令将数据库备份到当前目录中的名为“backup-demo.zip”的文件中。
After connecting you can use the following command to take backup of the database into a file named ‘backup-demo.zip’ in the current directory.
orientdb {db=demo}> BACKUP DATABASE ./backup-demo.zip
如果此命令成功执行,你将收到一些成功通知以及以下消息。
If this command is executed successfully, you will get some success notifications along with following message.
Backup executed in 0.30 seconds
OrientDB - Restore Database
与 RDBMS 一样,OrientDB 也支持还原操作。只有在控制台模式下,你才可以成功执行此操作。
As like RDBMS, OrientDB also supports restoring operation. Only from the console mode, you can execute this operation successfully.
以下语句是还原操作的基本语法。
The following statement is the basic syntax for restoring operation.
orientdb> RESTORE DATABSE <url of the backup zip file>
Example
你必须仅在控制台模式下执行此操作。因此,你首先必须使用以下 OrientDB 命令启动 OrientDB 控制台。
You have to perform this operation only from the console mode. Therefore, first you have to start the OrientDB console using the following OrientDB command.
$ orientdb
然后,连接到相应的数据库以还原备份。你可以使用以下命令连接到名为 demo 的数据库。
Then, connect to the respective database to restore the backup. You can use the following command to connect to the database named demo.
orientdb> CONNECT PLOCAL:/opt/orientdb/databases/demo admin admin
连接成功后,你可以使用以下命令从“backup-demo.zip”文件还原备份。在执行之前,请确保将 backup-demo.zip 文件放在当前目录中。
After successful connection, you can use the following command to restore the backup from ‘backup-demo.zip’ file. Before executing, make sure the backup-demo.zip file is placed in the current directory.
Orientdb {db = demo}> RESTORE DATABASE backup-demo.zip
如果此命令成功执行,你将收到一些成功通知以及以下消息。
If this command is executed successfully, you will get some success notifications along with the following message.
Database restored in 0.26 seconds
OrientDB - Connect Database
本章解释如何通过 OrientDB 命令行连接到特定数据库。它打开一个数据库。
This chapter explains how to connect to a particular database from the OrientDB command line. It opens a database.
以下是连接命令的基本语法。
The following statement is the basic syntax of the Connect command.
CONNECT <database-url> <user> <password>
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<database-url> - 定义数据库的 URL。URL 包含两部分,一是 <mode>,二是 <path>。
<database-url> − Defines the URL of the database. URL contains two parts one is <mode> and the second one is <path>.
<mode> - 定义模式,即本地模式或远程模式。
<mode> − Defines the mode, i.e. local mode or remote mode.
<path> - 定义到数据库的路径。
<path> − Defines the path to the database.
<user> - 定义连接到数据库的用户。
<user> − Defines the user you want to connect to the database.
<password> - 定义用于连接到数据库的密码。
<password> − Defines the password for connecting to the database.
Example
在之前的章节中,我们已经创建了一个名为“demo”的数据库。在此示例中,我们将使用用户管理员连接到它。
We have already created a database named ‘demo’ in the previous chapters. In this example, we will connect to that using the user admin.
可以使用以下命令连接到 demo 数据库。
You can use the following command to connect to demo database.
orientdb> CONNECT PLOCAL:/opt/orientdb/databases/demo admin admin
如果成功连接,您将获得以下输出 -
If it is successfully connected, you will get the following output −
Connecting to database [plocal:/opt/orientdb/databases/demo] with user 'admin'…OK
Orientdb {db = demo}>
OrientDB - Disconnect Database
本章介绍如何从 OrientDB 命令行断开与特定数据库的连接。它会关闭当前打开的数据库。
This chapter explains how to disconnect to a particular database from the OrientDB command line. It closes the currently open database.
以下语句是 Disconnect 命令的基本语法。
The following statement is the basic syntax of the Disconnect command.
DISCONNECT
Note − 你只能在连接到特定数据库后才能使用此命令,并且它只会关闭当前正在运行的数据库。
Note − You can use this command only after connecting to a particular database and it will only close the currently running database.
Example
在此示例中,我们将使用与前一章中创建的同名数据库“demo”。我们将断开与 demo 数据库的连接。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will disconnect from demo database.
可以使用以下命令断开数据库连接。
You can use the following command to disconnect the database.
orientdb {db = demo}> DISCONNECT
如果断开连接成功,你将收到以下输出 −
If it is successfully disconnected, you will get the following output −
Disconnecting to database [plocal:/opt/orientdb/databases/demo] with user 'admin'…OK
orientdb>
OrientDB - Info Database
本章介绍如何从 OrientDB 命令行获取特定数据库的信息。
This chapter explains how to get information of a particular database from the OrientDB command line.
以下语句是 Info 命令的基本语法。
The following statement is the basic syntax of the Info command.
info
Note - 仅在连接到特定数据库后才能使用此命令,它将仅检索当前正在运行的数据库的信息。
Note − You can use this command only after connecting to a particular database and it will retrieve the information of only the currently running database.
Example
在此示例中,我们将使用我们在上一章创建的同名数据库“demo”。我们将从 demo 数据库检索基本信息。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will retrieve the basic information from demo database.
可以使用以下命令断开数据库连接。
You can use the following command to disconnect the database.
orientdb {db = demo}> info
如果断开连接成功,您将看到以下输出。
If it is successfully disconnected, you will get the following output.
Current database: demo (url = plocal:/opt/orientdb/databases/demo)
DATABASE PROPERTIES
--------------------------------+---------------------------------------------+
NAME | VALUE |
--------------------------------+---------------------------------------------+
Name | null |
Version | 14 |
Conflict Strategy | version |
Date format | yyyy-MM-dd |
Datetime format | yyyy-MM-dd HH:mm:ss |
Timezone | Asia/Kolkata |
Locale Country | IN |
Locale Language | en |
Charset | UTF-8 |
Schema RID | #0:1 |
Index Manager RID | #0:2 |
Dictionary RID | null |
--------------------------------+---------------------------------------------+
DATABASE CUSTOM PROPERTIES:
+-------------------------------+--------------------------------------------+
| NAME | VALUE |
+-------------------------------+--------------------------------------------+
| strictSql | true |
+-------------------------------+--------------------------------------------+
CLUSTERS (collections)
---------------------------------+-------+-------------------+----------------+
NAME | ID | CONFLICT STRATEGY | RECORDS |
---------------------------------+-------+-------------------+----------------+
OrientDB - List Database
本章介绍如何从 OrientDB 命令行获取实例中所有数据库的列表。
This chapter explains how to get the list of all databases in an instance from the OrientDB command line.
以下语句是 info 命令的基本语法。
The following statement is the basic syntax of the info command.
LIST DATABASES
Note − 你只能在连接到本地或远程服务器后才能使用此命令。
Note − You can use this command only after connecting to a local or remote server.
Example
在检索数据库列表之前,我们必须通过远程服务器连接到本地主机服务器。需要提醒的是,连接到本地主机实例的用户名和密码分别是 guest 和 guest,这已在 orintdb/config/orientdb-server-config.xml 文件中配置。
Before retrieving the list of databases, we have to connect to the localhost server through the remote server. It is required to remind that the username and password for connecting to the localhost instance is guest and guest respectively, which is configured in the orintdb/config/orientdb-server-config.xml file.
可使用以下命令连接到 localhost 数据库服务器实例。
You can use the following command to connect to the localhost database server instance.
orientdb> connect remote:localhost guest
它将询问密码。根据配置文件,guest 的密码也是 guest。如果已成功连接,你将获得以下输出。
It will ask the password. As per the config file password for guest is also guest. If it is successfully connected, you will get the following output.
Connecting to remote Server instance [remote:localhost] with user 'guest'...OK
orientdb {server = remote:localhost/}>
连接到 localhost 数据库服务器后,可使用以下命令列出数据库。
After connecting to the localhost database server you can use the following command to list the databases.
orientdb {server = remote:localhost/}> list databases
如果已成功执行,你将获得以下输出:
If it is successfully executed, you will get the following output −
Found 6 databases:
* demo (plocal)
* s2 (plocal)
* s1 (plocal)
* GratefulDeadConcerts (plocal)
* s3 (plocal)
* sample (plocal)
orientdb {server = remote:localhost/}>
OrientDB - Freeze Database
每当需要使数据库状态为静态时,这意味着数据库不对任何读、写操作做出响应的状态。简单来说,数据库处于冻结状态。
Whenever you want to make the database state as static it means a state where the database didn’t respond to any of the read and write operations. Simply said, the database is in freeze state.
在本章中,你可以了解如何从 OrientDB 命令行冻结数据库。
In this chapter, you can learn how to freeze the database from the OrientDB command line.
以下语句是冻结数据库命令的基本语法。
The following statement is the basic syntax of the freeze database command.
FREEZE DATABASE
Note − 在连接到远程或本地数据库中特定数据库后,你才能使用此命令。
Note − You can use this command only after connecting to a particular database either in remote or local database.
Example
在本示例中,我们将使用上一章中创建的同名数据库“demo”。我们将从 CLI 冻结此数据库。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will freeze this database from CLI.
可使用以下命令冻结数据库。
You can use the following command to freeze the database.
Orientdb {db = demo}> FREEZE DATABASE
如果已成功执行,你将获得以下输出。
If it is successfully executed, you will get the following output.
Database 'demo' was frozen successfully
OrientDB - Release Database
在本章中,你可以了解如何通过 OrientDB 命令行使数据库从冻结状态中复原。
In this chapter, you can learn how to release the database from the freeze state through OrientDB command line.
以下语句为复原数据库命令的基本语法。
The following statement is the basic syntax of the Release database command.
RELEASE DATABASE
Note − 在连接到处于冻结状态的特定数据库后,你才能使用此命令。
Note − You can use this command only after connecting to a particular database, which is in freeze state.
Example
在本示例中,我们将使用上一章中创建的同名数据库“demo”。我们将解除上一章冻结的数据库。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will release the database that was freezed in the previous chapter.
可使用以下命令复原数据库。
You can use the following command to release the database.
Orientdb {db = demo}> RELEASE DATABASE
如果已成功执行,你将获得以下输出。
If it is successfully executed, you will get the following output.
Database 'demo' was release successfully
OrientDB - Config Database
在本章中,你可以了解如何通过 OrientDB 命令行显示特定数据库的配置。此命令适用于本地和远程数据库。
In this chapter, you can learn how to display the configuration of a particular database through OrientDB command line. This command is applicable for both local and remote databases.
配置信息包含已启用或未启用的默认缓存、该缓存的大小、负载因子值、映射的最大内存、节点页大小、池的最小和最大大小等。
Configuration information contains default cache either enabled or not, the size of that cache, the load factor value, max memory for map, node page size, pool minimum and maximum size, etc.
以下语句是 config 数据库命令的基本语法。
The following statement is the basic syntax of the config database command.
CONFIG
Note − 您只能在连接到特定数据库后才能使用此命令。
Note − You can use this command only after connecting to a particular database.
Example
在本例中,我们将使用之前章节中创建的同名数据库“demo”。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter.
您可以使用以下命令显示 demo 数据库的配置。
You can use the following command to display the configuration of demo database.
Orientdb {db = demo}> CONFIG
如果已成功执行,你将获得以下输出。
If it is successfully executed, you will get the following output.
LOCAL SERVER CONFIGURATION:
+---------------------------------------+-------------------------+
| NAME | VALUE |
+---------------------------------------+-------------------------+
| environment.dumpCfgAtStartup | false |
| environment.concurrent | true |
| environment.allowJVMShutdown | true |
| script.pool.maxSize | 20 |
| memory.useUnsafe | true |
| memory.directMemory.safeMode | true |
| memory.directMemory.trackMode | false |
|……………………………….. | |
| storage.lowestFreeListBound | 16 |
| network.binary.debug | false |
| network.http.maxLength | 1000000 |
| network.http.charset | utf-8 |
| network.http.jsonResponseError | true |
| network.http.json | false |
| tx.log.fileType | classic |
| tx.log.synch | false |
| tx.autoRetry | 1 |
| client.channel.minPool | 1 |
| storage.keepOpen | true |
| cache.local.enabled | true |
+---------------------------------------+-------------------------+
orientdb {db = demo}>
在以上列出的配置参数中,如果您希望更改任何参数值,可以直接使用命令行轻松地通过 config set 和 get 命令完成。
In the above list of configuration parameters, if you want to change any of the parameter value then you can do it from the command line easily using config set and get command.
Config Set
您可以使用命令更新配置变量的值。
You can update the configuration variable value by using the CONFIG SET command.
以下语句是 config set 命令的基本语法。
The following statement is the basic syntax of the config set command.
CONFIG SET <config-variable> <config-value>
Note − 您只能在连接到特定数据库后才能使用此命令。
Note − You can use this command only after connecting to a particular database.
Example
在本例中,我们将使用之前章节中创建的同名数据库“demo”。我们将把“tx.autoRetry”变量值修改为 5。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will modify the ‘tx.autoRetry’ variable value to 5.
您可以使用以下命令设置 demo 数据库的配置。
You can use the following command to set the configuration of demo database.
orientdb {db = demo}> CONFIG SET tx.autoRetry 5
如果已成功执行,你将获得以下输出。
If it is successfully executed, you will get the following output.
Local configuration value changed correctly
Config Get
您可以使用命令显示配置变量的值。
You can display the configuration variable value by using the CONFIG GET command.
以下语句是 config get 命令的基本语法。
The following statement is the basic syntax of the config get command.
CONFIG GET <config-variable>
Note − 您只能在连接到特定数据库后才能使用此命令。
Note − You can use this command only after connecting to a particular database.
Example
在本例中,我们将使用之前章节中创建的同名数据库“demo”。我们将尝试检索“tx.autoRetry”变量的值。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will try to retrieve the ‘tx.autoRetry’ variable value.
您可以使用以下命令显示 demo 数据库的配置。
You can use the following command to display the configuration of demo database.
orientdb {db = demo}> CONFIG GET tx.autoRetry
如果已成功执行,你将获得以下输出。
If it is successfully executed, you will get the following output.
Local configuration: tx.autoRetry = 5
OrientDB - Export Database
像 RDBMS 一样,OrientDB 也提供导出和导入数据库等功能。OrientDB 使用 JSON 格式导出数据。默认情况下,导出命令使用 GZIP 算法压缩文件。
Like RDBMS, OrientDB also provides features like Export and Import the database. OrientDB uses the JSON format to export the data. By default export command is using the GZIP algorithm to compress the files.
在导出数据库期间,它不会锁定数据库,这意味着您可以对其执行并发读写操作。这也意味着您可以创建该数据的精确副本,因为并发读写操作。
While exporting a database it is not locking the database, which means you can perform concurrent read and write operations on it. It also means that you can create an exact copy of that data because of concurrent read and write operations.
在本章中,您可以了解如何从 OrientDB 命令行导出数据库。
In this chapter, you can learn how to export the database from the OrientDB command line.
以下语句是导出数据库命令的基本语法。
The following statement is the basic syntax of the Export database command.
EXPORT DATABASE <output file>
Note − 您只能在连接到特定数据库后才能使用此命令。
Note − You can use this command only after connecting to a particular database.
Example
在本例中,我们将使用之前章节中创建的同名数据库“demo”。您可以使用以下命令将数据库导出到名为“export-demo”的文件中。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. You can use the following command to export the database to a file named ‘export-demo’.
orientdb {db = demo}> EXPORT DATABASE ./export-demo.export
如果执行成功,它将基于操作系统创建一个名为“export-demo.zip”或“exportdemo.gz”的文件,您会看到以下输出。
If it is successfully executed, it will create a file named ‘export-demo.zip’ or ‘exportdemo.gz’ based on the operating system and you will get the following output.
Exporting current database to: DATABASE /home/linuxtp/Desktop/demo.export in
GZipped JSON format ...
Started export of database 'demo' to /home/linuxtp/Desktop/demo.export.gz...
Exporting database info...OK
Exporting clusters...OK (12 clusters)
Exporting schema...OK (11 classes)
Exporting records...
- Cluster 'internal' (id = 0)...OK (records = 3/3)
- Cluster 'index' (id = 1)...OK (records = 0/0)
- Cluster 'manindex' (id = 2)...OK (records = 0/0)
- Cluster 'default' (id = 3)...OK (records = 0/0)
- Cluster 'orole' (id = 4)...OK (records = 3/3)
- Cluster 'ouser' (id = 5)...OK (records = 3/3)
- Cluster 'ofunction' (id = 6)...OK (records = 0/0)
- Cluster 'oschedule' (id = 7)...OK (records = 0/0)
- Cluster 'orids' (id = 8)...OK (records = 0/0)
- Cluster 'v' (id = 9)...OK (records = 0/0)
- Cluster 'e' (id = 10)...OK (records = 0/0)
- Cluster '_studio' (id = 11)...OK (records = 1/1)
Done. Exported 10 of total 10 records
Exporting index info...
- Index dictionary...OK
- Index OUser.name...OK
- Index ORole.name...OK
OK (3 indexes)
Exporting manual indexes content...
- Exporting index dictionary ...OK (entries = 0)
OK (1 manual indexes)
Database export completed in 377ms
OrientDB - Import Database
您需要在导入数据库时使用由导出命令生成的导出 JSON 格式文件。
Whenever you want to import the database, you must use the JSON format exported file, which is generated by export command.
在本章中,您可以了解如何从 OrientDB 命令行导入数据库。
In this chapter you can learn how to import the database from the OrientDB command line.
以下命令为导入数据库命令的基本语法。
The following statement is the basic syntax of the Import database command.
IMPORT DATABASE <input file>
Note − 您只能在连接到特定数据库后才能使用此命令。
Note − You can use this command only after connecting to a particular database.
Example
在这个例子中,我们会使用上一章建立的,叫做“demo”的相同数据库。你可以使用以下命令,把数据库导入到名为“export-demo.gz”的文件里。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. You can use the following command to import the database to a file named ‘export-demo.gz’.
orientdb {db = demo}> IMPORT DATABASE ./export-demo.export.gz
如果成功运行,你会看到以下的输出以及成功通知。
If it is successfully executed, you will get the following output along with the successful notification.
Database import completed in 11612ms
OrientDB - Commit Database
与 RDBMS 相似,OrientDB 也提供了提交和回滚等事务概念。 Commit 指关闭事务,通过将所有更改保存到数据库。 Rollback 指恢复数据库状态到打开事务时的那个点。
Similar to RDBMS, OrientDB also provides transaction concepts like Commit and Rollback. Commit refers to closing the transaction by saving all changes to the database. Rollback refers to recovering 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 −您必须在连接到特定的数据库并且开始事务之后才能使用此命令。
Note − You can use this command only after connecting to a particular database and after beginning the transaction.
Example
在这个例子中,我们会使用上一章建立的,叫做“demo”的相同数据库。我们将会看到提交事务的操作,以及通过事务储存记录。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will see the operation of commit transaction and store a record using transactions.
首先,使用以下 BEGIN 命令开始事务。
First, start the transaction using the following BEGIN command.
orientdb {db = demo}> BEGIN
然后,使用以下命令,插入一条 id = 12 且 name = satish.P 的记录到 employee 表中。
Then, 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 is successfully committed, you will get the following output.
Transaction 2 has been committed in 4ms
OrientDB - Rollback Database
在本章中,你将学会如何通过 OrientDB 命令行界面,回滚尚未提交的事务。
In this chapter, you will learn how to roll back the un-committed transaction through the OrientDB command line interface.
以下命令为回滚数据库命令的基本语法。
The following statement is the basic syntax of the Rollback database command.
ROLLBACK
Note −您必须在连接到特定的数据库并且开始事务之后才能使用此命令。
Note − You can use this command only after connecting to a particular database and after beginning the transaction.
Example
在这个例子中,我们会使用上一章建立的,叫做“demo”的相同数据库。我们将会看到回滚事务的操作,以及通过事务储存记录。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. We will see the operation of rollback transaction and store a record using transactions.
首先,使用以下 BEGIN 命令开始事务。
First, start the transaction using the following BEGIN command.
orientdb {db = demo}> BEGIN
然后,使用以下命令,插入一条 id = 12 且 name = satish.P 的记录到 employee 表中。
Then, 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')
你可以使用以下命令,从 Employee 表中检索记录。
You can use the following command to retrieve the records from the Employee table.
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 now use the following command to Rollback this transaction.
orientdb> ROLLBACK
再次检查 select 查询,来从 employee 表中检索相同的记录。
Check the select query again to retrieve the same record from the employee table.
orientdb> SELECT FROM employee WHERE name LIKE '%.P'
如果回滚成功执行,你会在输出中看到 0 条已找到的记录。
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).
OrientDB - Optimize Database
根据技术术语, Optimization 意味着“在最短的时间内,达到最好的可能性能”。参照数据库,优化包含最大化数据检索的速度和效率。
As per technical terminology Optimization means "Achieve the better possible performance in the quickest amount of time." With reference to database, optimization involves maximizing the speed and efficiency with which data is retrieved.
OrientDB 支持轻量级边,即数据实体之间的直接关系。简单来说,它是一种字段到字段的关系。OrientDB 提供了优化数据库的不同方式。它支持将常规边转换为轻量级边。
OrientDB supports lightweight edges, which means a direct relation between the data entities. In simple terms, it is a field-to-field relation. OrientDB provides different ways to optimize the database. It supports the conversion of regular edges to lightweight edges.
以下命令为优化数据库命令的基本语法。
The following statement is the basic syntax of the Optimize database command.
OPTMIZE DATABASE [-lwedges] [-noverbose]
在 lwedges 将常规节点转化为轻量级节点和 noverbose 禁用输出。
Where lwedges converts regular edges into lightweight edges and noverbose disables the output.
Example
在这个例子中,我们将使用与前一章节中创建的同名的数据库“demo”。您可以使用下列优化数据库命令。
In this example, we will use the same database named ‘demo’ that we created in the previous chapter. You can use the following optimize database command.
OPTIMIZE DATABASE -lwedges
如果成功执行,您会得到一些成功通知以及完成消息。
If it is successfully executed, you will get some successful notifications along with the completion message.
Database Optimization completed in 35ms
OrientDB - Drop Database
类似于 RDBMS,OrientDB 提供了删除数据库的功能。 Drop database 指的是彻底删除一个数据库。
Similar to RDBMS, OrientDB provides the feature to drop a database. Drop database refers to removing a database completely.
下列陈述是删除数据库命令的基本语法。
The following statement is the basic syntax of the Drop database command.
DROP DATABASE [<database-name> <server-username> <server-user-password>]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<database-name> − 您想要删除的数据库名称。
<database-name> − Database name you want to drop.
<server-username> − 拥有删除数据库权限的数据库的用户名。
<server-username> − Username of the database who has the privilege to drop a database.
<server-user-password> − 指定用户的密码。
<server-user-password> − Password of the particular user.
Example
有两种删除数据库的方法,一种是删除当前已打开的数据库,另一种是通过提供特定名称来删除特定数据库。
There are two ways to drop a database, one is drop a currently open database and second is drop a particular database by providing the particular name.
在此示例中,我们将使用此前章节中创建的同名数据库“demo”。您可以使用以下命令来删除数据库 demo 。
In this example, we will use the same database named ‘demo’ that we created in an earlier chapter. You can use the following command to drop a database demo.
orientdb {db = demo}> DROP DATABASE
如果这个命令成功执行,您将得到以下输出。
If this command is successfully executed, you will get the following output.
Database 'demo' deleted successfully
或
OR
您可以使用另一个命令来删除数据库,如下所示。
You can use another command to drop a database as follows.
orientdb> DROP DATABASE PLOCAL:/opt/orientdb/databases/demo admin admin
如果这个命令成功执行,您将得到以下输出。
If this command is successfully executed, you will get the following output.
Database 'demo' deleted successfully
OrientDB - Insert Record
OrientDB 是一个 NoSQL 数据库,可以存储文档和面向图的数据。NoSQL 数据库不包含任何表,那么您如何才能作为记录来插入数据。在此,您可以看到以类、特性、顶点和边的形式存在的表数据,这意味着类类似于表,而特性类似于文件。
OrientDB is a NoSQL database that can store the documents and graph-oriented data. NoSQL database does not contain any table, so how can you insert data as a record. Here you can see the table data in the form of class, property, vertex, and edge meaning classes are like tables, and properties are like files in the tables.
我们可以在 OrientDB 中使用 schema 来定义所有这些实体。可以将属性数据插入到一个类中。Insert 命令在数据库模式中创建一个新记录。记录可以无模式或遵循一些指定的规则。
We can define all these entities using schema in OrientDB. Property data can be inserted into a class. Insert command creates a new record in the database schema. Records can be schema-less or follow some specified rules.
以下是插入记录命令的基本语法。
The following statement is the basic syntax of the Insert Record command.
INSERT INTO [class:]<class>|cluster:<cluster>|index:<index>
[(<field>[,]*) VALUES (<expression>[,]*)[,]*]|
[SET <field> = <expression>|<sub-command>[,]*]|
[CONTENT {<JSON>}]
[RETURN <expression>]
[FROM <query>]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
SET − 为每个字段定义关联值。
SET − Defines each field along with the value.
CONTENT − 定义用于设置字段值的 JSON 数据。这是可选的。
CONTENT − Defines JSON data to set field values. This is optional.
RETURN − 定义要返回内容(而不是插入的记录数量)的表达式。最常见的用例为 −
RETURN − Defines the expression to return instead of number of records inserted. The most common use cases are −
-
@rid − Returns the Record ID of the new record.
-
@this − Returns the entire new record.
FROM – 要插入记录或结果集的位置。
FROM − Where you want to insert the record or a result set.
Example
我们考虑一个具有以下字段和类型的 Customer 表。
Let us consider a Customer table with the following fields and types.
Sr.No. |
Field Name |
Type |
1 |
Id |
Integer |
2 |
Name |
String |
3 |
Age |
Integer |
您可以通过执行以下命令来创建架构(表)。
You can create the Schema (table) by executing the following commands.
CREATE DATABASE PLOCAL:/opt/orientdb/databases/sales
CREATE CLASS Customer
CREATE PROPERTY Customer.id integer
CREATE PROPERTY Customer.name String
CREATE PROPERTY Customer.age integer
执行所有命令后,您将获得具有 id、name 和 age 字段的表名 Customer。您可以通过在 Customer 表中执行选择查询来检查表。
After executing all the commands, you will get the table name Customer with id, name, and age fields. You can check the table by executing select query into the Customer table.
OrientDB 提供了不同的方式来插入记录。考虑以下包含示例记录的 Customer 表。
OrientDB provides different ways to insert a record. Consider the following Customer table containing the sample records.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
5 |
Raja |
29 |
以下命令是将第一条记录插入 Customer 表。
The following command is to insert the first record into the Customer table.
INSERT INTO Customer (id, name, age) VALUES (01,'satish', 25)
如果上述命令已成功执行,您将获得以下输出。
If the above command is successfully executed, you will get the following output.
Inserted record 'Customer#11:0{id:1,name:satish,age:25} v1' in 0.069000 sec(s).
以下命令是将第二条记录插入 Customer 表。
The following command is to insert the second record into the Customer table.
INSERT INTO Customer SET id = 02, name = 'krishna', age = 26
如果上述命令已成功执行,您将获得以下输出。
If the above command is successfully executed, you will get the following output.
Inserted record 'Customer#11:1{id:2,age:26,name:krishna} v1' in 0.005000 sec(s).
以下命令是将第三条记录插入 Customer 表。
The following command is to insert the third record into the Customer table.
INSERT INTO Customer CONTENT {"id": "03", "name": "kiran", "age": "29"}
如果上述命令已成功执行,您将获得以下输出。
If the above command is successfully executed, you will get the following output.
Inserted record 'Customer#11:2{id:3,name:kiran,age:29} v1' in 0.004000 sec(s).
以下命令是将接下来的两条记录插入 Customer 表。
The following command is to insert the next two records into the Customer table.
INSERT INTO Customer (id, name, age) VALUES (04,'javeed', 21), (05,'raja', 29)
如果上述命令已成功执行,您将获得以下输出。
If the above command is successfully executed, you will get the following output.
Inserted record '[Customer#11:3{id:4,name:javeed,age:21} v1,
Customer#11:4{id:5,name:raja,age:29} v1]' in 0.007000 sec(s).
您可以通过执行以下命令来检查是否已插入所有这些记录。
You can check if all these records are inserted or not by executing the following command.
SELECT FROM Customer
如果上述命令已成功执行,您将获得以下输出。
If the above command is successfully executed, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:1|Customer|2 |krishna|26
2 |#11:2|Customer|3 |kiran |29
3 |#11:3|Customer|4 |javeed |21
4 |#11:4|Customer|5 |raja |29
----+-----+--------+----+-------+----
OrientDB - Display Records
类似于 RDBMS,OrientDB 支持不同的 SQL 查询类型以从数据库中检索记录。在检索记录时,我们有不同的查询变体或选项以及 select 语句。
Similar to RDBMS, OrientDB supports different types of SQL queries to retrieve the records from the database. While retrieving the records we have different variations or options of queries along with the select statement.
以下语句是 SELECT 命令的基本语法。
The following statement is the basic syntax of the SELECT command.
SELECT [ <Projections> ] [ FROM <Target> [ LET <Assignment>* ] ]
[ WHERE <Condition>* ]
[ GROUP BY <Field>* ]
[ ORDER BY <Fields>* [ ASC|DESC ] * ]
[ UNWIND <Field>* ]
[ SKIP <SkipRecords> ]
[ LIMIT <MaxRecords> ]
[ FETCHPLAN <FetchPlan> ]
[ TIMEOUT <Timeout> [ <STRATEGY> ] ]
[ LOCK default|record ]
[ PARALLEL ]
[ NOCACHE ]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<Projections> - 指示您希望从查询中提取作为结果记录集的数据。
<Projections> − Indicates the data you want to extract from the query as a result records set.
FROM - 表示要查询的对象。这可以是类、集群、单个记录 ID、记录 ID 集合。您可以将所有这些对象指定为目标。
FROM − Indicates the object to query. This can be a class, cluster, single Record ID, set of Record IDs. You can specify all these objects as target.
WHERE - 指定用于过滤结果集的条件。
WHERE − Specifies the condition to filter the result-set.
LET - 表示用于投影、条件或子查询的上下文变量。
LET − Indicates the context variable which are used in projections, conditions or sub queries.
GROUP BY - 表示用于对记录进行分组的字段。
GROUP BY − Indicates the field to group the records.
ORDER BY - 表示用于按顺序排列记录的文件。
ORDER BY − Indicates the filed to arrange a record in order.
UNWIND - 指定用于解开记录集合的字段。
UNWIND − Designates the field on which to unwind the collection of records.
SKIP - 定义从结果集开始要跳过的记录数。
SKIP − Defines the number of records you want to skip from the start of the result-set.
LIMIT - 表示结果集中记录的最大数量。
LIMIT − Indicates the maximum number of records in the result-set.
FETCHPLAN - 指定定义如何获取结果的策略。
FETCHPLAN − Specifies the strategy defining how you want to fetch results.
TIMEOUT - 定义查询的最大时间(以毫秒为单位)。
TIMEOUT − Defines the maximum time in milliseconds for the query.
LOCK - 定义锁定策略。DEFAULT 和 RECORD 是可用的锁定策略。
LOCK − Defines the locking strategy. DEFAULT and RECORD are the available lock strategies.
PARALLEL - 执行针对“x”个并发线程的查询。
PARALLEL − Executes the query against ‘x’ concurrent threads.
NOCACHE − 定义是否要使用缓存。
NOCACHE − Defines whether you want to use cache or not.
Example
让我们考虑一下上一章中创建的以下 Customer 表。
Let’s consider the following Customer table created in the previous chapter.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
5 |
Raja |
29 |
尝试不同的 select 查询以从 Customer 表中检索数据记录。
Try different select queries to retrieve the data records from the Customer table.
Method 1 − 您可以使用以下查询从 Customer 表中选择所有记录。
Method 1 − You can use the following query to select all records from the Customer table.
orientdb {db = demo}> SELECT FROM Customer
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:1|Customer|2 |krishna|26
2 |#11:2|Customer|3 |kiran |29
3 |#11:3|Customer|4 |javeed |21
4 |#11:4|Customer|5 |raja |29
----+-----+--------+----+-------+----
Method 2 − 选择所有名称以字母“ k ”开头的记录。
Method 2 − Select all records whose name starts with the letter 'k'.
orientdb {db = demo}> SELECT FROM Customer WHERE name LIKE 'k%'
或者您可以对上述示例使用以下查询。
OR you can use the following query for the above example.
orientdb {db = demo}> SELECT FROM Customer WHERE name.left(1) = 'k'
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:1|Customer|2 |krishna|26
1 |#11:2|Customer|3 |kiran |29
----+-----+--------+----+-------+----
Method 3 − 从 Customer 表中选择 id、name 记录,这些记录中的名称为大写字母。
Method 3 − Select id, name records from the Customer table with names in uppercase letters.
orientdb {db = demo}> SELECT id, name.toUpperCase() FROM Customer
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+--------+----+-------
# |@CLASS |id |name
----+--------+----+-------
0 |null |1 |SATISH
1 |null |2 |KRISHNA
2 |null |3 |KIRAN
3 |null |4 |JAVEED
4 |null |5 |RAJA
----+--------+----+-------
Method 4 − 从 Customer 表中选择所有记录,其中年龄在 25 至 29 岁之间。
Method 4 − Select all records from the Customer table where age is in the range of 25 to 29.
orientdb {db = demo}> SELECT FROM Customer WHERE age in [25,29]
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:2|Customer|3 |kiran |29
2 |#11:4|Customer|5 |raja |29
----+-----+--------+----+-------+----
Method 5 − 从 Customer 表中选择所有记录,其中任何字段都包含单词“sh”。
Method 5 − Select all records from the Customer table where any field contains the word ‘sh’.
orientdb {db = demo}> SELECT FROM Customer WHERE ANY() LIKE '%sh%'
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:1|Customer|2 |krishna|26
----+-----+--------+----+-------+----
Method 6 − 从 Customer 表中选择按年龄降序排列的所有记录。
Method 6 − Select all records from the Customer table, ordered by age in descending order.
orientdb {db = demo}> SELECT FROM Customer ORDER BY age DESC
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:2|Customer|3 |kiran |29
1 |#11:4|Customer|5 |raja |29
2 |#11:1|Customer|2 |krishna|26
3 |#11:0|Customer|1 |satish |25
4 |#11:3|Customer|4 |javeed |21
----+-----+--------+----+-------+----
OrientDB - Load Record
Load Record 用于从架构中加载特定记录。加载记录会借助记录 ID 加载记录。它在结果集中用 @rid 符号表示。
Load Record is used to load a particular record from the schema. Load record will load the record with the help of Record ID. It is represented with @rid symbol in the resultset.
以下语句是 LOAD 记录命令的基本语法。
The following statement is the basic syntax of the LOAD Record command.
LOAD RECORD <record-id>
其中 <record-id> 定义要加载的记录的记录 id。
Where <record-id> defines the record id of the record you want to load.
如果您不知道特定记录的记录 ID,则可以在表上执行任何查询。在结果集中,您会找到相应记录的记录 ID (@rid)。
If you don’t know the Record ID of a particular record, then you can execute any query against the table. In the result-set you will find the Record ID (@rid) of the respective record.
Example
我们考虑我们在前几章中使用的同一个 Customer 表。
Let us consider the same Customer table that we have used in previous chapters.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
5 |
Raja |
29 |
尝试以下查询以检索具有记录 ID @rid: #11:0 的记录。
Try the following query to retrieve the record having Record ID @rid: #11:0.
orientdb {db = demo}> LOAD RECORD #11:0
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
+---------------------------------------------------------------------------+
| Document - @class: Customer @rid: #11:0 @version: 1 |
+---------------------------------------------------------------------------+
| Name | Value |
+---------------------------------------------------------------------------+
| id | 1 |
| name | satish |
| age | 25 |
+---------------------------------------------------------------------------+
OrientDB - Reload Record
Reload Record 与加载记录命令类似,也用于从架构中加载特定记录。加载记录会借助记录 ID 加载记录。它在结果集中用 @rid 符号表示。主要区别在于重新加载记录会忽略缓存,当应用外部并发事务更改记录时,这非常有用。它会提供最新更新。
Reload Record also works similar to Load Record command and is also used to load a particular record from the schema. Load record will load the record with the help of Record ID. It is represented with @rid symbol in the result-set. The main difference is Reload record ignores the cache which is useful when external concurrent transactions is applied to change the record. It will give the latest update.
以下语句是重新加载记录命令的基本语法。
The following statement is the basic syntax of the RELOAD Record command.
RELOAD RECORD <record-id>
其中 <record-id> 定义您要重新加载的记录的记录 ID。
Where <record-id> defines the record id of the record you want to reload.
如果您不知道特定记录的记录 ID,则可以在表上执行任何查询。在结果集中,您会找到相应记录的记录 ID (@rid)。
If you don’t know the Record ID of a particular record, then you can execute any query against the table. In the result-set you will find the Record ID (@rid) of the respective record.
Example
让我们考虑我们在上一章中使用的相同的客户表。
Let us consider the same Customer table that we have used in the previous chapter.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
5 |
Raja |
29 |
尝试以下查询以检索具有记录 ID @rid: #11:0 的记录。
Try the following query to retrieve the record having Record ID @rid: #11:0.
orientdb {db = demo}> LOAD RECORD #11:0
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
+---------------------------------------------------------------------------+
| Document - @class: Customer @rid: #11:0 @version: 1 |
+---------------------------------------------------------------------------+
| Name | Value |
+---------------------------------------------------------------------------+
| id | 1 |
| name | satish |
| age | 25 |
+---------------------------------------------------------------------------+
OrientDB - Export Record
Export Record 是用于将加载的记录导出到请求和支持的格式的命令。如果您执行任何错误的语法,它都会提供支持的格式列表。OrientDB 是一系列文档数据库,因此 JSON 是默认支持的格式。
Export Record is the command used to export the loaded record into the requested and supported format. If you are executing any wrong syntax, it will give the list of supported formats. OrientDB is a family of Document database, therefore JSON is the default supported format.
以下语句是导出记录命令的基本语法。
The following statement is the basic syntax of the Export Record command.
EXPORT RECORD <format>
其中 <Format> 定义您要获取记录的格式。
Where <Format> defines the format you want to get the record.
Note - 导出命令将根据记录 ID 导出加载的记录。
Note − Export command will export the loaded record based on Record ID.
Example
让我们考虑我们在上一章中使用的相同的客户表。
Let us consider the same Customer table that we have used in the previous chapter.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
5 |
Raja |
29 |
尝试以下查询以检索具有记录 ID @rid: #11:0 的记录。
Try the following query to retrieve the record having Record ID @rid: #11:0.
orientdb {db = demo}> LOAD RECORD #11:0
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
+---------------------------------------------------------------------------+
| Document - @class: Customer @rid: #11:0 @version: 1 |
+---------------------------------------------------------------------------+
| Name | Value |
+---------------------------------------------------------------------------+
| id | 1 |
| name | satish |
| age | 25 |
+---------------------------------------------------------------------------+
使用以下查询以 JSON 格式导出加载的记录 (#11:0)。
Use the following query to export he loaded record (#11:0) into JSON format.
orientdb {db = demo}> EXPORT RECORD json
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
{
"@type": "d",
"@rid": "#11:0",
"@version": 1,
"@class": "Customer",
"id": 1,
"name": "satish",
"age": 25
}
OrientDB - Update Record
Update Record 命令用来修改某个特定记录的值。SET 是更新某个特定字段值的基本命令。
Update Record command is used to modify the value of a particular record. SET is the basic command to update a particular field value.
以下语句是更新命令的基本语法。
The following statement is the basic syntax of the Update command.
UPDATE <class>|cluster:<cluster>|<recordID>
[SET|INCREMENT|ADD|REMOVE|PUT <field-name> = <field-value>[,]*] |[CONTENT| MERGE <JSON>]
[UPSERT]
[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.
SET - 定义要更新的字段。
SET − Defines the field to update.
INCREMENT - 通过给定值递增指定字段值。
INCREMENT − Increments the specified field value by the given value.
ADD - 在集合字段中添加新项。
ADD − Adds the new item in the collection fields.
REMOVE - 从集合字段中移除一项。
REMOVE − Removes an item from the collection field.
PUT - 向映射字段中输入一项。
PUT − Puts an entry into map field.
CONTENT - 用 JSON 文档内容替换记录内容。
CONTENT − Replaces the record content with JSON document content.
MERGE - 用 JSON 文档合并记录内容。
MERGE − Merges the record content with a JSON document.
LOCK - 指定如何在加载和更新之间锁定记录。我们有两个选项来指定 Default 和 Record 。
LOCK − Specifies how to lock the records between load and update. We have two options to specify Default and Record.
UPSERT - 如果记录存在则更新,如果不存在则插入新记录。它有助于执行单个查询来代替执行两个查询。
UPSERT − Updates a record if it exists or inserts a new record if it doesn’t. It helps in executing a single query in the place of executing two queries.
RETURN − 指定要在记录数量中返回的表达式。
RETURN − Specifies an expression to return instead of the number of records.
LIMIT − 定义要更新的最大记录数量。
LIMIT − Defines the maximum number of records to update.
TIMEOUT − 定义在超时前允许更新运行的时间。
TIMEOUT − Defines the time you want to allow the update run before it times out.
Example
让我们考虑我们在上一章中使用的相同的客户表。
Let us consider the same Customer table that we have used in the previous chapter.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
5 |
Raja |
29 |
尝试使用以下查询以更新名为“Raja”的客户的年龄。
Try the following query to update the age of a customer ‘Raja’.
Orientdb {db = demo}> UPDATE Customer SET age = 28 WHERE name = 'Raja'
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Updated 1 record(s) in 0.008000 sec(s).
要检查客户表中的记录,可以使用以下查询。
To check the record of Customer table you can use the following query.
orientdb {db = demo}> SELECT FROM Customer
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:1|Customer|2 |krishna|26
2 |#11:2|Customer|3 |kiran |29
3 |#11:3|Customer|4 |javeed |21
4 |#11:4|Customer|5 |raja |28
----+-----+--------+----+-------+----
OrientDB - Truncate Record
Truncate Record 命令用于删除特定记录的值。
Truncate Record command is used to delete the values of a particular record.
以下语句是截断命令的基本语法。
The following statement is the basic syntax of the Truncate command.
TRUNCATE RECORD <rid>*
其中 <rid> * 表示要截断的记录 ID。可以使用多个 Rids 并用逗号分隔它们来截断多个记录。它返回截断的记录数。
Where <rid>* indicates the Record ID to truncate. You can use multiple Rids separated by comma to truncate multiple records. It returns the number of records truncated.
Example
让我们考虑我们在上一章中使用的相同的客户表。
Let us consider the same Customer table that we have used in the previous chapter.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
5 |
Raja |
28 |
尝试使用以下查询来截断记录 ID 为 #11:4 的记录。
Try the following query to truncate the record having Record ID #11:4.
Orientdb {db = demo}> TRUNCATE RECORD #11:4
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Truncated 1 record(s) in 0.008000 sec(s).
要检查客户表中的记录,可以使用以下查询。
To check the record of Customer table you can use the following query.
Orientdb {db = demo}> SELECT FROM Customer
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:1|Customer|2 |krishna|26
2 |#11:2|Customer|3 |kiran |29
3 |#11:3|Customer|4 |javeed |21
----+-----+--------+----+-------+----
OrientDB - Delete Record
Delete Record 命令用于从数据库中完全删除一个或多个记录。
Delete Record command is used to delete one or more records completely from the database.
以下语句是删除命令的基本语法。
The following statement is the basic syntax of the Delete command.
DELETE FROM <Class>|cluster:<cluster>|index:<index>
[LOCK <default|record>]
[RETURN <returning>]
[WHERE <Condition>*]
[LIMIT <MaxRecords>]
[TIMEOUT <timeout>]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
LOCK - 指定如何在加载和更新之间锁定记录。我们有两个选项来指定 Default 和 Record 。
LOCK − Specifies how to lock the records between load and update. We have two options to specify Default and Record.
RETURN − 指定要在记录数量中返回的表达式。
RETURN − Specifies an expression to return instead of the number of records.
LIMIT − 定义要更新的最大记录数量。
LIMIT − Defines the maximum number of records to update.
TIMEOUT − 定义在超时前允许更新运行的时间。
TIMEOUT − Defines the time you want to allow the update run before it times out.
Note − 不要使用 DELETE 删除点或边,因为它会影响图表的完整性。
Note − Don’t use DELETE to remove Vertices or Edges because it effects the integrity of the graph.
Example
我们以客户表为例。
Let us consider the Customer table.
Sr.No. |
Name |
Age |
1 |
Satish |
25 |
2 |
Krishna |
26 |
3 |
Kiran |
29 |
4 |
Javeed |
21 |
尝试使用以下查询来删除 id = 4 的记录。
Try the following query to delete the record having id = 4.
orientdb {db = demo}> DELETE FROM Customer WHERE id = 4
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Delete 1 record(s) in 0.008000 sec(s).
要检查客户表中的记录,可以使用以下查询。
To check the record of Customer table you can use the following query.
Orientdb {db = demo}> SELECT FROM Customer
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
----+-----+--------+----+-------+----
# |@RID |@CLASS |id |name |age
----+-----+--------+----+-------+----
0 |#11:0|Customer|1 |satish |25
1 |#11:1|Customer|2 |krishna|26
2 |#11:2|Customer|3 |kiran |29
----+-----+--------+----+-------+----
OrientDB - Create Class
OrientDB 支持多模型功能,并提供不同的方法来理解和了解数据库的基本概念。然而,我们可以轻松访问这些模型,从文档数据库 API 的角度来看。与 RDBMS 类似,OrientDB 也使用 Record 作为存储元素,但它使用 Document 类型。文档以键值对的形式存储。我们将字段和属性存储为属于概念类的键值对。
OrientDB supports multi-model feature and provides different ways in approaching and understanding the basic concepts of a database. However, we can easily access these models from the perspective of Document database API. Like RDBMS, OrientDB also uses the Record as an element of storage but it uses the Document type. Documents are stored in the form of Key/Value pairs. We are storing fields and properties as key/value pairs which belong to a concepts class.
Class 是一种数据模型,这种概念取自面向对象编程模式。基于传统的文档数据库模型,数据以集合的形式存储,而在关系数据库模型中,数据存储在表中。OrientDB 遵循文档 API 和 OPPS 模式。作为一个概念,OrientDB 中的类与关系数据库中的表有最密切的关系,但是(与表不同)类可以无模式、全模式或混合。类可以从其他类继承,创建类树。每个类都有自己的集群或多个集群(如果未定义,则默认创建)。
Class is a type of data model and the concept is drawn from the Object-oriented programming paradigm. Based on the traditional document database model, data is stored in the form of collection, while in the relational database model data it is stored in tables. OrientDB follows the Document API along with OPPS paradigm. As a concept, class in OrientDB has the closest relationship with the table in relational databases, but (unlike tables) classes can be schema-less, schema-full or mixed. Classes can inherit from other classes, creating trees of classes. Each class has its own cluster or clusters, (created by default, if none are defined).
以下语句是 Create Class Command 的基本语法。
The following statement is the basic syntax of the Create Class Command.
CREATE CLASS <class>
[EXTENDS <super-class>]
[CLUSTER <cluster-id>*]
[CLUSTERS <total-cluster-number>]
[ABSTRACT]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<class> − 定义要创建的类的名称。
<class> − Defines the name of the class you want to create.
<super-class> − 定义要使用此类扩展的超类。
<super-class> − Defines the super-class you want to extend with this class.
<total-cluster-number> − 定义此类中使用的集群总数。默认值为 1。
<total-cluster-number> − Defines the total number of clusters used in this class. Default is 1.
ABSTARCT − 定义类是抽象的。此为可选。
ABSTARCT − Defines the class is abstract. This is optional.
Example
如前所述,类是一个与表相关的概念。因此,这里我们将创建一个表 Account。但是,在创建类时,我们无法定义字段,即基于 OOPS 模式的属性。
As discussed, class is a concept related to table. Therefore here we will create a table Account. However, while creating class we cannot define fields i.e., properties based on OOPS paradigm.
以下命令用于创建一个名为 Account 的类。
The following command is to create a class named Account.
orientdb> CREATE CLASS Account
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Class created successfully
您可以使用以下命令来创建一个 Car 类,该类扩展至 Vehicle 类。
You can use the following command to create a class Car which extends to class Vehicle.
orientdb> CREATE CLASS Car EXTENDS Vehicle
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Class created successfully
您可以使用以下命令来创建一个抽象 Person 类。
You can use the following command to create a class Person as abstract.
orientdb> CREATE CLASS Person ABSTRACT
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Class created successfully
Note − 在没有属性的情况下,该类是无用的并且无法构建实际对象。在后面的章节中,您可以学习如何为特定类创建属性。
Note − Without having properties, the class is useless and unable to build real object. In the further chapters, you can learn how to create properties for a particular class.
OrientDB - Alter Class
OrientDB 中的类和属性用于构建架构,其中包含不同的属性,例如类名、超类、集群、集群数、抽象等。如果您想修改或更新架构中现有类的任何属性,则必须使用 Alter Class 命令。
Class and Property in OrientDB are used to build a schema with the respective attributes such as class name, super-class, cluster, number of clusters, Abstract, etc. If you want to modify or update any attribute of existing classes in the schema then you have to use Alter Class command.
以下语句是 Alter Class 命令的基本语法。
The following statement is the basic syntax of the Alter Class Command.
ALTER CLASS <class> <attribute-name> <attribute-value>
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<class> − 定义类名。
<class> − Defines the class name.
<attribute-name> − 定义您想要更改的属性。
<attribute-name> − Defines the attribute you want to change.
<attribute-value> − 定义想要为该属性设置的值。
<attribute-value> − Defines the value you want to set for the attribute.
下表定义了支持 Alter Class 命令的属性列表。
The following table defines the list of attributes that support Alter Class command.
Attribute |
Type |
Description |
NAME |
String |
Changes the class name. |
SHORTNAME |
String |
Defines a short name, (that is, an alias), for the class. Use NULL to remove a short name assignment. |
SUPERCLASS |
String |
Defines a super-class for the class. To add a new class, you can use the syntax +<class>, to remove it use -<class>. |
OVERSIZE |
Decimal number |
Defines the oversize factor. |
ADDCLUSTER |
String |
Adds a cluster to the class. If the cluster doesn’t exist, it creates a physical cluster. Adding clusters to a class is also useful in storing records in distributed servers. |
REMOVECLUSTER |
String |
Removes a cluster from a class. It does not delete the cluster, only removes it from the class. |
STRICTMODE |
- |
Enables or disables strict mode. When in strict mode, you work in schema-full mode and cannot add new properties to a record if they are part of the class' schema definition. |
CLUSTERSELECTION |
- |
Defines the selection strategy in choosing which cluster it uses for new records. |
CUSTOM |
- |
Defines custom properties. Property names and values must follow the syntax <propertyname>=<value> without spaces between the name and value. |
ABSTRACT |
Boolean |
Converts class to an abstract class or the opposite. |
Example
让我们尝试一些将更新或修改现有类的属性的示例。
Let us try few examples that will update or modify the attributes of the existing class.
以下查询用于为现有类“Employee”定义超类“Person”。
The following query is used to define a super-class ‘Person’ for an existing class ‘Employee’.
orientdb> ALTER CLASS Employee SUPERCLASS Person
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Class altered successfully
以下查询用于为现有类“Employee”添加超类“Person”。
The following query is used to add a super-class ‘Person’ for an existing class ‘Employee’.
orientdb> ALTER CLASS Employee SUPERCLASS +Person
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Class altered successfully
OrientDB - Truncate Class
Truncate class 将删除作为类一部分定义的群集的所有记录。在 OrientDB 中,每个类都有一个关联的群集,名称相同。如果您还想要从类层次结构中删除所有记录,您需要使用 POLYMORPHIC 关键字。
Truncate class will delete all records of clusters defined as part of class. In OrientDB, every class has an associated cluster with the same name. If you want to also remove all records from the class hierarchy, you need to use the POLYMORPHIC keyword.
以下是 Truncate Class 命令的基本语法。
The following statement is the basic syntax of Truncate Class Command.
TRUNCATE CLASS <class> [ POLYMORPHIC ] [ UNSAFE ]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<class> −定义您想要截断的类。
<class> − Defines the class you want to truncate.
POLYMORPHIC −定义此命令是否还截断了层次结构。
POLYMORPHIC − Defines whether the command also truncates the hierarchy.
UNSAFE - 定义了命令强制对顶点或边类执行截断。
UNSAFE − Defines the command forces truncation on vertex or edge class.
OrientDB - Drop Class
Drop Class 命令从模式中删除一个类。注意并维护一个一致的模式非常重要。例如,避免删除其他类的超类。关联的集群不会被删除。
The Drop Class command removes a class from the schema. It is important to pay attention and maintain a consistent schema. For example, avoid to remove classes that are super-classes of others. The associated cluster won’t be deleted.
以下是 Drop Class 命令的基本语法。
The following statement is the basic syntax of Drop Class command.
DROP CLASS <class>
通过类名称删除一个类。
Drop a class with the class name.
OrientDB - Create Cluster
Cluster 是 OrientDB 中的一个重要概念,用于存储记录、文档或顶点。简单来说,集群是一个存储一组记录的地方。默认情况下,OrientDB 将为每个类创建一个集群。某个类的所有记录都存储在同一个集群中,该集群具有与该类相同名称。可以在数据库中创建多达 32767(2^15-1)个集群。
Cluster is an important concept in OrientDB which is used to store records, documents, or vertices. In simple words, cluster is a place where a group of records are stored. By default, OrientDB will create one cluster per class. All the records of a class are stored in the same cluster, which has the same name as the class. You can create up to 32,767(2^15-1) clusters in a database.
CREATE class 是一个用于创建特定名称集群的命令。创建集群后,您可以在创建任何数据模型期间指定名称,使用集群来保存记录。如果您想向类中添加一个新集群,请使用 Alter Class 命令和 ADDCLUSTER 命令。
The CREATE class is a command used to create a cluster with a specific name. Once the cluster is created, you can use the cluster to save records by specifying the name during the creation of any data model. If you want to add a new cluster to a class, use Alter Class command and ADDCLUSTER command.
以下语句是 Create Cluster 命令的基本语法。
The following statement is the basic syntax of Create Cluster command.
CREATE CLUSTER <cluster> [ID <cluster-id>]
其中 <cluster> 定义所要创建的集群的名称, <cluster-id> 定义所要用于该集群的数字 ID。
Where <cluster> defines the name of the cluster you want to create and <cluster-id> defines the numeric ID you want to use for the cluster.
下表提供了集群选取策略列表。
The following table provides the list of Cluster selection strategies.
Sr.No. |
Strategy & Description |
1 |
Default Selects the cluster using the class property default ClusterId. |
2 |
Round-robin Selects the next cluster in a circular order. It is restarting once complete. |
3 |
Balanced Selects the smallest cluster. Allows the class to have all underlying clusters balanced on size. When adding a new cluster to an existing class, it fills the new cluster first. |
OrientDB - Alter Cluster
Alter Cluster 命令用于更新现有集群上的属性。在本部分中,您可以了解如何添加或修改集群的属性。
Alter Cluster command is to update attributes on an existing cluster. In this chapter you can learn how to add or modify the attributes of a cluster.
以下语句是 Alter Cluster 命令的基本语法。
The following statement is the basic syntax of Alter Cluster command.
ALTER CLUSTER <cluster> <attribute-name> <attribute-value>
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<cluster> − 定义集群名称。
<cluster> − Defines the cluster name.
<attribute-name> − 定义您想要更改的属性。
<attribute-name> − Defines the attribute you want to change.
<attribute-value> − 定义所要为该属性设置的值。
<attribute-value> − Defines the value you want to set for this attribute.
以下表格格式提供了您可与 Alter cluster 命令一起使用的受支持属性列表。
The following tabular format provides the list of supported attributes you can use along with Alter cluster command.
Name |
Type |
Description |
NAME |
String |
Changes the cluster name. |
STATUS |
String |
Changes the cluster status. Allowed values are ONLINE and OFFLINE. By default, clusters are online. |
COMPRESSION |
String |
Defines the compression type to use. Allowed values are NOTHING, SNAPPY, GZIP, and any other compression types registered in the OCompressionFactory class. |
USE_WAL |
Boolean |
Defines whether it uses the Journal when OrientDB operates against the cluster |
RECORD_GROW_FACTO R |
Integer |
Defines the grow factor to save more space on record creation. You may find this useful when you update the record with additional information. |
RECORD_OVERFLOW_GR OW_FACTOR |
Integer |
Defines grow factor on updates. When it reaches the size limit, is uses this setting to get more space, (factor > 1). |
CONFLICTSTRATEGY |
String |
Defines the strategy it uses to handle conflicts in the event that OrientDB MVCC finds an update or a delete operation it executes against an old record. |
下表提供了冲突策略列表。
The following table provides the list of Conflict strategies.
Sr.No. |
Strategy & Description |
1 |
Version Throws an exception when versions are different. This is the default setting. |
2 |
Content In the event that the versions are different, it checks for changes in the content, otherwise it uses the highest version to avoid throwing an exception. |
3 |
Automerge Merges the changes. |
Example
尝试以下示例查询以学习 Alter cluster 命令。
Try the following example queries to learn Alter cluster command.
执行以下命令以将群集名称从 Employee 更改为 Employee2。
Execute the following command to change the name of a cluster from Employee to Employee2.
orientdb {db = demo}> ALTER CLUSTER Employee NAME Employee2
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Cluster updated successfully
执行以下命令以使用群集 ID 将群集名称从 Employee2 更改为 Employee。
Execute the following command to change the name of a cluster from Employee2 to Employee using cluster ID.
orientdb {db = demo}> ALTER CLUSTER 12 NAME Employee
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Cluster updated successfully
执行以下命令以将群集冲突策略更改为自动合并。
Execute the following command to change the cluster conflict strategy to automerge.
orientdb {db = demo}> ALTER CLUSTER V CONFICTSTRATEGY automerge
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Cluster updated successfully
OrientDB - Truncate Cluster
Truncate Cluster 命令将删除群集的所有记录。
The Truncate Cluster command deletes all records of a cluster.
以下语句是 Truncate Cluster 命令的基本语法。
The following statement is the basic syntax of Truncate Cluster Command.
TRUNCATE CLUSTER <cluster-name>
其中 <cluster-name> 是群集的名称。
Where <cluster-name> is the name of the cluster.
OrientDB - Drop Cluster
Drop Cluster 命令将删除群集及其所有相关内容。此操作是永久性的并回滚。
The Drop Cluster command removes the cluster and all its related content. This operation is permanent and rollback.
以下语句是 Drop Cluster 命令的基本语法。
The following statement is the basic syntax of Drop Cluster command.
DROP CLUSTER <cluster-name>|<cluster-id>
其中 <cluster-name> 定义要删除的群集的名称, <cluster-id> 定义要删除的群集的 ID。
Where <cluster-name> defines the name of the cluster you want to remove and <cluster-id> defines the ID of the cluster you want to remove.
OrientDB - Create Property
OrientDB 中的 Property 类似于数据库表中的类字段和列。创建属性是一个用于为特定类创建属性的命令。您在命令中使用的类名称必须存在。
Property in OrientDB works like a field of class and column in the database table. Create Property is a command used to create a property for a particular class. The class name that you used in the command must exist.
以下语句是 Create Property 命令的基本语法。
The following statement is the basic syntax of Create Property command.
CREATE PROPERTY <class-name>.<property-name> <property-type> [<linked-type>][ <linked-class>]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<class-name> − 定义要为其创建属性的类。
<class-name> − Defines the class you want to create the property in.
<property-name> − 定义属性的逻辑名称。
<property-name> − Defines the logical name of the property.
<property-type> − 定义要创建的属性类型。
<property-type> − Defines the type of property you want to create.
<linked-type> − 定义容器类型,用于容器属性类型。
<linked-type> − Defines the container type, used in container property type.
<linked-class> − 定义容器类,用于容器属性类型。
<linked-class> − Defines the container class, used in container property type.
下表为属性提供数据类型,以便 OrientDB 知道要存储的数据类型。
The following table provides the data type for property so that OrientDB knows the type of data to store.
BOOLEAN |
INTEGER |
SHORT |
LONG |
FLOAT |
DATE |
STRING |
EMBEDDED |
LINK |
BYTE |
BINARY |
DOUBLE |
除了这些之外,还有几个其他作为容器的属性类型。
In addition to these there are several other property types that work as containers.
EMBEDDEDLIST |
EMBEDDEDSET |
EMBEDDEDMAP |
LINKLIST |
LINKSET |
LINKMAP |
Example
尝试使用以下示例在类型为 String 的类 Employee 上创建属性名称。
Try the following example to create a property name on the class Employee, of the String type.
orientdb> CREATE PROPERTY Employee.name STRING
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Property created successfully with id = 1
OrientDB - Alter Property
Alter Property 是用来修改或更新特定类的属性的命令。更改属性表示修改表中的字段。在本章中,你可以了解如何更新属性。
Alter Property is a command used to modify or update the Property of a particular class. Altering the property means modifying the fields of a table. In this chapter, you can learn how to update the property.
以下语句是 Alter Property 命令的基本语法。
The following statement is the basic syntax of Alter Property Command.
ALTER PROPERTY <class>.<property> <attribute-name> <attribute-value>
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<class> − 定义属性所属的类。
<class> − Defines the class to which the property belongs.
<property> − 定义要更新的属性。
<property> − Defines the property you want to update.
<attribute-name> − 定义要更新的属性的属性。
<attribute-name> − Defines the attribute of a property you want to update.
<attribute-value> − 定义要设置在属性上的值。
<attribute-value> − Defines the value you want to set on the attribute.
下表定义了用于更改属性的属性列表。
The following table defines the list of attributes to alter the property.
Attribute |
Type |
Description |
LINKEDCLASS |
String |
Defines the linked class name. Use NULL to remove an existing value. |
LINKEDTYPE |
String |
Defines the link type. Use NULL to remove an existing value. |
MIN |
Integer |
Defines the minimum value as a constraint. Use NULL to remove an existing constraint. |
MANDATORY |
Boolean |
Defines whether the property requires a value. |
MAX |
Integer |
Defines the maximum value as a constraint. Use NULL to remove an existing constraint. |
NAME |
String |
Defines the property name. |
NOTNULL |
Boolean |
Defines whether the property can have a NULL value. |
REGEX |
String |
Defines a Regular Expression as constraint. Use NULL to remove an existing constraint. |
TYPE |
String |
Defines a property type. |
COLLATE |
String |
Sets collate to one of the defined comparison strategies. By default, it is set to case-sensitive (cs). You can also set it to case-insensitive (ci). |
READONLY |
Boolean |
Defines whether the property value is immutable. That is, if it is possible to change it after the first assignment. Use with DEFAULT to have immutable values on creation. |
CUSTOM |
String |
Defines custom properties. The syntax for custom properties is <custom-name> = <custom-value>, such as stereotype = icon. |
DEFAULT |
Defines the default value or function. |
Note - 如果要更改 NAME 或 TYPE,则此命令将根据数据量花费一些时间进行更新。
Note − if you are altering NAME or TYPE, this command will take some time to update depending on the amount of data.
Example
尝试一些下面给出的查询来理解 Alter 属性。
Try some queries which are given below to understand Alter property.
执行以下查询,将 Customer 类中属性的名称从“age”更改为“born”。
Execute the following query to change the name of the property from ‘age’ to ‘born’ in the class Customer.
orinetdb {db = demo}> ALTER PROPERTY Customer.age NAME born
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Property altered successfully
执行以下查询,将“name”设为类“Customer”的强制属性。
Execute the following query to make ‘name’ as the mandatory property of the class ‘Customer’.
orientdb {db = demo}> ALTER PROPERTY Customer.name MANDATORY TRUE
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Property altered successfully
OrientDB - Drop Property
Drop property 命令从模式中删除属性。它不会从记录中删除属性值,只会更改模式。
The Drop property command removes the property from the schema. It does not remove the property values from the record, it just change the schema.
以下语句是 Drop Property 命令的基本语法。
The following statement is the basic syntax of Drop Property Command.
DROP PROPERTY <class>.<property> [FORCE]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<class> - 定义属性所在类。
<class> − Defines the class where the property exists.
<property> - 定义要删除的属性。
<property> − Defines the property you want to remove.
[Force] - 如果在属性上定义了一个或多个索引。
[Force] − In case one or more indexes are defined on the property.
OrientDB - Create Vertex
OrientDB 数据库不仅是文档数据库,还是图形数据库。新概念(如顶点和边)用于以图形形式存储数据。它对顶点应用多态性。顶点的基类是 V。
OrientDB database is not only a Document database but also a Graph database. New concepts such as Vertex and Edge are used to store the data in the form of graph. It applies polymorphism on vertices. The base class for Vertex is V.
在本教程中,您可以了解如何创建顶点来存储图形数据。
In this chapter you can learn how to create vertex to store graph data.
以下是 Create Vertex Command 的基本语法。
The following statement is the basic syntax of Create Vertex Command.
CREATE VERTEX [<class>] [CLUSTER <cluster>] [SET <field> = <expression>[,]*]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<class> − 定义顶点所属的类。
<class> − Defines the class to which the vertex belongs.
<cluster> −定义存储顶点的群集。
<cluster> − Defines the cluster in which it stores the vertex.
<field> −定义希望设置的字段。
<field> − Defines the field you want to set.
<expression> −定义要为该字段设置的表达式。
<expression> − Defines the express to set for the field.
Example
尝试以下示例来了解如何创建顶点。
Try the following example to understand how to create vertex.
执行以下查询来创建不带“name”且在基本类 V 上的顶点。
Execute the following query to create a vertex without ‘name’ and on the base class V.
orientdb> CREATE VERTEX
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Created vertex 'V#9:0 v1' in 0.118000 sec(s)
执行以下查询创建一个名为 v1 的新顶点类,然后在该类中创建顶点。
Execute the following query to create a new vertex class named v1, then create vertex in that class.
orientdb> CREATE CLASS V1 EXTENDS V
orientdb> CREATE VERTEX V1
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Created vertex 'V1#14:0 v1' in 0.004000 sec(s)
执行以下查询创建一个名为 v1 的类的新顶点,定义其属性,例如 brand = 'Maruti' 和 name = 'Swift'。
Execute the following query to create a new vertex of the class named v1, defining its properties such as brand = 'Maruti' and name = 'Swift'.
orientdb> CREATE VERTEX V1 SET brand = 'maruti', name = 'swift'
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Created vertex 'V1#14:1{brand:maruti,name:swift} v1' in 0.004000 sec(s)
OrientDB - Move Vertex
OrientDB 中的移动顶点命令是将一个或多个顶点从当前位置移动到不同的类或集群。如果你将移动命令应用于特定顶点,则它将更新连接到此顶点的所有边。如果你指定一个集群来移动顶点,则它会将顶点移动到目标集群的所有者服务器。
Move Vertex command in OrientDB is to move one or more vertices from current location to different class or cluster. If you are applying move command on a particular vertex, then it will update all the edges that are connected to this vertex. If you are specifying a cluster to move vertex, then it moves the vertices to the server owner of the target cluster.
以下语句是 Move Vertex 命令的基本语法。
The following statement is the basic syntax of Move Vertex Command.
MOVE VERTEX <source> TO <destination>
[SET [<field>=<value>]* [,]]
[MERGE <JSON>]
[BATCH <batch-size>]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<source> - 定义要移动的顶点。它接受特定顶点的记录 ID 或顶点的记录 ID 数组。
<source> − Defines the vertex you want to move. It accepts Record ID of a particular vertex or array of Record IDs for vertices.
<destination> - 定义要将顶点移动到哪里。它将类或集群作为目的地。
<destination> − Defines where you want to move the vertex. It supports either class or a cluster as destination.
SET - 向字段设置值。
SET − Sets the values to fields.
MERGE − 通过 JSON 设置字段的值。
MERGE − Sets the values to fields through JSON.
BATCH − 定义批处理大小。
BATCH − Defines the batch size.
Note − 此命令更新所有已连接的边,但不更新链接。在使用图 API 时,建议使用连到顶点的边。
Note − This command updates all connected edges, but not links. When using Graph API, it is recommended to use edge connected to vertices.
Example
尝试以下示例来了解如何移动顶点。
Try the following examples to learn how to move vertices.
执行以下查询,将记录 ID 为 #11:2 的单个顶点从当前位置移到员工类别。
Execute the following query to move a single vertex having Record ID #11:2 from its current position to Class Employee.
orientdb> MOVE VERTEX #11:2 TO CLASS:Employee
如果以上查询执行成功,您将获得以下输出 −
If the above query is executed successfully, you will get the following output −
Move vertex command executed with result '[{old:#11:2, new:#13:0}]' in 0.022000 sec(s)
执行以下查询,将一组顶点从“客户”类别移到“员工”类别。
Execute the following query to move set of vertices from the class ‘Customer’ to class ‘Employee’.
orientdb> MOVE VERTEX (SELECT FROM Customer) TO CLASS:Employee
如果成功执行了以上查询,您会获得以下输出。
If the above query is executed successfully, you will get the following output.
Move vertex command executed with result '[{old:#11:0,
new:#13:1},{old:#11:1, new:#13:2},{old:#11:2, new:#13:3}]' in 0.011000 sec(s)
OrientDB - Delete Vertex
Delete Vertex 命令用于从数据库中删除顶点。在删除时,它将检查并维护与边的连贯性,并删除指向已删除顶点的所有交叉引用(与边)。
Delete Vertex command is used to remove vertices from the database. While deleting, it checks and maintains the consistency with the edges and removes all cross-references (with the edges) to the deleted vertex.
以下语句是删除顶点命令的基本语法。
The following statement is the basic syntax of Delete Vertex Command.
DELETE VERTEX <vertex> [WHERE <conditions>]
[LIMIT <MaxRecords>>] [BATCH <batch-size>]
以下是上文中选项的详细信息。
Following are the details about the options in the above syntax.
<vertex> - 使用类、记录 ID 或子查询定义要删除的顶点。
<vertex> − Defines the vertex that you want to remove, using its Class, Record ID, or through a sub-query.
WHERE - 过滤条件,用于确定命令删除哪些记录。
WHERE − Filters condition to determine which records the command removes.
LIMIT - 定义要删除的最大记录数。
LIMIT − Defines the maximum number of records to be removed.
BATCH - 定义命令一次删除多少条记录,允许将大事务分解成小块,以节省内存使用量。
BATCH − Defines how many records the command removes at a time, allowing you to break large transactions into smaller blocks to save on memory usage.
Example
试试以下命令来学习如何删除单个顶点或多个顶点。
Try the following command to learn how to delete single vertex or multiple vertices.
执行以下命令,删除顶点 ‘#14:1’。
Execute the following command to remove the vertex ‘#14:1’.
orientdb> DELETE VERTEX #14:1
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Delete record(s) '1' in 0.005000 sec(s)
执行以下命令,删除所有标记为 ‘isSpam’ 属性的类 ‘Customer’ 中的顶点。
Execute the following command to remove all vertices from the class ‘Customer’ marked with the property ‘isSpam’.
orientdb> DELETE VERTEX Customer WHERE isSpam = TRUE
如果上述命令执行成功,您将获得以下输出内容。
If the above command is executed successfully, you will get the following output.
Delete record(s) '3' in 0.005000 sec(s)
OrientDB - Create Edge
在 OrientDB 中, Edge 概念的作用是借助一些属性在顶点之间建立关系。边和顶点是图数据库的主要组成部分。它对边运用多态。边的基类是 E。在实现边时,如果源顶点或目标顶点缺失或不存在,则将回滚该事务。
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> − 定义边的类名。
<class> − Defines the class name for the edge.
<cluster> − 定义用于存储边的集群。
<cluster> − Defines the cluster in which you want to store the edge.
JSON − 提供要设置为记录的 JSON 内容。
JSON − Provides JSON content to set as the record.
RETRY − 定义在发生冲突时尝试的重试次数。
RETRY − Defines the number of retries to attempt in the event of conflict.
WAIT − 定义重试之间以毫秒为单位的延迟时间。
WAIT − Defines the time to delay between retries in milliseconds.
BATCH − 定义它是否将命令分解为较小的块以及批处理的大小。
BATCH − Defines whether it breaks the command down into smaller blocks and the size of the batches.
Example
执行以下查询,在两个顶点 #9:0 和 #14:0 之间创建一个边 E。
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)
OrientDB - Update Edge
Update edge 命令用于更新当前数据库中的边记录。这相当于实际的 update 命令,除了在事件中检查和维护与顶点的一致性外,还可以更新 out 和 in 属性。
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> − 定义要更新的边。你可以在 Class 中选择按类型更新边,在以 Cluster 为前缀的 Cluster 中按群集更新边,或在 Record ID 中按记录 ID 更新边。
<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 − 将字段更新为给定值。
SET − Updates the field to the given values.
INCREMENT − 将给定字段加上该值。
INCREMENT − Increments the given field by the value.
ADD − 定义一个项目以添加到字段集合中。
ADD − Defines an item to add to a collection of fields.
REMOVE − 定义一个项目以从字段集合中删除。
REMOVE − Defines an item to remove from a collection of fields.
PUT − 定义入口以放入映射字段中。
PUT − Defines an entry to put into map fields.
RETURN − 定义在运行更新后要返回的表达式。
RETURN − Defines the expression you want to return after running the update.
WHERE − 定义筛选条件。
WHERE − Defines the filter condition.
LOCK − 定义在加载和更新之间记录锁定的方式。
LOCK − Defines how the record locks between the load and updates.
LIMIT − 定义最大记录数。
LIMIT − Defines the maximum number of records.
Example
让我们考虑一个通过从区域 ID = 001 和人员姓名 = Krishna 的地址表获取数据来更新人员类型中的“address”边的示例。
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)
OrientDB - Delete Edge
Delete edge 命令用于删除数据库。这相当于删除命令,此外还检查并通过从“in”和“out”顶点属性中移除对边的所有交叉引用来维护与顶点的相关性。
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 − 定义要删除的边的起始点顶点。
FROM − Defines the starting point vertex of the edge to delete.
To − 定义要删除的边的结束点顶点。
To − Defines the ending point vertex of the edge to delete.
WHERE − 定义筛选条件。
WHERE − Defines the filtering conditions.
LIMIT − 定义要删除的最大边数。
LIMIT − Defines the maximum number of edges to delete.
BATCH − 定义操作的块大小。
BATCH − Defines the block size for the operation.
Example
尝试以下示例以了解如何删除边。
Try the following examples to learn how to delete edges.
执行以下查询删除两个顶点(#11:2 和 #11:10)之间的边。但是有可能两个顶点之间存在一个或多个边。我们使用 date 属性来实现适当的功能。此查询将删除在“ 2015-01-15 ”及之后创建的边。
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)
执行以下查询以删除从顶点“#11:5”开始到顶点“#11:10”且与“class = Customer”相关的边。
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)
OrientDB - Functions
本章解释了 OrientDB 中不同类型函数的完整参考。下表定义了按其功能分类的函数列表。
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
---+----------+---------
执行以下查询以获取顶点 #11:3 的传入和传出顶点。
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.
执行以下查询以获取教授 9 年级课程的一组教师。
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.
执行以下查询以学习如何执行 if 表达式。
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
----+--------+------------------------
通过彻底使用此函数,你可以轻松地处理 OrientDB 数据。
By using this function thoroughly you can easily manipulate the OrientDB data.
OrientDB - Sequences
Sequences 是在自动递增机制中使用的概念,它在 OrientDB v2.2 中引入。在数据库术语中,序列是一种管理计数器字段的结构。简单来说,序列通常在需要始终递增的数字时使用。它支持两种类型−
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 −每次指针调用返回新值的 .next 方法。
ORDERED − Each time the pointer calls the .next method that returns a new value.
CACHED −序列将在每个节点上缓存“N”个项目。若要调用每个项目,我们使用 .next() ,在缓存包含多个项目时首选它。
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
序列通常用于自动增加人员的 ID 值。与 OrientDB 的其他 SQL 概念一样,它还执行与 RDBMS 中的序列类似的操作。
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> −序列的本地名称。
<Sequence> − Local name for sequence.
TYPE −定义序列类型为有序或缓存。
TYPE − Defines the sequence type ORDERED or CACHED.
START −定义初始值。
START − Defines the initial value.
INCREMENT −为每个 .next 方法调用定义增量。
INCREMENT − Defines the increment for each .next method call.
CACHE −定义预缓存的值的数量(如果使用了缓存序列类型)。
CACHE − Defines the number of value to pre-cache, in the event that you used to cache sequence type.
让我们创建一个以数字 1201 开头的名为“seqid”的序列。尝试以下查询使用序列实现此示例。
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
尝试以下查询使用序列“seqid”插入帐户表的 ID 值。
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 是一条用于更改序列属性的命令。它将修改除序列类型以外的所有序列选项。
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> −定义要更改的序列。
<Sequence> − Defines the sequence you want to change.
START −定义初始值。
START − Defines the initial value.
INCREMENT −为每个 .next 方法调用定义增量。
INCREMENT − Defines the increment for each .next method call.
CACHE −定义在使用缓存序列类型时要预缓存的值的数量。
CACHE − Defines the number of value to pre-cache in the event that you used to cache sequence type.
尝试以下查询更改名为 seqid 的序列的启动值从“1201 到 1000”。
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 是一条用于删除序列的命令。
Drop sequence is a command used to drop a sequence.
以下语句是删除序列的基本语法。
The following statement is the basic syntax to drop a sequence.
DROP SEQUENCE <sequence>
其中 <Sequence> 为要删除的序列。
Where <Sequence> defines the sequence you want to drop.
尝试以下查询删除名为“seqid”的序列。
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
OrientDB - Indexes
Index 是指向数据库中数据位置的指针。 Indexing 是一个概念,用于快速找到数据而无需搜索数据库中的每条记录。OrientDB 支持四种索引算法和其中的若干类型。
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
它的性能更快,并且磁盘占用量非常小。它耐用、可进行事务处理,但不支持范围查询。它的工作原理类似于 HASHMAP,这使得它在点查找方面更快速并且比其他索引类型消耗更少的资源。支持此算法的不同类型插件包括:
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
是在特定架构上创建索引的命令。
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> - 定义索引的逻辑名称。您还可以使用 <class.property> 表示法创建绑定到架构属性的自动索引。<class> 使用架构的类,<property> 使用在类中创建的属性。
<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> - 提供用于为其创建自动索引索引的类的名称。此类必须存在于数据库中。
<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> - 提供自动索引要索引的属性列表。这些属性必须已存在于架构中。
<prop-names> − Provides the list of properties, which you want the automatic index to index. These properties must already exist in schema.
<type> - 提供要创建的算法和索引类型。
<type> − Provides the algorithm and type of index that you want to create.
<key-type> - 在自动索引中提供可选键值。
<key-type> − Provides the optional key type with automatic indexes.
<metadata> - 提供 JSON 表示。
<metadata> − Provides the JSON representation.
Example
尝试以下查询以创建自动索引,该索引绑定到用户 sales_user 的属性“ID”。
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
可以使用 select 查询获取索引中的记录。
You can use select query to get the records in the index.
尝试以下查询以检索名为“indexforId”的索引的键。
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>
<name> 提供要删除的索引的名称。
Where <name> provides the name of the index you want to drop.
尝试以下查询以删除用户 sales_user 的名为“ID”的索引。
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
OrientDB - Transactions
与 RDBMS 类似,OrientDB 支持事务 ACID 属性。 transaction 包含在数据库管理系统内执行的工作单元。在数据库环境中维护事务有两个主要原因。
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.
默认情况下,数据库事务必须遵循 ACID 属性,如原子性、一致性、隔离性和持久性属性。但 OrientDB 是一个 ACID 兼容数据库,这意味着它不会矛盾或否定 ACID 的概念,而是在处理 NoSQL 数据库时改变了它的认知。了解 ACID 属性如何与 NoSQL 数据库一起工作。
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 −当您执行更改数据库操作时,更改应完全成功或失败。
Atomic − When you do something to change the database the change should work or fail as a whole.
Consistent −数据库应保持一致。
Consistent − The database should remain consistent.
Isolated −如果其他事务执行同时执行,那么用户将无法看到并行执行中的记录。
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 −如果系统崩溃(硬件或软件),数据库本身应该能够进行备份。
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.
以下是 COMMIT 数据库命令的基本语法。
The following statement is the basic syntax of the COMMIT database command.
COMMIT
Note −您必须在连接到特定的数据库并且开始事务之后才能使用此命令。
Note − You can use this command only after connecting to a particular database and after beginning the transaction.
Example
在这个示例中,我们将使用这个教程早期某个章节中创建的、称为“demo”的相同的数据库。我们将看到执行事务的操作并将记录使用事务存储起来。
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.
您需要首先使用以下 BEGIN 命令开始事务。
You need to first start the transaction using the following BEGIN command.
orientdb {db = demo}> BEGIN
使用以下命令向包含 id = 12 和 name = satish.P 值的 employee 表中插入一条记录。
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.
以下语句是 ROLLBACK 数据库命令的基本语法。
The following statement is the basic syntax of the ROLLBACK database command.
ROLLBACK
Note −您必须在连接到特定的数据库并且开始事务之后才能使用此命令。
Note − You can use this command only after connecting to a particular database and after beginning the transaction.
Example
在这个示例中,我们将使用这个教程早期某个章节中创建的、称为“demo”的相同的数据库。我们将看到执行回滚事务的操作并将记录使用事务存储起来。
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.
您必须首先使用以下 BEGIN 命令开始事务。
You have to first start the transaction using the following BEGIN command.
orientdb {db = demo}> BEGIN
使用以下命令向包含 id = 12 和 name = satish.P 值的 employee 表中插入一条记录。
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')
您可以使用以下命令检索表 employee 的记录。
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
再次查看 select 查询来从 Employee 表中检索相同的记录。
Check the select query again to retrieve the same record from the Employee table.
orientdb> SELECT FROM employee WHERE name LIKE '%.P'
如果 Rollback 成功执行,您将在输出中得到 0 条记录已找到。
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).
OrientDB - Hooks
OrientDB Hooks 不过是在数据库术语中触发器,它们启用在用户应用程序中的每个 CRUD 操作之前和之后的内部事件。您可以使用钩子来编写自定义验证规则,以强制执行安全性,或安排外部事件,比如对于关系 DBMS 进行复制。
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 支持两种钩子 −
OrientDB supports two kinds of hooks −
Dynamic Hook − 触发器,可以在类级别和/或文档级别构建。
Dynamic Hook − Triggers, which can be built at class level and/or Document level.
Java (Native) Hook − 触发器,可以使用 Java 类构建。
Java (Native) Hook − Triggers, which can be built using Java classes.
Dynamic Hooks
动态钩子比 Java 钩子更灵活,因为它们可以在运行时更改并且可以在需要时针对每个文档运行,但是比 Java 钩子慢。
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.
要在您的文档上执行钩子,首先允许您的类扩展 OTriggered 基类。之后,为相关事件定义一个自定义属性。以下是可用的事件。
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
让我们以 Javascript 编制函数 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
现在通过创建新 Invoice 文件来尝试此钩子。
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
您只能针对一个或多个文件定义特别操作。为此,允许类扩展 OTriggered 类。
You can define a special action only against one or more documents. To do this, allow your class to extend OTriggered class.
例如,让我们针对现有 Profile 类的所有文件(带有 account = 'Premium' 属性)以 Javascript 函数形式执行一个触发器。此触发器将被调用以防止删除文件。
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'
让我们创建 preventDeletion() Javascript 函数。
Let’s create the preventDeletion() Javascript function.
CREATE FUNCTION preventDeletion "throw new java.lang.RuntimeException('Cannot
delete Premium profile ' + doc)" LANGUAGE Javascript
然后通过尝试删除 “Premium” 帐户来测试钩子。
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
OrientDB 钩子(触发器)的一个常见用例是管理任何或所有类的创建和更新日期。例如,可以设置一个 CreatedDate 字段,在创建记录时使用该字段,设置一个 UpdatedDate 字段,在更新记录时使用该字段,并且可以采用在数据库层一次实现逻辑,无需在应用程序层再次考虑的方法来执行这些操作。
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.
在创建之前,您将必须通过访问以下链接 download OrientDB core 下载 orientdb-core.jar 文件。然后将 JAR 文件复制到要存储 Java 源文件的文件夹中。
Before creating, you will have to download orientdb-core.jar file by visit the following link download OrientDB core. And later copy that jar file into the folder where you want to store the Java source file.
Create Hook File
创建一个名为 HookTest.java 的 Java 文件,该文件将使用 Java 语言测试钩子机制。
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.
让我们再添加一个钩子文件 setCreatedUpdatedDates.java 如下:
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;
}
}
}
以上代码所做的是查找任何以字母“ r ”或“ t ”开头的类,并在该记录创建时设置 CreatedDate 和 UpdatedDate,并在每次更新该记录时仅设置 UpdatedDate。
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
使用以下命令编译 Java 代码。 Note :将下载的 JAR 文件和这些 Java 文件保留在同一个文件夹中。
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
您需要将完成的 JAR 文件复制到 OrientDB 服务器将对其进行查找的目录中。这意味着 OrientDB 服务器根目录下的“ ./lib ”文件夹将如下所示:
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
编辑 $ORIENTDB_HOME/config/orientdb-server-config.xml ,并添加以下部分到该文件的末尾:
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
一旦重新启动 OrientDB 服务器,您在 orientdb-server-config.xml 中定义的钩子现在就处于活动状态。启动 OrientDB 控制台,将其连接到您的数据库,并运行以下命令:
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
编辑 $ORIENTDB_HOME/config/orientdb-server-config.xml ,并将钩子部分更改如下:
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
从字母“ r ”或“ t ”开始创建新类 -
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
----+-----+------+----+-----------+-----------
即使您没有指定为 CreatedDate 和 UpdatedDate 设置的值,OrientDB 也已经为您自动设置了这些字段。
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
----+-----+------+----+-----------+-----------
您会发现,OrientDB 已经更改了 UpdatedDate ,但未更改 CreatedDate 。
You can see that OrientDB has changed the UpdatedDate but has let the CreatedDate remain unchanged.
OrientDB Java Hooks 可能是极有价值的工具,可以帮助您自动完成本来需要在应用程序代码中完成的工作。由于许多 DBA 并不总是 Java 专家,因此希望本教程中包含的信息能为您提供良好的开端,并让您对这项技术充满信心,使您能够在需要时成功创建数据库触发器。
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.
OrientDB - Caching
Caching 是一个概念,它将创建一个数据库表结构的副本,为用户应用程序提供一个舒适的环境。OrientDB 具有多个不同级别的缓存机制。
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.
在上述插图中, DB1 、 DB2 、 DB3 是应用程序中使用的三个不同的数据库实例。
In the above illustration DB1, DB2, DB3 are the three different database instances used in an application.
Level-1 缓存是一个 Local cache ,它存储特定会话已知的所有实体。如果此会话中有三个事务,它将保留所有三个事务使用的所有实体。当您关闭会话或执行“clear”方法时,会清除此缓存。它减轻了应用程序与数据库之间的 I/O 操作负担,进而提高了性能。
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 缓存是一个 Real cache ,它通过使用第三方提供程序来工作。您可以完全控制缓存的内容,即您将能够指定应删除哪些条目,应将哪些条目存储更长时间,依此类推。它是多个线程之间的完全共享缓存。
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 就是存储设备,即磁盘、内存或远程服务器。
Storage model is nothing but storage device that is disk, memory, or remote server.
How Cache Works in OrientDB?
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.
当客户端应用程序请求记录时,OrientDB 检查以下内容:
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.
当客户端应用程序请求记录时,OrientDB 检查以下信息:
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).
OrientDB - Logging
OrientDB 使用了与 Java 虚拟机捆绑的 Java 日志记录框架。OrientDB 的默认日志格式由 OLogFormatter 类进行管理。
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> − 它以以下格式来表示日期日志:yyyy-MM-dd HH:mm:ss:SSS。
<date> − It is the log date in the following format: yyyy-MM-dd HH:mm:ss:SSS.
<level> − 它是一个 5 个字符形式输出的日志记录级别。
<level> − It is the logging level as 5 chars output.
<message> − 它是日志文本,它可以具有任何大小。
<message> − It is the text of log, it can be of any size.
[<class>] − 它是一个被记录的 Java 类(可选)。
[<class>] − It is the Java class that is logged (optional).
受支持的级别是 JRE 类 java.util.logging.Level 中包含的级别。它们为:
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
可以使用 Java 之后的日志策略和策略配置一个文件。
The logging strategies and policies can be configured using a file following the Java.
syntax − Java 日志记录配置。
syntax − Java Logging configuration.
Example
从 orientdb-server-log.properties 文件复制以下内容并将其置于 $ORIENTDB_HOME/config 文件中。
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
要告知 JVM 属性文件的位置,您需要设置“ java.util.logging.config.file ”系统属性。例如,使用以下命令 −
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
要更改日志记录级别而不修改日志记录配置,只要将“ log.console.level ”和“ log.file.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
打开文件 orientdb-server-config.xml ,在 <properties> 部分的文件末尾添加或更新以下行 −
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
使用 java 的 -D 参数将系统属性“ log.console.level ”和“ log.file.level ”设置为所需的级别。
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
可以使用 System.setProperty() API 在启动时设置系统变量。以下代码段是使用 Java 代码设置日志记录级别的语法。
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
针对 URL 执行 HTTP POST:/server/log.<type>/<level>,其中 −
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
以下示例使用 cURL 对 OrientDB 服务器执行 HTTP POST 命令。使用了服务器的“root”用户和密码,请替换为自己的密码。
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
OrientDB - Performance Tuning
在本章中,你可以获得一些关于如何优化使用 OrientDB 的应用程序的一般性技巧。有三种方法可以提高不同类型数据库的性能。
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.
你可以通过更改内存、JVM 和远程连接设置来实现通用性能调整。
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
这些设置对服务器组件和在嵌入模式下直接使用 plocal 运行 Java 应用程序的 JVM 均有效。
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.
调优最重要的在于确保内存设置正确。决定性因素在于正确平衡内存映射中使用的堆和虚拟内存,特别是在大数据集方面(GB、TB 及以上),在这种情况下,内存内缓存结构的重要性低于原始 IO。
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.
例如,如果可以将最高 8GB 分配给 Java 进程,那么通常分配小堆和较大的磁盘高速缓存(堆外内存)会更好。
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 ...
设置 storage.diskCache.bufferSize (旧“本地”存储为 file.mmap.maxMemory )以 MB 为单位,说明磁盘高速缓存组件使用多少内存。默认值为 4GB。
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 − 如果最大堆和磁盘高速缓存的总和过高,可能会导致操作系统因巨大减速而交换。
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 设置编码在 server.sh(和 server.bat)批处理文件中。您可以更改它们来根据您的使用情况和硬件/软件设置来调整 JVM。在 server.bat 文件中添加以下行。
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
此设置将禁用 JVM 的调试信息写入。如果您需要分析 JVM,只需移除此设置。
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
使用远程数据库时,您必须注意所使用的获取策略。默认情况下,OrientDB 客户端仅加载结果集中包含的记录。例如,如果查询返回 100 个元素,但您如果从客户端遍历这些元素,则 OrientDB 客户端会延迟为每个丢失的记录向服务器进行一次网络调用来加载元素。
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.
配置非常简单,仅有 2 个参数 −
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
即使更新图形,您也应始终在事务中工作。OrientDB 允许您在事务之外工作。常见情况是只读查询,或者在发生故障时可以恢复的庞大且非并发操作。当您在分布式配置上运行时,使用事务有助于降低延迟。这是因为分布式操作仅在提交时发生。由于延迟,分配一个大操作比传输多个小操作更有效。
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 分布式配置设置为完全复制。拥有多个具有相同数据库副本的节点对于扩展读取非常重要。事实上,每台服务器都是独立执行读取和查询的。如果您有 10 个服务器节点,则读取吞吐量就是 10 倍。
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.
对于写入操作,正好相反:如果复制是同步的,则具有完全复制的多个节点会使操作变慢。在这种情况下,将数据库分片到多个节点可以扩展写入,因为只有部分节点参与写入。此外,你的数据库可以大于一个服务器节点的 HD。
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
如果你有慢速网络,并且有同步(默认)复制,则可能会付出延迟的代价。事实上,当 OrientDB 同步运行时,它至少等待 writeQuorum 。这意味着,如果 writeQuorum 为 3,并且有 5 个节点,则协调器服务器节点(分布式操作在那里启动)必须至少等待来自 3 个节点的响应,才能向客户端提供响应。
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.
为了保持一致性,应将 writeQuorum 设置为多数。如果你有 5 个节点,则多数为 3。将 writeQuorum 设置为 3 而不是 4 或 5 可以降低延迟成本,同时仍保持一致性。
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.
OrientDB - Upgrading
升级时,必须考虑版本号和格式。有三种类型的格式 - MAJOR(主要)、MINOR(次要)、PATCH(修补)。
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.
要在次要版本和主要版本之间同步,可能需要导出并导入数据库。有时,可能需要将数据库从 LOCAL 迁移到 PLOCAL,并且需要将图迁移到 RidBag。
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
从版本 1.5.x 开始,OrientDB 带有一个全新的存储引擎:PLOCAL(分页 LOCAL)。它与 LOCAL 一样持久,但以不同的方式存储信息。以下各点显示了 PLOCAL 和 LOCAL 之间的比较 −
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".
若要将本地存储迁移到新 PLOCAL,需要使用 PLOCAL 作为存储引擎导出并重新导入数据库。以下为步骤。
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 − 打开一个新 shell(Linux/Mac)或命令提示符(Windows)。
Step 1 − Open a new shell (Linux/Mac) or a Command Prompt (Windows).
Step 2 − 使用控制台导出数据库。按照给定命令将数据库 demo 导出到 demo.json.gzip 文件中。
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 − 在本地文件系统中,使用“plocal”引擎创建新数据库 −
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 − 将旧数据库导入到新数据库中。
Step 4 − Import the old database to the new one.
orientdb> IMPORT DATABASE /temp/demo.json.gzip -preserveClusterIDs=true
orientdb> QUIT
如果您在相同 JVM 中访问数据库,请务必将 URL 从“local:”更改为“plocal:”
If you access the database in the same JVM, remember to change the URL from "local:" to "plocal:"
Migrate Graph to RidBag
从 OrientDB 1.7 开始,RidBag 是一种默认集合,用于管理图中的邻接关系。虽然由 MVRB-Tree 管理的较旧数据库完全兼容,但您可以将数据库更新为较新的格式。
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.
您可以通过控制台或使用 ORidBagMigration 类来升级图形。
You can upgrade your graph via console or using the ORidBagMigration class.
-
Connect to database CONNECT plocal:databases/<graphdb-name>
-
Run upgrade graph command
OrientDB - Security
与 RDBMS 一样,OrientDB 也提供基于众所周知概念、用户和角色的安全机制。每个数据库都有自己的用户,每个用户有一个或多个角色。角色是工作模式和权限集的组合。
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
默认情况下,OrientDB 为服务器中的所有数据库维护三个不同的用户 −
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
连接到数据库后,可以通过对 OUser 类的 SELECT 查询来查询数据库上的当前用户。
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
要创建新用户,请使用 INSERT 命令。请记住,在此过程中,你必须将状态设置为 ACTIVE,并授予它一个有效角色。
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
你可以使用 UPDATE 语句更改用户名称。
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 以哈希格式保存密码。触发器 OUserTrigger 在保存记录之前,会透明地加密密码。
OrientDB saves the password in a hash format. The trigger OUserTrigger encrypts the password transparently before it saves the record.
Disabling Users
要禁用用户,请使用 UPDATE 将其状态从 ACTIVE 更改为 SUSPENDED。例如,如果你希望禁用除 admin 之外的所有用户,请使用以下命令 −
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
连接到数据库后,可以使用对 ORole 类的 SELECT 查询来查询数据库上的当前角色。
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
要创建新角色,请使用 INSERT 语句。
To create a new role, use the INSERT statement.
orientdb> INSERT INTO ORole SET name = 'developer', mode = 0
Working with Modes
规则用于确定属于特定角色的用户在数据库上可以做什么,工作模式用于确定 OrientDB 如何解释这些规则。工作模式有两种类型,由 1 和 0 指定。
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.
OrientDB - Studio
OrientDB 提供了一个 Web UI 来通过 GUI 执行数据库操作。本章介绍 OrientDB 中提供的不同选项。
OrientDB provides a web UI to carry out database operations through GUI. This chapter explains the different options available in OrientDB.
Studio Homepage
Studio 是一个用于管理 OrientDB 的 Web 界面,作为 OrientDB 发行版的一部分提供。
Studio is a web interface for the administration of OrientDB that comes in bundle with the OrientDB distribution.
首先,你需要使用以下命令启动 OrientDB 服务器。
First, you need to start the OrientDB server using the following command.
$ server.sh
在计算机上运行 OrientDB 时,可以通过 URL 访问 Web 界面 −
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.
Connect to an Existing Database
要登录,请从数据库列表中选择一个数据库,并使用任意数据库用户。默认情况下(用户名/密码), reader/reader 可以读取数据库中的记录, writer/writer 可以读取、创建、更新和删除记录,而 admin/admin 拥有所有权限。
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
从数据库列表中选择一个数据库,然后单击废纸篓图标。Studio 会打开一个确认弹出窗口,你必须在其中输入服务器用户名和服务器密码。
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.
然后单击“删除数据库”按钮。你可以在 $ORIENTDB_HOME/config/orientdb-server-config.xml 文件中找到服务器凭证。
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.
需要以下信息才能创建新数据库 −
Following information is needed to create a new database −
-
Database name
-
Database type (Document/Graph)
-
Storage type (plocal/memory)
-
Server user
-
Server password
你可以在 $ORIENTDB_HOME/config/orientdbserver-config.xml 文件中找到服务器凭证。
You can find the server credentials in the $ORIENTDB_HOME/config/orientdbserver-config.xml file.
<users>
<user name = "root" password = "pwd" resources = "*" />
</users>
创建后,Studio 会自动登录到新数据库。
Once created, Studio will automatically login to the new database.
Execute a Query
Studio 支持对你正在使用的语言(包括 SQL 和 Gremlin)来自动识别。在编写时,按 Ctrl + Space 使用自动完成功能。
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.
通过单击结果集中任何 @rid 值,如果记录是文档,您将进入文档编辑模式;否则,您将进入顶点编辑模式。
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.
您可以通过单击结果集中或编辑器中的星形图标对查询进行书签。要浏览有书签的查询,请单击 Bookmarks 按钮。Studio 将在左侧打开书签列表,您可以在其中编辑/删除或重新运行查询。
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.
Studio 将执行的查询保存在浏览器的本地存储中。在查询设置中,您可以配置 Studio 在历史记录中保留多少查询。您还可以搜索以前执行的查询、从历史记录中删除所有查询或删除单个查询。
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.
选择特定顶点上的编辑符号。您将获得以下屏幕,其中包含编辑顶点的选项。
Select the edit symbol on the particular vertex. You will get the following screen which contains the options to edit the vertex.
Schema Manager
OrientDB 可以以无模式模式、模式模式或两者兼有的模式工作。这里,我们将讨论模式模式。单击 Web UI 顶部的架构部分。您将获得以下屏幕截图。
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.
Create a New Class
要创建新类,只需单击 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.
View All Indexes
当您希望概述数据库中创建的所有索引时,只需单击架构 UI 中的所有索引按钮即可。这将快速访问有关索引的一些信息(名称、类型、属性等),您可以从此处删除或重建它们。
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.
Edit Class
单击架构部分中的任何类,您将获得以下屏幕截图。
Click on any class on the schema section, you will get the following screenshot.
在编辑类时,您可以添加属性或添加新索引。
While editing a class, you can add a property or add a new 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.
Add Vertices
若要在图表数据库和图表画布区域中添加新顶点,您必须按下 Add Vertex 按钮。此操作分两步完成。
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.
在第二步,您必须插入新顶点的字段值。您还可以添加自定义字段,因为 OrientDB 支持无模式模式。若要使新顶点持久化,请单击“保存更改”,然后顶点将被保存到数据库中并添加到画布区域。
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.
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.
Security
Studio 2.0 包含新的安全管理,您可以在其中以图形方式管理用户和角色。
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
Roles
您可以执行以下操作来管理数据库角色 -
You can perform the following actions to manage the database roles −
-
Search Role
-
Add Role
-
Delete Role
-
Edit Role
Add Role
若要添加新用户,请单击 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 Rule to a Role
若要为所选角色添加新的安全规则,请单击 Add Rule 按钮。这将会询问您要保护的资源字符串。然后,您可以在新创建的资源上配置 CRUD 权限。
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.
OrientDB - Java Interface
与 RDBMS 类似,OrientDB 支持 JDBC。为此,我们首先需要为 JDBC 编程配置环境。以下是创建应用程序和数据库之间连接的过程。
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.
首先,我们需要下载 JDBC 驱动程序。访问以下链接 https://code.google.com/archive/p/orient/downloads 下载 OrientDB-JDBC。
First, we need to download the JDBC Driver. Visit the following link https://code.google.com/archive/p/orient/downloads to download OrientDB-JDBC.
以下是实现 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
尝试以下示例来理解 OrientDB-JDBC 连接。让我们考虑一张包含以下字段及其类型的员工表。
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
执行所有命令后,将生成包含以下字段的 Employee 表,即带 ID 的雇员姓名、年龄和入职日期字段。
After executing all the commands, you will get the Employee table with the following fields, employee name with id, age, and join_date fields.
将以下代码保存在 OrientJdbcDemo.java 文件中。
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
OrientDB - Python Interface
面向 Python 的 OrientDB 驱动程序使用二进制协议。PyOrient 是帮助将 OrientDB 连接到 Python 的 git hub 项目名称。它适用于 OrientDB 1.7 及更高版本。
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.
以下命令用于安装 PyOrient。
The following command is used to install PyOrient.
pip install pyorient
可以将名为 demo.py 的脚本文件用于执行以下任务:
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