title: Integrating Cosmos DB with OData using Azure Http trigger function app
body: <p><strong>Objective: implement oData Azure Http trigger function to decrease latency.</strong></p>
  
  <p>I have 3.5 lacks records in cosmosdb and querying the data using azure Http Trigger function app. </p>
  
  <p>I am querying CosmosDB data in via azure DocumentDB client in azure Http Trigger Function. </p>
  
  <pre><code>        public static async Task&lt;IActionResult&gt; MachinesByRegion_Get(
          [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Region/Machines")]HttpRequest req,
          ILogger log)
      {
  
          log.LogInformation("GetMachinesByRegion function Started to process a request.");
  
          // check parameters
          if (string.IsNullOrEmpty(req.Query["PageSize"]) || string.IsNullOrEmpty(req.Query["PageNumber"]))
              return new BadRequestObjectResult(new PostActionResponse(400, "Please provide valid PageSize and PageNumber"));
  
          // Number of documents per page
          int pageSize = int.Parse(req.Query["PageSize"]);
          Dictionary&lt;string,string&gt; field = new Dictionary&lt;string, string&gt;();
          string columns = "*";
          if (!string.IsNullOrEmpty(req.Query["Fields"]))
          {
              string columnstring = req.Query["Fields"].ToString();
              field.Add("Fields", columnstring);
              string[] columnarr = columnstring.Split(',');
              int arraylength = columnarr.Length;
  
              // Build Selection columns
              if (arraylength != 0)
              {
                  StringBuilder strinbuilder = new StringBuilder("c.id, ");
                  int i = 1;
                  foreach (string value in columnarr)
                  {
                      strinbuilder.Append($"c.{value.Replace(" ", String.Empty)}");
                      if (arraylength &gt; i)
                          strinbuilder.Append(", ");
                      i++;
                  }
                  columns = strinbuilder.ToString();
              }
          }
  
          // Parse Query Parameter
          int pagenumber = int.Parse(req.Query["PageNumber"]);
  
          int offset = pagenumber == 1 ? 0 : (pagenumber - 1) * pageSize;
  
          // Bulid query string based on request
          string sqlstr = string.Format($"SELECT {columns} FROM c ORDER BY c.id ASC OFFSET {offset} LIMIT {pageSize}");
  
  
          Helper.TraceLogWriter(log, "Summary:");
          Helper.TraceLogWriter(log, "--------------------------------------------------------------------- ");
          Helper.TraceLogWriter(log, $"Collection : {DBConstants.DataBaseName.Telemetry}.{DBConstants.ContainerName.KomatsuMachine}");
          Helper.TraceLogWriter(log, $"The Query String : {sqlstr}");
          Helper.TraceLogWriter(log, "--------------------------------------------------------------------- ");
          Helper.TraceLogWriter(log, "");
  
          try
          {
              // Feed Options 
              var options = new FeedOptions
              {
                  MaxItemCount = pageSize,
                  MaxDegreeOfParallelism = -1,
                  EnableCrossPartitionQuery = true,
              };
  
              // Create CosmosDB Connection URI
              Uri collectionUri = UriFactory.CreateDocumentCollectionUri(databaseId: DBConstants.DataBaseName.Telemetry, collectionId: DBConstants.ContainerName.KomatsuMachine);
  
              ConnectionPolicy connPolicy = new ConnectionPolicy
              {
                  ConnectionMode = ConnectionMode.Direct,
                  ConnectionProtocol = Protocol.Tcp
              };
  
              using var client = new DocumentClient(new Uri(BaseRepository.EndpointUri), BaseRepository.PrimaryKey, connPolicy);
              // Get the List of Items against the Query string
              var results = client.CreateDocumentQuery(collectionUri, sqlstr, options).ToList();
              int records = results.Count;
              Helper.TraceLogWriter(log, $"Retrieved Documents: {records}");
  
              Helper.TraceLogWriter(log, $"Sample Document: {JsonConvert.DeserializeObject(JsonConvert.SerializeObject(results[0]))}");
  
              await Task.Yield();
  
              // Build base url                    
              var pages = new PageLinkBuilder($"{BaseRepository.BaseUrl}/api/Region/Machines", pagenumber, pageSize, records, field);
  
              return (ActionResult)new OkObjectResult(new PagedResult
              {
                  PageNumber = pagenumber,
                  PageSize = records,
                  Pages = pages,
                  Results = results
              });
          }
          catch (Exception ex)
          {
              Helper.TraceErrorWriter(log, $"Exception caught in GetMachinesByProduct: {ex.Message}");
              return new UnprocessableEntityObjectResult(new PostActionResponse(422, "Exception in CosmosDB, Please check logs"));
          }
      }
  </code></pre>
  
  <p>I just want to enable oData to optimistic performance in case of select, filter and order etc.</p>
  
  <p>in cosmosDB, document have many fields if enable, it will reduce the size of the data. </p>
  
  <p>i had a walk-through on this.<br>
  <a href="https://devblogs.microsoft.com/odata/integrating-cosmos-db-with-odata-part-1/" rel="nofollow noreferrer">Please Click Here</a></p>
  
  <p>This is for Web API. but i need for azure Http trigger function app </p>