Skip to content

Run a Saved Search

An accounts payable team keeps a saved search, Invoices by Vendor, that business users run in the Search app. Its reconciliation job needs the same list for one vendor at a time, every night, without rebuilding the query in code.

At a glance

  • Extension point REST API from your own code
  • You need A token with Run Searches, made by a user who can see the saved search; a saved search with a condition on the field VendorName
  • Teaches Condition ids versus field names, typed condition values, and paging with StartRow and RowLimit

Set it up

  1. In the Search app, save a search named Invoices by Vendor with a condition on the VendorName field. Share it with the service account, or create it as that account.
  2. Give the service account Run Searches and create a token. See Authentication.
  3. Set KnowledgeLakeApiURL and KnowledgeLakeApiToken in the environment, and reference KL.APIClient, generated from your tenant's spec.

How the ids fit together:

  • Each saved search has SavedSearchId and SearchCatalogId (the source it searches).
  • Each condition has ConditionId, ParameterInternalName (the field's internal name) and ParameterType.
  • To pass a value, put it in SearchConditions under the condition's ConditionId, in the dictionary that matches the type: Strings, Integers, Decimals or DateTimes.

The program

RunSavedSearch.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using KL.APIClient.Api;
using KL.APIClient.Client;
using KL.APIClient.Model;

public static class RunSavedSearch
{
    public static async Task Main()
    {
        string savedSearchName = "Invoices by Vendor";
        string conditionField = "VendorName";
        string conditionValue = "Gateway Fleet Services LLC";
        int pageSize = 200;

        var config = new Configuration { BasePath = Environment.GetEnvironmentVariable("KnowledgeLakeApiURL") };
        config.AddApiKey("TempIdentityToken", Environment.GetEnvironmentVariable("KnowledgeLakeApiToken"));
        var repository = new V1RepositoryAPIApi(config);

        // 1. Find the saved search and the condition id.
        var searches = await repository.V1RepositoryAPIControllerGetSavedSearchesAsync(new ParameterGetSavedSearchesListDTO());
        if (!searches.Success) throw new Exception("GetSavedSearches failed: " + searches.MessageKey);

        var search = searches.Data.FirstOrDefault(s => s.SavedSearchName == savedSearchName);
        if (search == null) throw new Exception("The user cannot see a saved search named " + savedSearchName);

        var condition = search.SearchConditions.FirstOrDefault(c => c.ParameterInternalName == conditionField);
        if (condition == null) throw new Exception("The search has no condition on " + conditionField);

        // 2. Run it, one page at a time.
        int startRow = 0;
        while (true)
        {
            var page = await repository.V1RepositoryAPIControllerRunSavedSearchAsync(new ParameterRunSavedSearchDTO
            {
                SearchId = search.SavedSearchId,
                SearchCatalogId = search.SearchCatalogId,
                StartRow = startRow,
                RowLimit = pageSize,
                SearchConditions = new PropertyBagDTOString
                {
                    Strings = new Dictionary<string, string> { { condition.ConditionId, conditionValue } }
                }
            });
            if (!page.Success) throw new Exception("RunSavedSearch failed: " + page.MessageKey);

            foreach (var item in page.Data.Results)
            {
                // Data holds one entry per result column: InternalPropertyId and Value.
                string values = string.Join(" | ", item.Data.Select(d => d.InternalPropertyId + "=" + d.Value));
                Console.WriteLine(item.ResultItemId + "  " + values);
            }

            if (page.Data.Results.Count < pageSize) break;
            startRow += pageSize;
        }
    }
}

How it works

  • GetSavedSearches returns only the searches the token's user can see, each with its conditions. The program finds the condition by field name, then uses its ConditionId.
  • The value goes into Strings because VendorName is a text field. A number goes into Integers or Decimals, a date into DateTimes.
  • RunSavedSearch returns one page. The loop moves StartRow by RowLimit and stops when a page is shorter than RowLimit. TotalRows is not filled, so do not rely on it.
  • Each result has ResultItemId and a Data list of { InternalPropertyId, Value }, one per result column of the saved search.

Test it

  1. Run the same search in the Search app with the vendor Gateway Fleet Services LLC.
  2. Run the program.

You should see

the same number of rows as the Search app shows, with the same column values, printed as ResultItemId column=value | column=value.

What can go wrong

What you see Cause and fix
The saved search is not found The token's user cannot see it. Share it with that user.
The condition is ignored The key in Strings must be the ConditionId, not the field name, and the value must be in the dictionary that matches ParameterType. Boolean conditions are not passed through this action.
Only 1000 rows come back RowLimit 0 means 1000. Page with StartRow and RowLimit.
TotalRows is 0 The action does not fill it. Stop when a page is short.
HTTP 412 with a search error The source rejected the query, for example a bad date value. The text after Root message: comes from the source.

Variations