Search code examples
c#azure-functionsazure-cosmosdbazure-cosmosdb-sqlapi

Azure functions with Cosmos DB with wild search


I want a 'wild' search where I get FirstName OR Surname. so it would be possible to send a FirstName of "" and Surname of "Smith" so I get everyone with the surname "Smith".

I feel this is partly correct, but having a sql query in the header has a slightly off smell. Is there a better way to do this?

 [FunctionName($"People_Get")]
 public IActionResult GetPeople(
 [HttpTrigger( AuthorizationLevel.Anonymous, "get", Route = "Review/{firstName}/{surname}")]
 PeopleRequest request,
 HttpRequest req,
 [CosmosDB( "CosmosDB", "PeopleContainer", Connection = "CosmosDbConnectionString",
   SqlQuery = @"SELECT  c.id ,
                        c.FirstName ,
                        c.Surname 
                FROM c.FirstName
                WHERE c.FirstName == firstName OR c.FirstName == surname")]
IEnumerable<Models.People> peopleReviews,
 ILogger log)
 {        
    return new OkObjectResult(peopleReviews);
 }

Solution

  • Azure functions with Cosmos DB with wild search

    The code is correct, but there are a few changes to be done.

    1. The SqlQuery property in the CosmosDB attribute should use string interpolation to include the values of the firstName and surname parameters in the query, rather than hardcoding them.

    2. Use the 'LIKE' operator in the WHERE clause instead of '==' to match partial strings.

    3. And also, you can add a condition to check if either firstName or surname is null or empty, and return an error response in that case.

    The below is the updated code:

    public static class Function1
        {
            [FunctionName("People_Get")]
            public IActionResult GetPeople([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Review/{firstName}/{surname}")]
    PeopleRequest request, HttpRequest req, [CosmosDB("CosmosDB", "PeopleContainer", Connection = "CosmosDbConnectionString")]
    IEnumerable<Models.People> peopleReviews, ILogger log)
            {
                if (string.IsNullOrEmpty(request.firstName) && string.IsNullOrEmpty(request.surname))
                {
                    return new BadRequestObjectResult("Please provide either a first name or a surname.");
                }
    
                var query = from p in peopleReviews
                where (string.IsNullOrEmpty(request.firstName) || p.FirstName.Contains(request.firstName))
                && (string.IsNullOrEmpty(request.surname) || p.Surname.Contains(request.surname))
                select p;
    
                return new OkObjectResult(query);
    
            }
        }