Wednesday, July 3, 2013

Cloudant search by indexes and set limit pagination


$cloudantLimit = 2;
$posts = array(
    "q" => "customerID:cid_100",
    "include_docs" => "true",
    "sort" => json_encode("-createdStamp"),
    "limit" => $cloudantLimit
);
$totalResult = array();
$bookmark = null;
$skip = 0;
while(true) {
    if($bookmark != null) {
        $posts["bookmark"] = $bookmark;
    }
    $loadMore = false;
    $result = getTransactionHistory($this->userName, $this->password, $posts);
    if($result != null && isset($result["code"]) && $result["code"] == 200 && isset($result["response"]) && strlen(trim($result["response"])) > 0) {
        $result200 = json_decode($result["response"]);
        if(isset($result200->total_rows)
            && isset($result200->bookmark)
            && isset($result200->rows) && is_array($result200->rows) && count($result200->rows) > 0) {
            $bookmark = $result200->bookmark;
            array_push($totalResult, $result["response"]);
            $skip = $skip + $cloudantLimit;
            if($result200->total_rows > $skip) {
                $loadMore = true;
            }
        }
    }
    if(!$loadMore) {
        break;
    }
}

function getTransactionHistory($userName, $password, $posts = null) {
    $headers[0] = "Authorization: Basic " . base64_encode("$userName:$password");
    $headers[1] = "Content-Type: application/json";

    return makeCurlCall(
        "https://$userName.cloudant.com/transactions/_design/views103/_search/animals",
        "GET",
        $headers,
        $posts
    );
}

function makeCurlCall($url, $method = "GET", $headers = null, $gets = null, $posts = null) {
    $ch = curl_init();
    if($gets != null)
    {
        $url.="?".(http_build_query($gets));
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    if($posts != null)
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    }
    if($method == "POST") {
        curl_setopt($ch, CURLOPT_POST, true);
    } else if($method == "PUT") {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    } else if($method == "HEAD") {
        curl_setopt($ch, CURLOPT_NOBODY, true);
    }
    if($headers != null && is_array($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    curl_close($ch);
    return array(
        "code" => $code,
        "response" => $response
    );
}

No comments:

Post a Comment