1. PHP드라이브
PHP 개발자을 위해 아랑고DB를 컨트롤 할 수 있는 예제를 만들어 보았다.
그대로 복사 붙혀넣어서 분석하면 가장 빠르겠지만 손으로 직접 쳐보면서 해보자
- arangoDB PHP 드라이브 파일
- 대용량 데이터를 위해 10가지 문자열들 (단순히 include "txt.php" 를 위함)
- 설치방법 : (/)루트에 arangoDB.7z 해당 파일을 풀고 requeire로 autoload.php를 인트루드 하면 준비 PHP에서 아랑고 디비 쓰기 준비 끝!!
// - 아랑고 드라이버를 로드한다. //https://www.arangodb.com/arangodb-drivers // 아랑고 디비 드라이브
require_once __DIR__ . '/arangoDB/autoload.php';
2. ArangoDB -> PHP 레퍼런스
<?php
/*** 0.연결 ***/
// - 아랑고 드라이버를 로드한다. //https://www.arangodb.com/arangodb-drivers // 아랑고 디비 드라이브
require_once __DIR__ . '/arangoDB/autoload.php';
// - 아랑고 함수를 as 합니다. 이름 그대로 쓰면 내장함수랑 구분 가독성이 떨어져 as
use ArangoDBClient\Collection as ArangoCollection; // 컬렉션(테이블)
use ArangoDBClient\CollectionHandler as ArangoCollectionHandler; // 컬렉션 핸들
use ArangoDBClient\Connection as ArangoConnection; // 컨넥션
use ArangoDBClient\ConnectionOptions as ArangoConnectionOptions; // 컨넥션 옵션
use ArangoDBClient\DocumentHandler as ArangoDocumentHandler; // 도큐먼트(컬럼) 핸들
use ArangoDBClient\Document as ArangoDocument; // 데이터 핸들
use ArangoDBClient\Exception as ArangoException; // 예외사항 처리
use ArangoDBClient\Export as ArangoExport; // 데이터 exort
use ArangoDBClient\ConnectException as ArangoConnectException; // db연결 예외처리
use ArangoDBClient\ClientException as ArangoClientException; // 클라이언트 예외처리
use ArangoDBClient\ServerException as ArangoServerException; // 서버 예외처리
use ArangoDBClient\Statement as ArangoStatement; // 컨넥션 메소드 객체생성
use ArangoDBClient\UpdatePolicy as ArangoUpdatePolicy; // 업데이트 정책 (앞,뒤?)
// - 기본 연결 옵션입니다.
$connectionOptions = [
ArangoConnectionOptions::OPTION_DATABASE => 'sampledb', // 데이터 베이스명
ArangoConnectionOptions::OPTION_ENDPOINT => 'tcp://127.0.0.1:8529', // 아랑고 IP와 포트
ArangoConnectionOptions::OPTION_AUTH_TYPE => 'Basic', // 아랑고 연결 타입 Basic이 일반적인 연결
ArangoConnectionOptions::OPTION_AUTH_USER => 'admin@test', // 유저 로그인 ID 풀네임이 필요하다
ArangoConnectionOptions::OPTION_AUTH_PASSWD => 'test', // 유저 패스워드
ArangoConnectionOptions::OPTION_CONNECTION => 'Keep-Alive', // 연결을 계속 유지할것인지. != close
ArangoConnectionOptions::OPTION_TIMEOUT => 3, // 연결 시도 초
ArangoConnectionOptions::OPTION_RECONNECT => true, // 연결이 시간 초과되었을 때 재연결할지 여부, true ->끝임없이 재접속 시도함
ArangoConnectionOptions::OPTION_CREATE => true, // 데이터 입력시 새로운 컬렉션(테이블)에 입력한다면
ArangoConnectionOptions::OPTION_UPDATE_POLICY => ArangoUpdatePolicy::LAST,
];
// - 로깅 기능을 킨다. LOG기록이 남겨진다.
ArangoException::enableLogging();
// - 테스트를 위한 변수
// - DB를 연결한다.
$connection = new ArangoConnection($connectionOptions); // ArangoConnection을 이용해 설정한 연결을 변수에 담는다.
$collectionHandler = new ArangoCollectionHandler($connection); // 컨넥션 핸들을 만들어 낸다.
/*** 1. 컬렉션(테이블) 생성 예제 PHP 버전(create,drop) ***/
// - 컬렉션 존재 여부 체크, 삭제
foreach ($collectionName as $value) { // 컬렉션명 배열있는 만큼
if ($collectionHandler->has($value)) { // 해당 컬렉션 존재 하는지 체크
$collectionHandler->drop($value); // 컬렉션 삭제
//$collectionHandler->getCollectionId($collection); // 컬렉션 아이디를 가져온다
//$collectionHandler->rename($collection, $name); // 컬렉션 명을 바꾼다.
}
}
// - 컬렉션 생성 예제
for($x = 0; $x < count($collectionName); $x++) { // 컬렉션 생성 배열
$userCollection = new ArangoCollection(); // 컬렉션 사용준비
$userCollection->setName($collectionName[$x]); // 생성할 컬렉션 이름을 지정
$id = $collectionHandler->create($collectionName[$x]); // 컬렉션을 생성한다. ID가 반환됨
//createSkipListIndex, createPersistentIndex 도 같은 방법으로 생성 가능하다.
}
/*** 2. insert documnet(데이터) PHP 버전 ***/
include "txt.php";
for ($i = 1; $i <= $dataCnt; $i++) {
try {
$handler = new ArangoDocumentHandler($connection);
// - 아랑고 도큐먼트를 가져온다.
$user = new ArangoDocument();
// - (키 , 값)으로 데이터를 만든다.
$user->set('name', 'gv_'.$i);
$user->set('age', 26+$i);
$user->set('weight', null);
$user->set('content',${"str_"."0".substr($i,-1)} );
// - 배열데이터를 만든다.
$user->favorites = ['drawing', 'cycle', 'one piece'];
// - 서버로 데이터를 전송한다.
$id = $handler->save($collectionName[0], $user); //고유 seq값인 _key를 반환한다.
// - 데이터 입력 됐는지 확인
$result = $handler->has($collectionName[0], $id);
//var_dump($user->getId());
} catch (ArangoConnectException $e) {
print 'Connection error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoClientException $e) {
print 'Client error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoServerException $e) {
print 'Server error: ' . $e->getServerCode() . ':' . $e->getServerMessage() . ' ' . $e->getMessage() . PHP_EOL;
}
}
/*** 3. SELECT documnet(데이터)를 선택한다. PHP버전 ***/
$document = $handler->get($collectionName[0], $id); // 컬렉션,고유키(_key)로 document(데이터)를 얻는다. 이 dcument로 update,delete 가능
/*** 4. UPDATE documnet(데이터)를 수정한다. PHP버전 ***/
$document->set("name", "hire"); // 먼저 수정하고 싶은 데이터를 READ 한후에 set으로 바꿔주고 그대로 다시 업데이트(입력) 한다.
$handler->update($document); // document 그대로 실행
/*** 5. DELETE documnet(데이터)를 삭제한다. PHP버전 ***/
$documentDelete = $handler->remove($document); // 업데이트와 마찬가지로 Read한 document로 삭제 한다.
/*** 6. insert 예제 AQL버전 ***/
//$query = ' INSERT { name: "raebu", age:13, width:null, favorites:[\'sing\', \'rap\', \'fight\'] } INTO ' . $collectionName; //한줄 넣기
$query = ' FOR i IN 1..'.$dataCnt; /* 반복문 루프될 숫자만 정해주면 된다.*/
$query = $query.' INSERT {';
$query = $query.' name: CONCAT("gv_", i),'; /* CONCAT 문자열 연결 */
$query = $query.' addr : (i % 2 == 0 ? "강북" : "강남")'; /* 삼항연산 가능 */
$query = $query.' }';
$query = $query.' INTO '.$collectionName[1];
$statement = new ArangoStatement( /* 컨넥션 메서드를 설정하고 */
$connection,
array(
"query" => $query
)
);
$statement->execute(); /* excute 한다. */
/*** 7. select , inner join AQL버전 ***/
$query = ' FOR cur1 IN '.$collectionName[0];
$query = $query.' FOR cur2 IN '.$collectionName[1]; // join할 테이블
$query = $query.' FILTER cur1.name == cur2.name '; // 여기서 On 을 하면 된다.
$query = $query.' SORT cur1.age desc ';
$query = $query.' RETURN { ';
$query = $query.' name:cur1.name ';
$query = $query.' ,age:cur1.age ';
$query = $query.' ,age:cur1.age ';
$query = $query.' ,favorites:cur1.favorites ';
$query = $query.' ,addr:cur2.addr '; // 명명자로 구분해서 노출 TSQL이랑 상당히 흡사
$query = $query.'}';
//echo $query;
$statement = new ArangoStatement(
$connection,
array(
"query" => $query
,"count" => false
,"batchSize" => 1000 // 노출 데이터 사이즈 기본이 1000 엘리먼트
,"sanitize" => true
,"_flat" => true // 기초적인 데이터만 노출, true를 해야 바로 json_encode로 데이터를 만들수 있다.
)
);
$cursor = $statement->execute();
/*** 7-1.AQL 실행된걸 JSON으로 노출 ***/
$resultingDocuments = array();
foreach ($cursor as $key => $value) {
$resultingDocuments[$key] = $value;
}
//echo json_encode($resultingDocuments); // json으로 노출
ini_set('max_execution_time', 3000); //300 seconds = 5 minutes
// - 아랑고 드라이버를 로드한다. //https://www.arangodb.com/arangodb-drivers // 아랑고 디비 드라이브
require_once __DIR__ . '/arangoDB/autoload.php';
// - 아랑고 함수를 as 합니다. 이름 그대로 쓰면 내장함수랑 구분 가독성이 떨어져 as
use ArangoDBClient\Collection as ArangoCollection; // 컬렉션(테이블)
use ArangoDBClient\CollectionHandler as ArangoCollectionHandler; // 컬렉션 핸들
use ArangoDBClient\Connection as ArangoConnection; // 컨넥션
use ArangoDBClient\ConnectionOptions as ArangoConnectionOptions; // 컨넥션 옵션
use ArangoDBClient\DocumentHandler as ArangoDocumentHandler; // 도큐먼트(컬럼) 핸들
use ArangoDBClient\Document as ArangoDocument; // 데이터 핸들
use ArangoDBClient\Exception as ArangoException; // 예외사항 처리
use ArangoDBClient\Export as ArangoExport; // 데이터 exort
use ArangoDBClient\ConnectException as ArangoConnectException; // db연결 예외처리
use ArangoDBClient\ClientException as ArangoClientException; // 클라이언트 예외처리
use ArangoDBClient\ServerException as ArangoServerException; // 서버 예외처리
use ArangoDBClient\Statement as ArangoStatement; // 컨넥션 메소드 객체생성
use ArangoDBClient\UpdatePolicy as ArangoUpdatePolicy; // 업데이트 정책 (앞,뒤?)
// - 기본 연결 옵션입니다.
$connectionOptions = [
ArangoConnectionOptions::OPTION_DATABASE => 'sampledb', // 데이터 베이스명
ArangoConnectionOptions::OPTION_ENDPOINT => 'tcp://127.0.0.1:8529', // 아랑고 IP와 포트
ArangoConnectionOptions::OPTION_AUTH_TYPE => 'Basic', // 아랑고 연결 타입 Basic이 일반적인 연결
ArangoConnectionOptions::OPTION_AUTH_USER => 'admin@test', // 유저 로그인 ID 풀네임이 필요하다
ArangoConnectionOptions::OPTION_AUTH_PASSWD => 'test', // 유저 패스워드
ArangoConnectionOptions::OPTION_CONNECTION => 'Keep-Alive', // 연결을 계속 유지할것인지. != close
ArangoConnectionOptions::OPTION_TIMEOUT => 3, // 연결 시도 초
ArangoConnectionOptions::OPTION_RECONNECT => true, // 연결이 시간 초과되었을 때 재연결할지 여부, true ->끝임없이 재접속 시도함
ArangoConnectionOptions::OPTION_CREATE => true, // 데이터 입력시 새로운 컬렉션(테이블)에 입력한다면
ArangoConnectionOptions::OPTION_UPDATE_POLICY => ArangoUpdatePolicy::LAST,
];
// - 로깅 기능을 킨다. LOG기록이 남겨진다.
ArangoException::enableLogging();
// - 테스트를 위한 변수
$collectionName = array("argdb", "argdb_addr"); // 컬렉션 이름을 지정한 변수, 두개 테이블 선언
$dataCnt = 1000;
// - DB를 연결한다.
$connection = new ArangoConnection($connectionOptions); // ArangoConnection을 이용해 설정한 연결을 변수에 담는다.
$collectionHandler = new ArangoCollectionHandler($connection); // 컨넥션 핸들을 만들어 낸다.
/*** 1. 컬렉션(테이블) 생성 예제 PHP 버전(create,drop) ***/
// - 컬렉션 존재 여부 체크, 삭제
foreach ($collectionName as $value) { // 컬렉션명 배열있는 만큼
if ($collectionHandler->has($value)) { // 해당 컬렉션 존재 하는지 체크
$collectionHandler->drop($value); // 컬렉션 삭제
//$collectionHandler->getCollectionId($collection); // 컬렉션 아이디를 가져온다
//$collectionHandler->rename($collection, $name); // 컬렉션 명을 바꾼다.
}
}
// - 컬렉션 생성 예제
for($x = 0; $x < count($collectionName); $x++) { // 컬렉션 생성 배열
$userCollection = new ArangoCollection(); // 컬렉션 사용준비
$userCollection->setName($collectionName[$x]); // 생성할 컬렉션 이름을 지정
$id = $collectionHandler->create($collectionName[$x]); // 컬렉션을 생성한다. ID가 반환됨
// - 컬렉션 인덱스를 생성
$collectionHandler->createHashIndex($id,array("name"),null,null); // Hash 인덱스 생성, 컬렉션 ID를 이용해야 한다.
$collectionHandler->createFulltextIndex($id,array("content"),null); // FulltextIndex 생성//createSkipListIndex, createPersistentIndex 도 같은 방법으로 생성 가능하다.
}
/*** 2. insert documnet(데이터) PHP 버전 ***/
include "txt.php";
for ($i = 1; $i <= $dataCnt; $i++) {
try {
$handler = new ArangoDocumentHandler($connection);
// - 아랑고 도큐먼트를 가져온다.
$user = new ArangoDocument();
// - (키 , 값)으로 데이터를 만든다.
$user->set('name', 'gv_'.$i);
$user->set('age', 26+$i);
$user->set('weight', null);
$user->set('content',${"str_"."0".substr($i,-1)} );
// - 배열데이터를 만든다.
$user->favorites = ['drawing', 'cycle', 'one piece'];
// - 서버로 데이터를 전송한다.
$id = $handler->save($collectionName[0], $user); //고유 seq값인 _key를 반환한다.
// - 데이터 입력 됐는지 확인
$result = $handler->has($collectionName[0], $id);
//var_dump($user->getId());
} catch (ArangoConnectException $e) {
print 'Connection error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoClientException $e) {
print 'Client error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoServerException $e) {
print 'Server error: ' . $e->getServerCode() . ':' . $e->getServerMessage() . ' ' . $e->getMessage() . PHP_EOL;
}
}
/*** 3. SELECT documnet(데이터)를 선택한다. PHP버전 ***/
$document = $handler->get($collectionName[0], $id); // 컬렉션,고유키(_key)로 document(데이터)를 얻는다. 이 dcument로 update,delete 가능
/*** 4. UPDATE documnet(데이터)를 수정한다. PHP버전 ***/
$document->set("name", "hire"); // 먼저 수정하고 싶은 데이터를 READ 한후에 set으로 바꿔주고 그대로 다시 업데이트(입력) 한다.
$handler->update($document); // document 그대로 실행
/*** 5. DELETE documnet(데이터)를 삭제한다. PHP버전 ***/
$documentDelete = $handler->remove($document); // 업데이트와 마찬가지로 Read한 document로 삭제 한다.
/*** 6. insert 예제 AQL버전 ***/
//$query = ' INSERT { name: "raebu", age:13, width:null, favorites:[\'sing\', \'rap\', \'fight\'] } INTO ' . $collectionName; //한줄 넣기
$query = ' FOR i IN 1..'.$dataCnt; /* 반복문 루프될 숫자만 정해주면 된다.*/
$query = $query.' INSERT {';
$query = $query.' name: CONCAT("gv_", i),'; /* CONCAT 문자열 연결 */
$query = $query.' addr : (i % 2 == 0 ? "강북" : "강남")'; /* 삼항연산 가능 */
$query = $query.' }';
$query = $query.' INTO '.$collectionName[1];
$statement = new ArangoStatement( /* 컨넥션 메서드를 설정하고 */
$connection,
array(
"query" => $query
)
);
$statement->execute(); /* excute 한다. */
/*** 7. select , inner join AQL버전 ***/
$query = ' FOR cur1 IN '.$collectionName[0];
$query = $query.' FOR cur2 IN '.$collectionName[1]; // join할 테이블
$query = $query.' FILTER cur1.name == cur2.name '; // 여기서 On 을 하면 된다.
$query = $query.' SORT cur1.age desc ';
$query = $query.' RETURN { ';
$query = $query.' name:cur1.name ';
$query = $query.' ,age:cur1.age ';
$query = $query.' ,age:cur1.age ';
$query = $query.' ,favorites:cur1.favorites ';
$query = $query.' ,addr:cur2.addr '; // 명명자로 구분해서 노출 TSQL이랑 상당히 흡사
$query = $query.'}';
//echo $query;
$statement = new ArangoStatement(
$connection,
array(
"query" => $query
,"count" => false
,"batchSize" => 1000 // 노출 데이터 사이즈 기본이 1000 엘리먼트
,"sanitize" => true
,"_flat" => true // 기초적인 데이터만 노출, true를 해야 바로 json_encode로 데이터를 만들수 있다.
)
);
$cursor = $statement->execute();
/*** 7-1.AQL 실행된걸 JSON으로 노출 ***/
$resultingDocuments = array();
foreach ($cursor as $key => $value) {
$resultingDocuments[$key] = $value;
}
//echo json_encode($resultingDocuments); // json으로 노출
?>
'IT_Developers > NoSQL' 카테고리의 다른 글
ArangoDB | 강의 | 05 - INDEX (0) | 2017.07.01 |
---|---|
ArangoDB | 강의 | 04 - UPDATE / DELETE(REMOVE) (0) | 2017.07.01 |
ArangoDB | 강의 | 03 - INSERT / SELECT / INNER JOIN / COLLECTIONS (0) | 2017.07.01 |
ArangoDB | 강의 | 02 - 유저 및 DB 생성 / WEBInterface 접속&사용법 (0) | 2017.07.01 |
ArangoDB | 강의 | 01 - DB 설치(windows) (1) | 2017.07.01 |
댓글