Code Examples

JSON Example

The following query looks for French and Asian restaurants where cigars are welcome, the price is around $20 but no more than $35, and the location is around (-123.021, 23.4512). Also specified is the weight of the feature dimension which has been reduced to half the weight of the other dimensions:

Note that the values specified for each non-scalar dimension (in this case “french”, “asian”, and “cigars welcome”) should correspond to the elements specified in the dimension definition.

{
  "startIndex": 0,
  "pageSize": 20,
  "criteria": [
    {
      "dimension": "cuisine",
      "value": ["french", "asian"]
    },
    {
      "dimension": "feature",
      "value": "cigars welcome",
      "weight": 0.5
    },
    {
      "dimension": "geoloc",
      "latitude": -123.021,
      "longitude": 23.4512
    },
    {
      "dimension": "price",
      "value": 20,
      "max": 35
    }
  ]
}

PHP Example

The following example is based upon a Transparensee tutorial site for real estate using this web.config.ini file:

[AppSettings]
discoveryEngineUrl=http://localhost:8090
discoveryQueryPath=/ws/query

Code for the PHP controller:

<?php
require("t11e_utils.php");

error_reporting(E_WARNING);

$pageSize = 10;
$startIndex = 0;

if (array_key_exists("page", $_GET)) {
     $page = (int)  $_GET["page"];
     $startIndex = ($page - 1) * $pageSize;
}

$drillDown = array(
    array("dimension" => "bath"),
    array("dimension" => "bedroom"),
    array("dimension" => "condition"),
    array(
        "dimension" => "style",
        "ids" => array(
            "multi-family", "apartment", "condo", "co-op", "townhome",
            "single-family", "colonial", "new england", "cape cod",
            "classical", "federal", "greek revival", "tidewater",
            "antebellum", "victorian", "gothic", "second empire",
            "queen anne", "contemporary", "ranch", "raised ranch",
            "split-level", "bauhaus", "art moderne", "transitional"
        )
    )
);

$criteria = array();

if (array_key_exists("type", $_GET)) {
    $criteria[] = array(
        "dimension" => "type",
        "value" => $_GET["type"]
    );
} else {
    $criteria[] = array(
        "dimension" => "type",
        "value" => array("sales","rentals")
    );
}

if (array_key_exists("bath", $_GET)) {
    $criteria[] = array(
        "dimension" => "bath",
        "value" => $_GET["bath"]
    );
}

if (array_key_exists("bedroom", $_GET)) {
    $criteria[] = array(
        "dimension" => "bedroom",
        "value" => $_GET["bedroom"]
    );
}

if (array_key_exists("style", $_GET)) {
    $criteria[] = array(
        "dimension" => "style",
        "id" => $_GET["style"]
    );
}

if (array_key_exists("price_min", $_GET) ||
    array_key_exists("price_max", $_GET)) {
    $value = array("[");
    if (array_key_exists("price_min", $_GET)) {
        $value[] = $_GET["price_min"];
    };
    $value[] = ",";
    if (array_key_exists("price_max", $_GET)) {
        $value[] = $_GET["price_max"];
    };
    $value[] = "]";
    $criteria[] = array(
        "dimension" => "price",
        "value" => implode($value,"")
    );
}

if (array_key_exists("lease_min", $_GET) ||
    array_key_exists("lease_max", $_GET)) {
    $value = array("[");
    if (array_key_exists("lease_min", $_GET)) {
        $value[] = $_GET["lease_min"];
    };
    $value[] = ",";
    if (array_key_exists("lease_max", $_GET)) {
        $value[] = $_GET["lease_max"];
    };
    $value[] = "]";
    $criteria[] = array(
        "dimension" => "lease",
        "value" => implode($value,"")
    );
}

$request = array(
    "startIndex" => $startIndex,
    "pageSize" => $pageSize
);

if (!empty($criteria)) {
    $request["criteria"] = $criteria;
}

if (!empty($drillDown)) {
    $request["drillDown"] = $drillDown;
}

try {
    $queryUrl = $t11e_AppSettings["discoveryEngineUrl"]
        .$t11e_AppSettings["discoveryQueryPath"];

    echo T11e_Utils::t11e_query($queryUrl, $request);
}
catch (Exception $e)
{
    echo $e;
}

?>

Code for t11e_utils.php:

<?php

error_reporting('E_WARNING');

   class T11e_Utils
   {
     public static function t11e_query($url, $request) {
       $response = T11e_Utils::t11e_json_post($url, $request);

       $query_params = array(
         'totalSize' => (int) $response['totalSize'],
         'exactSize' => (int) $response['exactSize'],
         'startIndex' => (int) $response['startIndex'],
         'pageSize' => (int) $response['pageSize']
       );
       if (!empty($response['itemIds'])) {
         $query_params['itemIds'] = implode(',', $response['itemIds']);
       }
       if (!empty($response['exactMatches'])) {
         $query_params['exactMatches'] = implode($response['exactMatches'],'');
       }

       $results = array(
         'results_query_params' => http_build_query($query_params),
         '_discovery' => array(
           'request' => $request,
           'response' => $response
         )
       );

       return json_encode($results);
     }

     public static function t11e_json_post($url, $data) {
       /**
       * Posts $data to $url and expects JSON data in return
       */
       $json_data = json_encode($data);
       $c = curl_init($url);
       curl_setopt($c, CURLOPT_RETURNTRANSFER,true);
       curl_setopt($c, CURLOPT_POST, true);
       curl_setopt($c, CURLOPT_POSTFIELDS, $json_data);
       curl_setopt($c, CURLOPT_FAILONERROR,true);
       curl_setopt($c, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));

       $response = curl_exec($c);
       $http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
       $error = curl_error($c);
       curl_close($c);

       if ($http_status >= 200 && $http_status < 300 )
       { // 200 - 299 inclusive
         return json_decode($response, true);
       } else {
         throw new Exception($error, $http_status);
       }
     }

     public static function t11e_fix_get() {
       /**
       * From http://php.net/manual/en/reserved.variables.get.php
       * Adds support for retrieving arrays from $_GET.
       */
       $query_string = $_SERVER['QUERY_STRING'];
       $params = array();
       $pairs = explode('&', $query_string);

       foreach ($pairs as $i) {
         if (!empty($i)) {
           list($name, $value) = explode('=', $i, 2);
           $name = rawurldecode($name);
           $value = rawurldecode($value);
           if (isset($params[$name]) ) {
             if (is_array($params[$name]) ) {
               $params[$name][] = $value;
             } else {
               $params[$name] = array($params[$name], $value);
             }
           } else {
             $params[$name] = $value;
           }
         }
       }

       foreach ( $_GET as $key => $value ) {
         if (is_array($params[$key]) ) {
           $_GET[$key] = $params[$key];
           $_REQUEST[$key] = $params[$key];
         }
       }

       return $params;
     }
   }

   T11e_Utils::t11e_fix_get();

   $t11e_application_ini = parse_ini_file ( "web.config.ini",  true ); // process sections

   $t11e_AppSettings = $t11e_application_ini["AppSettings"];

  ?>

C# Example

The following example is based upon a Transparensee tutorial site for real estate using this web.config file:

<?xml version="1.0"?>
<!-- Web.config file for t11e_tutorial. -->
<configuration>
    <appSettings>
      <add key="discoveryEngineUrl" value="http://localhost:8090" />
      <add key="discoveryQueryPath" value="/ws/query" />
    </appSettings>
  <system.web>
  </system.web>
</configuration>

Controller code example:

using System;
using System.Web;
using System.Web.UI;
using System.Collections;
using System.Text;
using System.Configuration;

namespace t11e_tutorial
{

   public class Controller : System.Web.UI.Page
   {

       public void Page_Load() {
           int pageSize = 10;
           int startIndex = 0;

           if (Request.QueryString["page"] != null)
           {
                Int32 page = Int32.Parse(Request.QueryString["page"]);
                startIndex = (page - 1) * pageSize;
           }

           ArrayList drillDowns = new ArrayList();

           Hashtable drillDown = new Hashtable();
           drillDown.Add("dimension", "bath");
           drillDowns.Add(drillDown);

           drillDown = new Hashtable();
           drillDown.Add("dimension", "bedroom");
           drillDowns.Add(drillDown);

           drillDown = new Hashtable();
           drillDown.Add("dimension", "condition");
           drillDowns.Add(drillDown);

           drillDown = new Hashtable();
           drillDown.Add("dimension", "style");
           drillDown.Add("ids", new string[]{ "multi-family", "apartment", "condo",
                       "co-op", "townhome",
                       "single-family", "colonial", "new england", "cape cod",
                       "classical", "federal", "greek revival", "tidewater",
                       "antebellum", "victorian", "gothic", "second empire",
                       "queen anne", "contemporary", "ranch", "raised ranch",
                       "split-level", "bauhaus", "art moderne", "transitional"});
           drillDown.Add("isolated", "false");

           drillDowns.Add(drillDown);

           ArrayList criteria = new ArrayList();

           Hashtable criterion = new Hashtable();
           criterion.Add("dimension", "type");

           if (Request.QueryString["type"] != null)
           {
               criterion.Add("value", Request.QueryString["type"]);
           } else {
               criterion.Add("value", new string[]{"sales","rentals"});
           }
           criteria.Add(criterion);

           if (Request.QueryString["bath"] != null)
           {
               criterion = new Hashtable();
               criterion.Add("dimension", "bath");
               criterion.Add("value", Request.QueryString["bath"]);
               criteria.Add(criterion);
           }

           if (Request.QueryString["bedroom"] != null)
           {
               criterion = new Hashtable();
               criterion.Add("dimension", "bedroom");
               criterion.Add("value", Request.QueryString["bedroom"]);
               criteria.Add(criterion);
           }

           if (Request.QueryString["style"] != null)
           {
               string styles = Request.QueryString["style"];
               criterion = new Hashtable();
               criterion.Add("dimension", "style");
               criterion.Add("id", styles.Split(','));
               criteria.Add(criterion);
           }

           if (Request.QueryString["price_min"] != null
               || Request.QueryString["price_max"] != null)
           {
               StringBuilder val = new StringBuilder();

               val.Append("[");
               if (Request.QueryString["price_min"] != null)
               {
                   val.Append(Request.QueryString["price_min"]);
               }
               val.Append(",");
               if (Request.QueryString["price_max"] != null)
               {
                   val.Append(Request.QueryString["price_max"]);
               }
               val.Append("]");

               criterion = new Hashtable();
               criterion.Add("dimension", "price");
               criterion.Add("value", val.ToString());
               criteria.Add(criterion);
           }

           if (Request.QueryString["lease_min"] != null
               || Request.QueryString["lease_max"] != null)
           {
               StringBuilder val = new StringBuilder();

               val.Append("[");
               if (Request.QueryString["lease_min"] != null)
               {
                   val.Append(Request.QueryString["lease_min"]);
               }
               val.Append(",");
               if (Request.QueryString["lease_max"] != "")
               {
                   val.Append(Request.QueryString["lease_max"]);
               }
               val.Append("]");

               criterion = new Hashtable();
               criterion.Add("dimension", "lease");
               criterion.Add("value", val.ToString());
               criteria.Add(criterion);
           }

           Hashtable request = new Hashtable();

           request.Add("startIndex", startIndex);
           request.Add("pageSize", pageSize);

           if (criteria != null)
           {
               request.Add("criteria",criteria);
           }

           if (drillDowns != null)
           {
               request.Add("drillDown",drillDowns);
           }

           string queryUrl = new Uri(new Uri(
               ConfigurationManager.AppSettings["discoveryEngineUrl"]),
               ConfigurationManager.AppSettings["discoveryQueryPath"]).ToString();

           try {
               Response.Write(t11e_utils.t11e_query(queryUrl, request));
           }
           catch (Exception e)
           {
               Response.Write(e.ToString());
           }
       }

   }
 }