Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
USING RIAK WITH PHP
    Front Range PHP Users Group - May 12th, 2010
           Jon Meredith - Basho Technologies
        ...
RIAK BY EXAMPLE


• URL   Shortener Example in PHP (thx Sean Cribbs)

• Creates   a short URL that redirects to the real t...
<html>
            SUBMIT-TO-SELF FORM
<h1>URL Shortener</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];...
ON POST
<?php
include_once "riak.php";
// snip...

// Responding to a post
} elseif (isset($_POST['url'])) {
	 $url = $_PO...
ON GET
if ($_SERVER["REQUEST_METHOD"] == 'GET' and
    isset($_SERVER["PATH_INFO"])) {
	 $client = new RiakClient('localho...
STUPID COLLISION PRONE SHORTENER
                 DO NOT USE



// cheap and cheerful shortener - takes hash with crc32,
/...
SHTN DEMO
RIAK & PHP


• PHP    client http://bitbucket.org/basho/riak-php-client

• Uses   Riak’s RESTful HTTP interface

• Pure   ...
RIAK PHP API


• RiakClient   - a connection to a single server

• RiakBucket   - access to bucket properties/objects stor...
RIAK MATH

•N     - number of replicas

•R   - number of reads

•W     - number of writes

• DW     - durable writes

• As...
RIAKCLIENT CLASS

• Create   connection to a server
 $client = new RiakClient(HOST, PORT);
 assert($client->isAlive());


...
RIAK BUCKETS

• Buckets   group related keys together.

• Finest   level you can configure Riak at

  •n   value - number o...
RIAKBUCKET CLASS


• Retrieve       objects
 $obj1   =   $bucket->get("missing");
 $obj1   =   $bucket->get("missing", $rV...
MORE RIAKBUCKET


• Modify   bucket properties
 $bucket->getAllowMultiples();   $bucket->setAllowMultiples(TRUE);
 $bucket...
RIAK OBJECTS

• RiakObjects     hold bucket name, keys, values and metadata.

• Metadata    includes content type and link...
RIAKOBJECT CLASS


• Access   key/data/metadata
 $object->getKey(); $object->getBucket();
 $object->getContentType(); $obj...
MORE RIAKOBJECT

• Store   on server
 $obj->store();



• Reload   from server
 $obj->reload();



• Delete   from server
...
LINKS

•A  Link store a one-way relationship between two objects,
 similar to a hyperlink.

•A   link is a bucket & key pl...
LINKS EXAMPLE

people/alice                    vip/claire
                    friend




               [no tag]      [no ...
CREATING LINKS

• Create   objects with some links
 $people = $client->bucket('people');
 $vips = $client->bucket('vips');...
LINK WALKING
• Walk   the links
 $resultObjects = $object->link($bucket='_', $tag='_', $keep=FALSE);
 $bucket - match on a...
LINK WALKING DEMO



• http://github.com/schofield/riak_php_app

• Created   by Grant Schofield, Developer Advocate @ Basho
RIAK MAP/REDUCE

• Map/Reduce     allows you to query Riak

• Map   function selects/transforms data you want

• Reduce   ...
MAP/REDUCE EXAMPLE

$bucket->newObject("foo", 2)->store();
$bucket->newObject("bar", 3)->store();
$bucket->newObject("baz"...
SUPPLY YOUR OWN MAPS
•   Javascript map functions get passed an object
    {
     "bucket":BucketAsString,
     "key":KeyA...
RETURNS KEYS WITH SPACES
   $map = "function(obj) {
       if (obj.key.indexOf(' ') == -1) {
           return [obj.key];
...
SUPPLY YOUR OWN REDUCE
  $reduceMax = "function(values, arg) {
        values.sort().reverse();
        return [values[0]]...
OVER TO YOU...


• Website    http://riak.basho.com

• Mailing   list riak-users@basho.com

• #riak   on FreeNode

• Twitt...
Nächste SlideShare
Wird geladen in …5
×

PHP API

Overview of the PHP API for Riak given at the FrontRange PHP User Group May 2010

  • Als Erste(r) kommentieren

PHP API

  1. 1. USING RIAK WITH PHP Front Range PHP Users Group - May 12th, 2010 Jon Meredith - Basho Technologies jmeredith@basho.com / @jon_meredith
  2. 2. RIAK BY EXAMPLE • URL Shortener Example in PHP (thx Sean Cribbs) • Creates a short URL that redirects to the real thing • Demonstrates buckets, get and put.
  3. 3. <html> SUBMIT-TO-SELF FORM <h1>URL Shortener</h1> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> URL <input type="text" name="url" size="60" value="<?php echo $url; ?>"> <input type="submit" name="submit" value="Shtn!"><br/> <?php if (isset($shtn)) { $surl = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]"+ "$_SERVER[PHP_SELF]/$shtn"; echo "Shortened <a href='$surl'>$surl</a><br/>"; } if (isset($notice)) { echo "<em>$notice</em><br/>"; } ?> </form> </html>
  4. 4. ON POST <?php include_once "riak.php"; // snip... // Responding to a post } elseif (isset($_POST['url'])) { $url = $_POST['url']; $shtn = shorten($url); $client = new RiakClient('localhost', 8098); $bucket = $client->bucket('shtn'); $object = $bucket->newBinary($shtn, $url, 'text/plain'); $object->store(); } ?>
  5. 5. ON GET if ($_SERVER["REQUEST_METHOD"] == 'GET' and isset($_SERVER["PATH_INFO"])) { $client = new RiakClient('localhost', 8098); $bucket = $client->bucket('shtn'); $path_els = explode('/', $_SERVER["PATH_INFO"]); $key = $path_els[1]; $obj = $bucket->getBinary($key); if ($obj->exists()) { $lurl = $obj->getData(); header("Location: $lurl"); exit; } else { $notice = "Unknown redirect for $key"; } }
  6. 6. STUPID COLLISION PRONE SHORTENER DO NOT USE // cheap and cheerful shortener - takes hash with crc32, // converts to base64 and trims non a-zA-Z0-9 characters function shorten($url) { $hash = hash("crc32", $url, true); $str = base64_encode($hash); return preg_replace('/[^a-zA-Z0-9]/', '', $str); }
  7. 7. SHTN DEMO
  8. 8. RIAK & PHP • PHP client http://bitbucket.org/basho/riak-php-client • Uses Riak’s RESTful HTTP interface • Pure PHP - requires the cURL module to be installed
  9. 9. RIAK PHP API • RiakClient - a connection to a single server • RiakBucket - access to bucket properties/objects stored • RiakObject - a key/value/metadata object
  10. 10. RIAK MATH •N - number of replicas •R - number of reads •W - number of writes • DW - durable writes • As long as R+W > N you read your writes
  11. 11. RIAKCLIENT CLASS • Create connection to a server $client = new RiakClient(HOST, PORT); assert($client->isAlive()); • Create a RiakBucket object $bucket = $client->bucket('bucket'); • Get/Change Defaults $client->getR(); $client->getW(); $client->getDW(); $client->setR(1); $client->setW(3); client->setDW(1); $
  12. 12. RIAK BUCKETS • Buckets group related keys together. • Finest level you can configure Riak at •n value - number of replicas • allow_mult - return conflicts to client • r/w/dw - successful reads/writes/durable writes
  13. 13. RIAKBUCKET CLASS • Retrieve objects $obj1 = $bucket->get("missing"); $obj1 = $bucket->get("missing", $rVal); $obj2 = $bucket->getBinary('foo2'); $obj2 = $bucket->getBinary('foo2', $rVal); • Create Objects $obj1 = bucket->newObject('foo', $structuredData); $obj2 = $bucket->newBinary('foo1', $binaryData);
  14. 14. MORE RIAKBUCKET • Modify bucket properties $bucket->getAllowMultiples(); $bucket->setAllowMultiples(TRUE); $bucket->getNVal(); $bucket->setNVal(3); • Modify per-bucket defaults $bucket->getR(); $bucket->getW(); $bucket->getDW(); $bucket->setR(1); $bucket->setW(3); bucket->setDW(1); $
  15. 15. RIAK OBJECTS • RiakObjects hold bucket name, keys, values and metadata. • Metadata includes content type and links. • By default objects serialize using JSON ... can prevent using ‘binary’ objects $bucket->getBinary($key); $bucket->newBinary($key);
  16. 16. RIAKOBJECT CLASS • Access key/data/metadata $object->getKey(); $object->getBucket(); $object->getContentType(); $object->getLinks(); $object->getData(); • Change data/metadata $object->setContentType(); $object->setData(); $object->addLink($obj2,$tag); $object->removeLink($obj2, $tag);
  17. 17. MORE RIAKOBJECT • Store on server $obj->store(); • Reload from server $obj->reload(); • Delete from server $obj->delete(); • Clear contents data/metadata (but not bucket/key/vclock) $obj->clear();
  18. 18. LINKS •A Link store a one-way relationship between two objects, similar to a hyperlink. •A link is a bucket & key plus a user-supplied tag. • Objects can have multiple links. • Riak supports link walking - server side - match on bucket or tag
  19. 19. LINKS EXAMPLE people/alice vip/claire friend [no tag] [no tag] friend friend people/bob people/dean Images http://www.openclipart.org
  20. 20. CREATING LINKS • Create objects with some links $people = $client->bucket('people'); $vips = $client->bucket('vips'); $alice = $people->newObject("alice", array(name => 'Alice'))->store(); $bob = $people->newObject("bob", array(name => 'Bob'))->store(); $claire = $vip->newObject("claire", array(name => 'Claire'))-> addLink($alice, 'friend')-> store(); $dean = $people->newObject("dean", array(name => 'Dean'))-> addLink($alice)-> addLink($bob, 'friend')-> addLink($claire, 'friend')-> addLink($claire)-> store();
  21. 21. LINK WALKING • Walk the links $resultObjects = $object->link($bucket='_', $tag='_', $keep=FALSE); $bucket - match on a bucket name, '_' matches all $tag - match on a link tag, '_' matches all $keep - return results - last link always TRUE. • Examples // Dean’s links array of $alice, $bob, $claire, $claire (duplicate) $deans_links = $dean->link('_')->run(); // Dean’s friends array of $bob, $claire $deans_friends = $dean->link('_','friend')->run(); // Dean’s VIPs array of $claire $deans_vips = $dean->link('vip’)->run(); // Friends of Dean’s friends array of $alice $deans_fofs = $dean->link('_','friend')->link('_','friend')->run(); // friends within 2 degrees of separation - array(array($bob, $claire), $alice) $deans_2degs = $dean->link('_','friend', TRUE)->link('_','friend', TRUE)->run();
  22. 22. LINK WALKING DEMO • http://github.com/schofield/riak_php_app • Created by Grant Schofield, Developer Advocate @ Basho
  23. 23. RIAK MAP/REDUCE • Map/Reduce allows you to query Riak • Map function selects/transforms data you want • Reduce function combines the output of the map function • Provide your own functions (in erlang or javascript) or use the builtins
  24. 24. MAP/REDUCE EXAMPLE $bucket->newObject("foo", 2)->store(); $bucket->newObject("bar", 3)->store(); $bucket->newObject("baz", 4)->store(); # Run the map... $result = $client-> add($bucket->name)-> map("Riak.mapValuesJson") -> reduce("Riak.reduceSum")-> run(); test_assert($result == array(9));
  25. 25. SUPPLY YOUR OWN MAPS • Javascript map functions get passed an object { "bucket":BucketAsString, "key":KeyAsString, "vclock":VclockAsString, "values":[{"metadata":{"X-Riak-VTag":VtagAsString, "X-riak-Last-Modified":LastModAsString, ...other metadata... }, "data":ObjectData }, ...other metadata/data values (siblings)...] } • Returns an array of results
  26. 26. RETURNS KEYS WITH SPACES $map = "function(obj) { if (obj.key.indexOf(' ') == -1) { return [obj.key]; } else { return []; } }"; $result = $client-> add($bucket->name)-> map($map) -> reduce("Riak.reduceSort")-> run();
  27. 27. SUPPLY YOUR OWN REDUCE $reduceMax = "function(values, arg) { values.sort().reverse(); return [values[0]]; }"; $result = $client-> add($bucket->name)-> map("Riak.mapValuesJson") -> reduce($reduceMax)-> run();
  28. 28. OVER TO YOU... • Website http://riak.basho.com • Mailing list riak-users@basho.com • #riak on FreeNode • Twitter @basho (and it follows our devs)

×