public static function show(Inputter $inputter, JSONOutputter $outputter) { // Show // $id = $inputter->additional_uri_arguments[0]; $error = null; UniversallyUniqueIdentifier::propertyIsValid('rawIdentifier', $id, $error); if (isset($error)) { $outputter->print_error($error); } // User ID // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string = 'MATCH (object:Album) WHERE object.' . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . ' = \'' . $id . '\' RETURN object'; $query = new Everyman\Neo4j\Cypher\Query($client, $query_string); $result = $query->getResultSet(); if (count($result) > 0) { // Compare sent data is equal to data retrieved // $object = $result[0]['object']; // Print data // $outputter->print_data(array(Album::printer_dictionary($object))); } else { // Throw error, user doesn't exists // $error = Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_ENTITY_DOES_NOT_EXIST, 'Album with ID does not exist.'); $outputter->print_error($error); } }
public static function search_list(Inputter $inputter, JSONOutputter $outputter) { // Search string // $search_string = $inputter->additional_uri_arguments[0]; $user_error = null; if (!is_string($search_string)) { // Throw error, search string is not a string // $error = Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_INPUT_UNCONFORMING, 'Search string is not a string.'); $outputter->print_error($error); } // Query // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); // Users // $query_string_search_users = 'MATCH (foundUser:CreatingUser) ' . 'WHERE (foundUser.' . CREATINGUSER_KEY_FIRST_NAME . ' + " " + foundUser.' . CREATINGUSER_KEY_SURNAME . ') =~ "(?i)' . $search_string . '.*" OR foundUser.' . CREATINGUSER_KEY_NAME . ' =~ "(?i)' . $search_string . '.*" OR foundUser.' . USER_KEY_EMAIL . ' =~ "(?i)' . $search_string . '" ' . 'RETURN foundUser'; $query_search_users = new Everyman\Neo4j\Cypher\Query($client, $query_string_search_users); $result_search_users = $query_search_users->getResultSet(); // Events in scope // $query_string_search_events = 'MATCH (foundCreator:CreatingUser)-[:creator]-(foundEvent:Event)-[:type]-(foundEventType:EventType), (foundOccurrence:EventSpaceTimeOccurrence)-[:occurrence]-(foundEvent) ' . 'WHERE foundEvent.privacy = 1 AND ANY(label IN labels(foundEventType) WHERE label =~ "(?i).*' . $search_string . '.*") ' . 'RETURN foundEvent, foundEventType, foundCreator, collect(foundOccurrence) as foundEventOccurrences'; $query_search_events = new Everyman\Neo4j\Cypher\Query($client, $query_string_search_events); $result_search_events = $query_search_events->getResultSet(); // Output // // Users // $print_users = array(); foreach ($result_search_users as $row) { array_push($print_users, AttendingUser::printer_dictionary($row['foundUser'])); } // Events in scope // $print_events = array(); foreach ($result_search_events as $row) { $event_dictionary = array(); if ($event_dictionary != Event::printer_dictionary($row['foundEvent'])) { $event_dictionary = Event::printer_dictionary($row['foundEvent']); $event_dictionary[EVENT_RELATIONSHIP_NAME_TYPE] = EventType::printer_dictionary($row['foundEventType']); $event_dictionary[EVENT_RELATIONSHIP_NAME_OCCURRENCE] = array(); } foreach ($row['foundEventOccurrences'] as $occurrence) { array_push($event_dictionary[EVENT_RELATIONSHIP_NAME_OCCURRENCE], EventSpaceTimeOccurrence::printer_dictionary($occurrence)); } if ($event_dictionary != Event::printer_dictionary($row['foundEvent'])) { array_push($print_events, $event_dictionary); } } // Print data // $outputter->print_data(array(array("users" => $print_users, "events" => $print_events))); }
function enlargeNeoDatabase($unifiedName) { $client = new Everyman\Neo4j\Client('localhost', 7474); $client->getTransport()->setAuth('neo4j', 'muresearch'); //Check if the author exists $exist = FALSE; $authorExists = "match (u:Person {name: \"" . $unifiedName . "\"}) return u"; $query = new Query($client, $authorExists); $result = $query->getResultSet(); foreach ($result as $r) { $exist = TRUE; } if (!$exist) { //Author does not exists. Must be of Mizzou $crawler = new CoauthorNetworkCrawler($unifiedName, $affiliation = "University of Missouri"); $crawler->insertDB('localhost', 7474, 'neo4j', 'muresearch'); $setHasSearched = "match (u:Person {name: \"" . $unifiedName . "\"}) set u.hasSearched = 1"; $query = new Query($client, $setHasSearched); $result = $query->getResultSet(); return; } //Check if we need to crawl the network for this author while the author already exists. $hasSearched = "match (u:Person {name: \"" . $unifiedName . "\"}) return has(u.hasSearched) as hasSearched"; $query = new Query($client, $hasSearched); $result = $query->getResultSet(); foreach ($result as $r) { if ($r['hasSearched']) { //The user has been searched before. No need to re-search it return; } else { //The user has NOT been seasrched before. //Get the affiliation of this user $getAffiliation = "match (u:Person {name: \"" . $unifiedName . "\"}) return u.affiliation as affiliation"; $query = new Query($client, $getAffiliation); $result = $query->getResultSet(); foreach ($result as $r) { if (!empty($r['affiliation'])) { //Affiliation info presented $affiliation = filterAffiliation($r['affiliation']); } else { //Affiliation info empty $affiliation = ""; } } $setHasSearched = "match (u:Person {name: \"" . $unifiedName . "\"}) set u.hasSearched = 1"; $query = new Query($client, $setHasSearched); $result = $query->getResultSet(); //echo $affiliation."\n"; $crawler = new CoauthorNetworkCrawler($unifiedName, $affiliation); //print_r($crawler->crawlPubmed()); $crawler->insertDB('localhost', 7474, 'neo4j', 'muresearch'); return; } } }
public function indexAction() { $client = new Everyman\Neo4j\Client('localhost', 7474); $this->view->disable(); //Create a response instance $response = new \Phalcon\Http\Response(); //Set the content of the response $response->setContent(json_encode($client->getServerInfo())); $response->setContentType('application/json', 'UTF-8'); //Return the response return $response; }
public static function list_event(Inputter $inputter, JSONOutputter $outputter) { // List for event // // Verify input // $required_dictionary = array('event_identification' => ''); $inputter->validate_input($required_dictionary, null); // Validate // $event_id = $inputter->variables_array['event_identification']; $event_error = null; UniversallyUniqueIdentifier::propertyIsValid('rawIdentifier', $event_id, $event_error); if (isset($event_error)) { $outputter->print_error($event_error); } // Event ID // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string = 'MATCH (occurrence:EventSpaceTimeOccurrence)-[:event]-(event:Event), (occurrence)-[:location]-(location:Location), (occurrence)-[:confined_date]-(confinedDate:ConfinedDate), (occurrence)-[:attendees_range]-(attendeesRange:Range) ' . 'WHERE event.' . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $event_id . "' " . 'RETURN occurrence, location, confinedDate, attendeesRange'; $query = new Everyman\Neo4j\Cypher\Query($client, $query_string); $result = $query->getResultSet(); if (count($result) > 0) { $event_occurrence_prints = array(); foreach ($result as $row) { $event_occurrence_print = EventSpaceTimeOccurrence::printer_dictionary($row['occurrence']); $event_occurrence_print[SPACE_TIME_OCCURRENCE_RELATIONSHIP_NAME_LOCATION] = Location::printer_dictionary($row['location']); $event_occurrence_print[SPACE_TIME_OCCURRENCE_RELATIONSHIP_NAME_CONFINED_DATE] = ConfinedDate::printer_dictionary($row['confinedDate']); $event_occurrence_print[EVENT_SPACE_TIME_OCCURRENCE_RELATIONSHIP_NAME_RANGE] = Range::printer_dictionary($row['attendeesRange']); array_push($event_occurrence_prints, $event_occurrence_print); } // Print data // $outputter->print_data($event_occurrence_prints); } else { // Throw error, user doesn't exists // $error = Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_ENTITY_DOES_NOT_EXIST, 'No Event Occurrences for Event with identification ' . $event_id . ' does not exist.'); $outputter->print_error($error); } }
Neo4jPHP version {$meta['version']} {$_SERVER['argv'][0]} [-help|-license|-readme|-version|<host>] <port> -help Display help text -license Display software license -readme Display README -version Display version information <host> (<port>) Test connection to Neo4j instance on host (port defaults to 7474) HELP; } else { if ($command == '-license') { echo file_get_contents('phar://neo4jphp.phar/LICENSE') . "\n\n"; } else { if ($command == '-readme') { echo file_get_contents('phar://neo4jphp.phar/README.md') . "\n\n"; } else { if ($command == '-version') { echo "Neo4jPHP version {$meta['version']}\n\n"; } else { $port = empty($_SERVER['argv'][2]) ? 7474 : $_SERVER['argv'][2]; $client = new Everyman\Neo4j\Client($command, $port); print_r($client->getServerInfo()); } } } } exit(0); } __halt_compiler();
function main() { require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client('localhost', 7474); print_r($client->getServerInfo()); }
///////////////// Password protect //////////////////////////////////////////////////////////////// if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != ADMIN_USERNAME || $_SERVER['PHP_AUTH_PW'] != ADMIN_PASSWORD) { Header("WWW-Authenticate: Basic realm=\"Neo4j Login\""); Header("HTTP/1.0 401 Unauthorized"); echo <<<EOB \t\t\t\t<html><body> <h1>Rejected!</h1> <big>Wrong Username or Password!</big> </body></html> EOB; exit; } try { // require ('phar://neo4jphp.phar'); require __DIR__ . '/../application/vendor/neo4jphp/bootstrap.php'; $client = new \Everyman\Neo4j\Client('10.1.242.125', 7474); $server_info = $client->getServerInfo(); echo 'neo4j version = ' . $server_info['neo4j_version']; $result = ''; } catch (\Everyman\Neo4j\Exception $e) { $result = $e->getTraceAsString(); echo str_replace("\n", '<br/>', print_r($result, true)); } echo '<hr />'; $output = ''; if ($_POST && !empty($_POST['query'])) { try { $result = array(); $_POST['query'] = trim($_POST['query']); $query = new \Everyman\Neo4j\Cypher\Query($client, $_POST['query']); $res = $query->getResultSet();
<?php require 'vendor/autoload.php'; require 'rb.php'; R::setup('mysql:host=localhost;dbname=chai-crm', 'chai-crm', '6TWe9K7NPzT6jNDP'); R::freeze(TRUE); $client = new Everyman\Neo4j\Client(); $client->getTransport()->setAuth('neo4j', 'neo4j'); // Get all nodes : AKA Tables $nodeNames = array(); foreach ($client->GetLabels() as $label) { $node = $label->getName(); if ($node[0] != "_") { $nodeNames[] = $node; } } // Get each nodes properties foreach ($nodeNames as $nodeName) { $queryString = "MATCH (n:`" . $nodeName . "`) return count(n) as count"; $query = new Everyman\Neo4j\Cypher\Query($client, $queryString); $result = $query->getResultSet(); $count = 0; foreach ($result as $row) { $count = $row["count"]; } echo "Total Count for {$nodeName}: {$count} \n"; $mysql_count = 0; try { $mysql_count = R::count($nodeName); } catch (Exception $e) { echo "Records do not exist for {$nodeName} in MySQL\n";
public static function unauthenticate(Inputter $inputter, JSONOutputter $outputter) { // Unauthenticate // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); }
use GraphStory\GraphKit\Exception\JsonResponseEncodingException; use GraphStory\GraphKit\Neo4jClient; use GraphStory\GraphKit\Model\Content; use GraphStory\GraphKit\Model\User; use GraphStory\GraphKit\Service\ContentService; use GraphStory\GraphKit\Service\UserService; use GraphStory\GraphKit\Slim\JsonResponse; use GraphStory\GraphKit\Slim\Middleware\Navigation; use Monolog\Handler\StreamHandler; use Monolog\Logger; use Slim\Middleware\SessionCookie; use Slim\Mustache\Mustache; use Slim\Slim; if (getenv('SLIM_MODE') !== 'test') { $neo4jClient = new \Everyman\Neo4j\Client($config['graphStory']['restHost'], $config['graphStory']['restPort']); $neo4jClient->getTransport()->setAuth($config['graphStory']['restUsername'], $config['graphStory']['restPassword']); if ($config['graphStory']['https']) { $neo4jClient->getTransport()->useHttps(); } // neo client Neo4jClient::setClient($neo4jClient); } $app = new Slim($config['slim']); $app->container->singleton('logger', function () use($config) { $logger = new Logger('graph-kit'); $logger->pushHandler(new StreamHandler($config['logging']['logFile'], $config['logging']['logLevel'])); return $logger; }); $app->jsonResponse = function () use($app) { return new JsonResponse($app->response);
require_once "./HumanNameParser/init.php"; require_once 'databaseConfig.php'; require_once 'URLParser.php'; use Everyman\Neo4j\Cypher\Query; function findIfProfessor($title_str, $keywords = array("Professor", "Prof")) { //@Debug echo "\nThe title is: {$title_str}\n"; foreach ($keywords as $k) { if (($found = stripos($title_str, $k, 0)) !== false) { return 1; } } return 0; } $client = new Everyman\Neo4j\Client('localhost', 7474); $client->getTransport()->setAuth('neo4j', 'muresearch'); $q = "match (u:Person) return u.name as name"; $query = new Query($client, $q); $result = $query->getResultSet(); $mysqli = new mysqli(HOSTNAME, USERNAME, PASSWD, DATABASE); if ($mysqli->connect_errno) { die("error: " . $mysqli->connect_error); } $localTable = "MOSpacePeople"; $transaction = $client->beginTransaction(); foreach ($result as $r) { $parser = new HumanNameParser_Parser($r['name']); $last = $parser->getLast(); $first = $parser->getFirst(); //@Debug
/** * Convert a string into a Neo4j Label. * * @param string $label * @return Everyman\Neo4j\Label */ public function makeLabel($label) { return $this->client->makeLabel($label); }
<?php require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client(); $client->getTransport()->setAuth('neo4j', 'neo4j'); $nodes = array(); // Get customer count $queryString = "MATCH (n:`SalesCall` { status: 'new' }) OPTIONAL MATCH n-[r]-() DELETE n,r;"; $query = new Everyman\Neo4j\Cypher\Query($client, $queryString); $result = $query->getResultSet(); print_r($result);
<?php require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client('localhost', 7474); $client->getTransport()->setAuth('neo4j', 'soulmate'); print_r($client->getServerInfo());
public static function create(Inputter $inputter, JSONOutputter $outputter) { // Create // // 1) Test all data is available and valid // // Availability // $required_keys = array(LOCATION_KEY_COORDINATE_LATITUDE => '', LOCATION_KEY_COORDINATE_LONGITUDE => ''); $optional_dictionary = array(UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION => uniqid(), UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_CREATED => date('c'), UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_UPDATED => date('c')); // Validate input // $inputter->validate_input($required_keys, $optional_dictionary); // Valid // $creation_error = null; // Location // Location::isValid($inputter->variables_array, false, $creation_error); // Print error // if (isset($creation_error)) { $outputter->print_error($creation_error); return; } // 2) Check request we want to process CAN go ahead // // Location identification must not exist // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string_check_location = "MATCH (uniqueObject:UniversallyUniqueObject) " . "WHERE uniqueObject." . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array[UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION] . "' " . "RETURN uniqueObject"; $query_check_location = new Everyman\Neo4j\Cypher\Query($client, $query_string_check_location); $result_check_location = $query_check_location->getResultSet(); if ($result_check_location->count() > 0) { // Location identification exists // $identification_exists = Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_ENTITY_EXISTS, 'Identifier is not unique.'); $outputter->print_error($identification_exists); } // 3) We've got the go ahead to process the request as it's intended - create a new user in the data store // // Location // $location_to_create = $client->makeNode(); $location_to_create->setProperty(UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION, $inputter->variables_array[UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION]); $location_to_create->setProperty(UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_CREATED, $inputter->variables_array[UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_CREATED]); $location_to_create->setProperty(UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_UPDATED, $inputter->variables_array[UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_UPDATED]); $location_to_create->setProperty(LOCATION_KEY_COORDINATE_LATITUDE, $inputter->variables_array[LOCATION_KEY_COORDINATE_LATITUDE]); $location_to_create->setProperty(LOCATION_KEY_COORDINATE_LONGITUDE, $inputter->variables_array[LOCATION_KEY_COORDINATE_LONGITUDE]); $location_to_create->save(); // Add labels // $location_label_objects = array(); foreach (Location::labels() as $name) { array_push($location_label_objects, new Everyman\Neo4j\Label($client, $name)); } if (count($location_label_objects) > 0) { $location_to_create->addLabels($location_label_objects); } // 4) Output results // $outputter->print_data(array(Location::printer_dictionary($location_to_create))); }
<?php // connection to neo4j require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client('localhost', 7474); $label = $client->makeLabel('artist'); $file = fopen("./database/artists.dat", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reache $i = 0; while (!feof($file)) { $line = fgets($file); $atributes = explode("\t", $line); //echo "id = " . $atributes[0] ."\n"; //echo "name = " . $atributes[1] ."\n"; //echo "url = " . $atributes[2] ."\n"; // is_null switch (count($atributes)) { case 0: echo "Linea sin registros\n"; // Do Nthing break; case 1: // Do nothing break; case 2: // Only add Artist with id and name $id = $atributes[0]; $name = $atributes[1]; $artist = $client->makeNode(); $artist->setProperty('id', $id)->setProperty('name', $name)->save(); //$artistId = $artist->getId();
<?php // Load the relation user friend // userID friendID // 2 275 // 2 428 // 2 515 // connection to neo4j require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client('localhost', 7474); $file = fopen("./database/user_friends.dat", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reache $i = 0; while (!feof($file)) { $line = fgets($file); $atributes = explode("\t", $line); switch (count($atributes)) { case 0: // Do Nothing break; case 1: // Do nothing break; case 2: // create the relation add_friend_to $id1 = (int) trim($atributes[0]); $id2 = (int) trim($atributes[1]); //echo "Lee ". $id1 . " a friend of ". $id2 ."\n"; $userId1 = 0; $userId2 = 0; $queryString = "match (n:user {id: {id}}) return n";
public static function destroy(Inputter $inputter, JSONOutputter $outputter) { // Create // // 1) Test all data is available and valid // // Availability // $required_dictionary = array('user_identification' => '', 'user_to_unfollow_identification' => ''); $inputter->validate_input($required_dictionary, null); // Valid // // Identifiers // $validation_error = null; UniversallyUniqueObject::propertyIsValid(UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION, $inputter->variables_array['user_identification'], $validation_error); UniversallyUniqueObject::propertyIsValid(UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION, $inputter->variables_array['user_to_unfollow_identification'], $validation_error); if (isset($validation_error)) { $outputter->print_error($validation_error); } // Different // if ($inputter->variables_array['user_identification'] === $inputter->variables_array['user_to_unfollow_identification']) { $outputter->print_error(Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_INPUT_NOT_UNIQUE, 'Users cannot unfollow themselves.')); } // 2) Check request we want to process CAN go ahead // // Identification should exist // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string_check_object = 'MATCH (object:AttendingUser) ' . 'WHERE object.' . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array['user_identification'] . "' " . 'RETURN object'; $query_check_object = new Everyman\Neo4j\Cypher\Query($client, $query_string_check_object); $result_check_object = $query_check_object->getResultSet(); if (!isset($result_check_object[0]['object'])) { // No user exists // $outputter->print_error(Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_ENTITY_DOES_NOT_EXIST, 'user_identification should be an existing user identification.')); } $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string_check_object = 'MATCH (object:CreatingUser) ' . 'WHERE object.' . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array['user_to_unfollow_identification'] . "' " . 'RETURN object'; $query_check_object = new Everyman\Neo4j\Cypher\Query($client, $query_string_check_object); $result_check_object = $query_check_object->getResultSet(); if (!isset($result_check_object[0]['object'])) { // No user_to_follow_identification exists // $outputter->print_error(Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_ENTITY_DOES_NOT_EXIST, 'user_to_unfollow_identification should be an existing user identification.')); } // Connection might exist // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string_check_connection = 'OPTIONAL MATCH (user:AttendingUser)-[following:' . ATTENDINGUSER_RELATIONSHIP_NAME_FOLLOW . ']->(user_to_unfollow:CreatingUser)-[follower: ' . CREATINGUSER_RELATIONSHIP_NAME_FOLLOWER . ']->(user) ' . 'WHERE user.' . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array['user_identification'] . "' AND user_to_unfollow." . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array['user_to_unfollow_identification'] . "' " . 'RETURN following, follower'; $query_check_connection = new Everyman\Neo4j\Cypher\Query($client, $query_string_check_connection); $result_check_connection = $query_check_connection->getResultSet(); if (!isset($result_check_connection[0]['following']) || !isset($result_check_connection[0]['follower'])) { // At least one object exists // $outputter->print_error(Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_RELATIONSHIP_EXISTS, 'Connection does not exist between users.')); } // 3) We've got the go ahead to process the request as it's intended - destroy the follow connection // // Get objects // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string_users = 'MATCH (user:AttendingUser)-[following:' . ATTENDINGUSER_RELATIONSHIP_NAME_FOLLOW . ']->(user_to_unfollow:CreatingUser)-[follower:' . CREATINGUSER_RELATIONSHIP_NAME_FOLLOWER . ']->(user) ' . 'WHERE user.' . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array['user_identification'] . "' AND user_to_unfollow." . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array['user_to_unfollow_identification'] . "' " . 'RETURN user, user_to_unfollow, following, follower'; $query_users = new Everyman\Neo4j\Cypher\Query($client, $query_string_users); $result_users = $query_users->getResultSet(); $user = $result_users[0]['user']; $user_to_unfollow = $result_users[0]['user_to_unfollow']; $following_relationship = $result_users[0]['following']; $follower_relationship = $result_users[0]['follower']; // Remove relationships // $following_relationship->delete(); $follower_relationship->delete(); // 4) Output results // // Print data // $outputter->print_data(array(array("user" => AttendingUser::printer_dictionary($user), "user_to_unfollow" => CreatingUser::printer_dictionary($user_to_unfollow)))); }
<?php require_once 'vendor/autoload.php'; use Everyman\Neo4j\Cypher\Query; $client = new Everyman\Neo4j\Client('localhost', 7474); $client->getTransport()->setAuth('neo4j', 'muresearch'); /* function findMaxNumCoauthoredPapers($client, $unifiedName){ $q = "match (u:Person {name: \"".$unifiedName."\"}) - [r:COAUTHORED] - (:Person) return max(r.numOfPapers) as num"; $query = new Query($client, $q); $result = $query->getResultSet(); foreach($result as $r){ return $r['num']; } } function findMaxNumPublication($client, $unifiedName){ $q = "match (u:Person {name: \"".$unifiedName."\"}) - [r:COAUTHORED] - (u2:Person) return u.publicationNum as maxMain,max(u2.publicationNum) as maxOthers"; $query = new Query($client, $q); $result = $query->getResultSet(); foreach($result as $r){ if($r['maxMain'] >= $r['maxOthers']){ return $r['maxMain']; } else{ return $r['maxOthers']; } }
<?php require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client('localhost', 7474); $label = $client->makeLabel('user'); for ($i = 2; $i <= 2100; $i++) { // reate the users for test (all the users have the same name: Thomas) $user = $client->makeNode(); $user->setProperty('id', $i)->setProperty('name', 'Thomas')->save(); $labels = $user->addLabels(array($label)); $userId = $user->getId(); //echo "User created with id: " . $bobId; }
<?php // connection to neo4j require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client('localhost', 7474); $label = $client->makeLabel('tag'); $file = fopen("./database/tags.dat", "r") or exit("Unable to open file!"); $log = fopen("./database/tags.log", "w") or exit("Unable to open file!"); //Output a line of the file until the end is reache $i = 0; while (!feof($file)) { $line = fgets($file); $atributes = explode("\t", $line); //echo "id = " . $atributes[0] ."\n"; //echo "name = " . $atributes[1] ."\n"; //echo "url = " . $atributes[2] ."\n"; // is_null switch (count($atributes)) { case 0: echo "Linea sin registros\n"; // Do Nothing break; case 1: // Do nothing break; case 2: // Create a tag node $id = (int) trim($atributes[0]); $name = (string) utf8_decode(trim($atributes[1])); fwrite($log, "Reading {$id} | {$name}\n"); if (!is_null($name) and !is_null($name)) {
public function insertDB($host, $port, $username, $auth, $custom_data = null) { require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client($host, $port); $client->getTransport()->setAuth($username, $auth); if (is_null($custom_data)) { $values = $this->crawlPubmed(); } else { $values = $custom_data; } //$values = array_merge($this->crawlPubmed(), $this->crawlIEEE()); //print_r($values); //return; if (!is_array($values) || !isset($values[0])) { print_r($values); die("something is wrong with the values"); } $transaction = $client->beginTransaction(); $neo4jQueryArray = array(); //$queryForCentralPerson = "merge (u:Person {name: \"".$this->lastName.", ".$this->firstName."\"}) set u.affiliation = \"".$this->affiliation."\""; //$query = new Query($client, $queryForCentralPerson); //$result = $transaction->addStatements($query); foreach ($values as $one) { //print_r($one) has the format: //[17] => Array //( // [title] => RNA-protein distance patterns in ribosomes reveal the mechanism of translational attenuation. // [url] => http://www.ncbi.nlm.nih.gov/pubmed/25326828 // [people] => Array // ( // [0] => Array // ( // [firstName] => DongMei // [lastName] => Yu // [affiliation] => Department of Biological Engineering, University of Missouri, Columbia, MO, 65211, USA. // ) // [1] => Array // ( // [firstName] => Chao // [lastName] => Zhang // [affiliation] => // ) // ) //) array_key_exists('title', $one) && !empty($one['title']) ? $articleTitle = $one['title'] : die("why the title has not been set?"); if (!array_key_exists('url', $one)) { $articleURL = ""; } else { $articleURL = $one['url']; } array_key_exists('people', $one) && is_array($one['people']) && isset($one['people'][0]) ? $articleAuthorList = $one['people'] : die("People list might be wrong"); $queryToCreatePublication = "merge (paper:Publication {title: \"" . addslashes($articleTitle) . "\"}) set paper.url = \"" . $articleURL . "\""; $neo4jQueryArray[] = new Query($client, $queryToCreatePublication); //$result = $transaction->addStatements($query); //$queryToCreateWroteRelation = "match (u:Person {name: \"". $this->lastName.", ".$this->firstName."\"}), (p:Publication {title: \"".addslashes($theTitle)."\"}) create unique (u)-[r:Wrote]->(p)"; //echo $queryToCreateWroteRelation."\n"; //$query = new Query($client, $queryToCreateWroteRelation); //$result = $transaction->addStatements($query); foreach ($articleAuthorList as $p) { if (!is_array($p) || !array_key_exists('firstName', $p) || !array_key_exists('lastName', $p) || !array_key_exists('affiliation', $p)) { die("Ariticle Author List format Error"); } if (empty($p['firstName']) || empty($p['lastName'])) { continue; } if (empty($p['affiliation'])) { $queryToCreatePerson = "merge (author:Person {name: \"" . $p['lastName'] . ", " . $p['firstName'] . "\"})"; } else { $queryToCreatePerson = "merge (author:Person {name: \"" . $p['lastName'] . ", " . $p['firstName'] . "\"}) set author.affiliation = \"" . addslashes($p['affiliation']) . "\""; } $neo4jQueryArray[] = new Query($client, $queryToCreatePerson); $queryToCreateWroteRelation = "match (u:Person {name: \"" . $p['lastName'] . ", " . $p['firstName'] . "\"}), (p:Publication {title: \"" . addslashes($articleTitle) . "\"}) create unique (u)-[r:Wrote]->(p)"; $neo4jQueryArray[] = new Query($client, $queryToCreateWroteRelation); $queryToAdjustNumOfPublication = "match (u:Person {name: \"" . $p['lastName'] . ", " . $p['firstName'] . "\"}) - [:Wrote] - (p) with u, count(distinct p) as num set u.publicationNum = num"; $neo4jQueryArray[] = new Query($client, $queryToAdjustNumOfPublication); //addMOProperty($p['lastName'].", ".$p['firstName'], $client); //should be after transition->commit() } for ($i = 0; $i < sizeof($articleAuthorList); $i++) { for ($j = $i + 1; $j < sizeof($articleAuthorList); $j++) { $queryToCreateCoauthoredRelation = "match (p:Publication), (u1:Person {name: \"" . $articleAuthorList[$i]['lastName'] . ", " . $articleAuthorList[$i]['firstName'] . "\"}), (u2:Person {name: \"" . $articleAuthorList[$j]['lastName'] . ", " . $articleAuthorList[$j]['firstName'] . "\"})\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere (u1)-[:Wrote]->(p) AND (u2)-[:Wrote]->(p) with count(p) as n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmatch (u1:Person {name: \"" . $articleAuthorList[$i]['lastName'] . ", " . $articleAuthorList[$i]['firstName'] . "\"}), (u2:Person {name: \"" . $articleAuthorList[$j]['lastName'] . ", " . $articleAuthorList[$j]['firstName'] . "\"})\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcreate unique (u1)-[r:COAUTHORED]-(u2) set r.numOfPapers = n"; //echo $queryToCreateCoauthoredRelation."\n"; $neo4jQueryArray[] = new Query($client, $queryToCreateCoauthoredRelation); //$result = $query->getResultSet(); //$result = $transaction->addStatements($query); } } } $transaction->addStatements($neo4jQueryArray, true); foreach ($values as $one) { array_key_exists('people', $one) && is_array($one['people']) && isset($one['people'][0]) ? $articleAuthorList = $one['people'] : die("People list might be wrong"); foreach ($articleAuthorList as $p) { if (!is_array($p) || !array_key_exists('firstName', $p) || !array_key_exists('lastName', $p) || !array_key_exists('affiliation', $p)) { die("Ariticle Author List format Error"); } if (empty($p['firstName']) || empty($p['lastName'])) { continue; } addMOProperty($p['lastName'] . ", " . $p['firstName'], $client); } } }
<?php // This script php implements // find all artists listened by a user’s friend but not the user, order them by the // number of friends listening to them, recommend the top 5 // Include library of functions include "functions.php"; // connection to neo4j require 'vendor/autoload.php'; $client = new Everyman\Neo4j\Client('localhost', 7474); printHeader(); printSearchForm($uid); echo "<b>User: {$uid} - All Artist Listened by my friends</b><br><br>"; $queryString = "MATCH (u:user {id:{$uid}})-[:ADD_FRIEND_TO]-(:user)-[listen: WEIGHT]-(a:artist)\r\nWHERE NOT (u)-[:WEIGHT]-(a)\r\nWITH a, count(u) as count\r\nRETURN a\r\nORDER BY count desc LIMIT 5"; $query = new Everyman\Neo4j\Cypher\Query($client, $queryString); $result = $query->getResultSet(); foreach ($result as $row) { $artist = $client->getNode($row['x']->getId()); $artistId = $artist->getProperty('id'); $artistName = $artist->getProperty('name'); echo "Artist Name: " . $artistName . "</br>"; printArtistInfo($artistId); ?> <form action="listen.php" method="post"> <input type="hidden" name="action" value="addlisten"> <input type="hidden" name="userId" value="<?php echo $uid; ?> "> <input type="hidden" name="artistId" value="<?php echo $artistId;
public static function list_invited(Inputter $inputter, JSONOutputter $outputter) { // List Invited // // Constants // $invited_user_identification = 'invited_user_identification'; // Verify input // $required_keys = array($invited_user_identification => ''); $inputter->validate_input($required_keys, null); // Validate input // $validate_error = null; UniversallyUniqueIdentifier::propertyIsValid('rawIdentifier', $inputter->variables_array[$invited_user_identification], $validate_error); if (isset($validate_error)) { $outputter->print_error($validate_error); } // Events // $client = new Everyman\Neo4j\Client('events.sb04.stations.graphenedb.com', 24789); $client->getTransport()->setAuth('Events', '3TP9LHROhv8LIcGmbYzq'); $query_string = 'MATCH (invitedUser:AttendingUser)-[:softInvitation]-(event:Event)-[:type]-(eventType:EventType) ' . 'WHERE invitedUser.' . UNIVERSALLY_UNIQUE_OBJECT_KEY_IDENTIFICATION . " = '" . $inputter->variables_array[$invited_user_identification] . "' " . 'RETURN invitedUser, event, eventType'; $query = new Everyman\Neo4j\Cypher\Query($client, $query_string); $result = $query->getResultSet(); $creator = $result[0]['invitedUser']; if (count($creator) > 0) { // Compare sent data is equal to data retrieved // $events_printer_dictionaries = array(); foreach ($result as $value) { $event_print = Event::printer_dictionary($value['event']); $event_print[EVENT_RELATIONSHIP_NAME_TYPE] = EventType::printer_dictionary($value['eventType']); $event_print[EVENT_RELATIONSHIP_NAME_CREATOR] = AttendingUser::printer_dictionary($value['invitedUser']); array_push($events_printer_dictionaries, $event_print); } // Print data // $outputter->print_data($events_printer_dictionaries); } else { // Throw error, user doesn't exists // $error = Error::withDomain(PRIVATE_EVENTS_REST_CONTROLLER_ERROR_DOMAIN, PRIVATE_EVENTS_REST_CONTROLLER_ERROR_CODE_ENTITY_DOES_NOT_EXIST, 'No such user with identification ' . $invited_user_identification . '.'); $outputter->print_error($error); } }