Showing posts with label Cloudant. Show all posts
Showing posts with label Cloudant. Show all posts

Wednesday, July 3, 2013

Cloudant built in function for sum count and stats


Built-in reduces

While you can define your own reduce functions, it's often the case that your reduce is going to be doing a simple count or sum operation. There are a handful of built in reduce functions; _sum, _count and _stats. If you can use these functions you should - they're faster than a javascript reduce (since they avoid serialisation between erlang and javascript) and are very well tested.
_sum
Produces the sum of all values for a key, values must be numeric
_count
Produces the row count for a given key, values can be any valid json
_stats
Produces a json structure containing sum, count, min, max and sum squared, values must be numeric
To use a built-in reduce, just put its name in place of the javascript reduce function inside your view.

{
    "_id": "_design/views103",
    "_rev": "8-1798b34c9929eb36d3bc04f99d2b5445",
    "indexes": {
        "animals": {
            "index":
                "function(doc){\n
                    index(\"default\", doc._id);\n\n
                    if (doc['customerID']){\n    index(\"customerID\", doc['customerID'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['trxnStatus']){\n    index(\"trxnStatus\", doc['trxnStatus'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['createdStamp']){\n    index(\"createdStamp\", doc['createdStamp'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['paymentType']){\n    index(\"paymentType\", doc['paymentType'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['returnAmount']){\n    index(\"returnAmount\", doc['returnAmount'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['trxnNumber']){\n    index(\"trxnNumber\", doc['trxnNumber'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['trxnReference']){\n    index(\"trxnReference\", doc['trxnReference'], {\"store\": \"yes\"});\n  }\n\n
                    if (doc['authCode']){\n    index(\"authCode\", doc['authCode'], {\"store\": \"yes\"});\n
                }\n\n
            }"
        }
    },
    "views": {
        "returnAmount_sum": {
            "map": "function(doc) {\n  if(doc.returnAmount && doc.customerID){\n    emit(doc.customerID, doc.returnAmount);\n  }\n}",
            "reduce": "function (keys, values, rereduce) {\nreturn (values);\n}"
        }
    }
}
https://pritom.cloudant.com/transactions/_design/views103/_view/returnAmount_sum
https://cloudant.com/for-developers/views/#pageArea 
{
  "_id": "_design/name",
  "views": {
    "view1": {
      "map":"function(doc){emit(doc.field, 1)}",
      "reduce": "function(key, value, rereduce){return sum(values)}"
    }
  }
}

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
    );
}

Sunday, June 30, 2013

Cloudant create view and used indexes to search values

Create a document using : "_design/views103" (After selecting a database).
Enter "indexes" as key.
Enter following content after converting as JSON to value field:

{
    "search_name": {
        "index": 
          "function(doc) {
            index("default", doc._id);
            if (doc['customerID']) {
                index("customerID", doc['customerID'], {"store": "yes"});
            }
        }"
    }
}

_id automatically used as index.

https://{name}.cloudant.com/animaldb/_design/views103/_search/animals?q={id}
Wild card searches are supported, for both single (?) and multiple (*)
character searches. dat? would match date and data, dat* would match date,
data, database, dates etc. Wildcards must come after a search term, you cannot
do a query like *base.



customerID is a key field in data object.
https://{name}.cloudant.com/transactions/_design/views103/_search/animals?q=customerID:%228547963512%22

https://cloudant.com/for-developers/views/
https://cloudant.com/for-developers/search/

With this index you can run any of these queries.
Desired resultQuery
Birds class:bird
Animals that begin with the letter "l" l*
Carnivorous birds class:bird AND diet:carnivore
Herbivores that start with letter "l" l* AND diet:herbivore
Medium-sized herbivores min_length:[1 TO 3] AND diet:herbivore
Herbivores that are 2m long or less diet:herbivore AND min_length:[-Infinity TO 2]
Mammals that are at least 1.5m long class:mammal AND min_length:[1.5 TO Infinity]
Find "Meles meles" latin_name:"Meles meles"
Mammals who are herbivore or carnivore diet:(herbivore OR omnivore) AND class:mammal