Skip to content

Commit

Permalink
added RAM caching of queries
Browse files Browse the repository at this point in the history
  • Loading branch information
Koushik Biswas committed May 29, 2017
1 parent 2d28783 commit 7d86a42
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions calldatastore.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,48 @@

try
{
$mem = new Memcached();
$mem->addServer("127.0.0.1", 11211);

$projectId = 'triple-cab-162115';
$datastore = new DatastoreClient([
'projectId' => $projectId
]);

echo 'Matches:<br/>';
$matches_string = "";

//Get the string typed in by user for autocompletion...
$queryval = $_GET['searchtext'];

//If it is not blank...
if ($queryval[0]) {
$upperlimit = $queryval . json_decode('"\ufffd"');
$query = $datastore->query()
->kind('SKU')
->filter('name', '>=', $queryval)
->filter('name', '<', $upperlimit)
->order('name');
$result = $datastore->runQuery($query);
foreach ($result as $SKU) {
echo $SKU['name'];
echo '<br/>';

//we first have to check our local cache if we have the results for this query...
$cache_hit = $mem->get($queryval);
if ($cache_hit) {

//yes! we have it it cache, no need to go back to datastore...
$matches_string = (string) $cache_hit;
} else {

//cache miss, let us go to datastore and fetch the result...
$upperlimit = $queryval . json_decode('"\ufffd"');
$query = $datastore->query()
->kind('SKU')
->filter('name', '>=', $queryval)
->filter('name', '<', $upperlimit)
->order('name');
$result = $datastore->runQuery($query);
foreach ($result as $SKU) {
$matches_string = $matches_string . $SKU['name'] . "<br/>";
}

//finally, let us insert this query result in our local cache so that next time,
//we do not have to make a round-trip to datastore - note that we are caching for 1 day
$mem->set($queryval, $matches_string, 86400);
}
echo $matches_string;
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
Expand Down

0 comments on commit 7d86a42

Please sign in to comment.