Search for Resources

Each endpoint in the API provides operations for searching resources. For example you can use the Search Computers operation of the computers endpoint to search for computers. (See the API Reference.)

To use a search operation you provide a SearchFilter object that contains one or more search criteria. A SearchCriteria object includes properties for configuring the following types of searches:

  • Boolean: Search on boolean values.
  • Choice: Search fields that have a defined set of valid values
  • ID: Search unique ID’s
  • Null: Search on null values
  • Numeric: Search on numeric values
  • String: Search on string values
  • Date range: Search on date values

Searches that use multiple criteria return results that satisfy all of the criteria.

As mentioned in First Steps Toward Deep Security Automation, when you use the API directly, you use 0 to represent a null value. However, to search for a null value you use a Null search. You do not perform a numeric search for 0.

Search criteria include the following items:

  • The name of the field (the property of the resource) that you are searching
  • A value to search for (or, for date values, a range of dates)
  • An operator to test against field values (this does not apply to date-value searches)
  • The maximum number of items to return (default is 5000)
When performing an ID search, you do not include the name of the field as it is assumed to be the ID field.

The type of value that you are searching on determines the operators that are available.

Type Operators
 Boolean true (default)
false
 Choice (for fields that have a defined set of valid values) equal (default)
not-equal
 ID (for unique ID’s) equal (default)
greater-than
greather-than-or-equal
less-than
less-than-or-equal
not-equal
 Null true (default; true indicates null)
false
 Numeric equal (default)
greater-than
greather-than-or-equal
less-than
less-than-or-equal
not-equal
 String equal
not-equal
Date-related searches employ date ranges and you do not explicitly use operators.

Searchable fields

The API Reference indicates which fields of a resource are searchable. You can find the information for the fields in the response objects for the operations.

  1. Click an operation that returns the type of resource that you are searching. For example, the Describe a Computer operation returns a computer resource.
  2. Click 200 successful operation in the Responses section.
  3. Read the description of the field. The descriptions of searchable fields contain “Searchable as datatype“, where datatype can be String, Numeric, ID, Date,  Boolean, and Choice.

The following fields are not searchable:

  • The locale field of any object
  • The platform field of a Computer object
  • Fields that have an object as a value such as the computerSettings field of a Computer object

When you search a field that is not searchable, you receive an error similar to Invalid SearchFilter: unknown fieldName: platform.

Example: Search for policies by name

The following example performs a simple search on policy names.

Python
def search_policies_by_name(client, configuration, api_version, api_exception, name):
    """ Searches for a policy by name.

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :param name: The policy name to search for.
    :return: A PoliciesApi object that contains the policies found by the search.
    """

    # Set search criteria
    search_criteria = client.SearchCriteria()
    search_criteria.field_name = "name"
    search_criteria.string_test = "equal"
    search_criteria.string_value = name

    # Create a search filter
    search_filter = client.SearchFilter(None, [search_criteria])
    search_filter.max_items = 1

    # Perform the search
    try:
        policies_api = client.PoliciesApi(client.ApiClient(configuration))
        return policies_api.search_policies(api_version, search_filter=search_filter)

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Searches for a policy by name.
* @param {object} api The api module.
* @param {String} name The policy name to search for.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains the found poliicies.
*/
exports.searchPoliciesByName = function (api, name, apiVersion) {
  return new Promise((resolve, reject) => {
    // Search criteria
    const searchCriteria = new api.SearchCriteria();
    searchCriteria.fieldName = "name";
    searchCriteria.stringTest = api.SearchCriteria.StringTestEnum.equal;
    searchCriteria.stringValue = name;

    // Add criteria to search filter
    const searchFilter = new api.SearchFilter();
    searchFilter.maxItems = 1;
    searchFilter.searchCriteria = [searchCriteria];

    // Add search filter to a search options object
    const searchOptions = {
      searchFilter: searchFilter,
      overrides: false
    };

    // Perform the search
    const policiesApi = new api.PoliciesApi();
    policiesApi.searchPolicies(apiVersion, searchOptions)
      .then(policies => {
        resolve(policies);
      })
      .catch(error => {
        reject(error);
      });
  });
};
Java
/*
 * Searches for a policy by name
 * @param name The policy name
 * @Return A Policy object
 */
public static Policy searchPoliciesByName(String name) {
    //Create a search criteria
    SearchCriteria searchCriteria = new SearchCriteria();
    searchCriteria.setFieldName("name");
    searchCriteria.setStringValue(name);
    searchCriteria.setStringTest(SearchCriteria.StringTestEnum.EQUAL);
    
    //Create and configure a search filter
    SearchFilter searchFilter = new SearchFilter();
    searchFilter.setMaxItems(1);
    searchFilter.addSearchCriteriaItem(searchCriteria);
    
    //Search 
    PoliciesApi policiesApi = new PoliciesApi();
    Policies policies = new Policies();
    try {
        policies = policiesApi.searchPolicies(searchFilter, false, "v1");
    } catch (ApiException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    if (policies.getPolicies().size() > 0) {
        return policies.getPolicies().get(0);
    } else {
        return null;
    }
}

Example: Search using multiple criteria

Python
def get_computers_with_policy_and_relay_list(client, configuration, api_version, api_exception, relay_list_id, policy_id):
    """ Search for computers that are assigned to a specific policy and relay list.

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :param relay_list_id: The ID of the relay list.
    :param policy_id: The ID of the policy.
    :return: A ComputersApi object that contains matching computers
    """

    # Set search criteria for platform
    policy_criteria = client.SearchCriteria()
    policy_criteria.field_name = "policyID"
    policy_criteria.numeric_test = "equal"
    policy_criteria.numeric_value = policy_id

    # Set search criteria for relay
    relay_criteria = client.SearchCriteria()
    relay_criteria.field_name = "relayListID"
    relay_criteria.numeric_test = "equal"
    relay_criteria.numeric_value = relay_list_id

    # Create the search filter
    search_filter = client.SearchFilter(None, [policy_criteria, relay_criteria])

    try:
        # Perform the search
        computers_api = client.ComputersApi(client.ApiClient(configuration))
        return computers_api.search_computers(api_version, search_filter=search_filter)

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Searches for computers that are assigned to a specific policy and relay list.
* @param {object} api The api module.
* @param {Number} relayListID The ID of the relay list.
* @param {Number} policyID The policy ID.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains the found computers.
*/
exports.getComputersWithPolicyAndRelayList = function (api, relayListID, policyID, apiVersion) {
  // Search criteria for the platform
  const relayCriteria = new api.SearchCriteria();
  relayCriteria.fieldName = "relayListID";
  relayCriteria.numericTest = api.SearchCriteria.NumericTestEnum.equal;
  relayCriteria.numericValue = relayListID;

  // Search criteria for the policy ID
  const policyCriteria = new api.SearchCriteria();
  policyCriteria.fieldName = "policyID";
  policyCriteria.numericTest = api.SearchCriteria.NumericTestEnum.equal;
  policyCriteria.numericValue = policyID;

  // Add search criteria to a SearchFilter
  const searchFilter = new api.SearchFilter();
  searchFilter.searchCriteria = [relayCriteria, policyCriteria];

  // Add search filter to a search options object
  const searchOptions = {
    searchFilter: searchFilter,
    overrides: false
  };

  // Perform the search and return the promise
  const computersApi = new api.ComputersApi();
  return computersApi.searchComputers(apiVersion, searchOptions);
};
Java
/*
 * Search for computers that are assigned to a specific policy and relay list.
 * @param relayListID The ID of the relay list.
 * @param policyID The ID of the policy.
 * @returns A Computers object that contains matching computers.
 */
public static Computers getComputersWithPolicyAndRelayList(Integer relayListID, Integer policyID){
    //Search criteria for platform
    SearchCriteria relayCrit = new SearchCriteria();
    relayCrit.setFieldName("relayListID");
    relayCrit.setNumericValue(relayListID.longValue());
    relayCrit.setNumericTest(SearchCriteria.NumericTestEnum.EQUAL);
    
    //Search criteria for policy ID
    SearchCriteria policyCrit = new SearchCriteria();
    policyCrit.setFieldName("policyID");
    policyCrit.setNumericValue(policyID.longValue());
    policyCrit.setNumericTest(SearchCriteria.NumericTestEnum.EQUAL);
    
    //Search filter
    SearchFilter searchFilter = new SearchFilter();
    searchFilter.addSearchCriteriaItem(relayCrit);
    searchFilter.addSearchCriteriaItem(policyCrit);
    
    //Perform the search
    ComputersApi computersApi = new ComputersApi();
    Computers computers = new Computers();
    try {
        computers = computersApi.searchComputers(searchFilter, false, "v1");
    } catch (ApiException e) {
        e.printStackTrace();
    }
    return computers;
}
For information about authenticating API calls, see Authenticate with Deep Security Manager.

Use wildcards in String searches

String searches support the use of two wildcards in string values:

  • %: Matches zero or more characters
  • _; Matches 1 character

For example, the string value %Security matches Deep Security, and it also matches Security. The string value version_ matches version1, and does not match version.

If you want to search for the literal % or _ characters, you can disable wildcards. However, the use of wildcards is enabled by default.

The following search filter can be used to find the policy named “Base Policy”.

Python
# Create the search criteria
search_criteria = deepsecurity.SearchCriteria()
search_criteria.field_name = "name"
search_criteria.string_test = "equal"
search_criteria.string_value = "Base%"
JavaScript
// Create the search criteria
const searchCriteria = new api.SearchCriteria();
searchCriteria.fieldName = "name";
searchCriteria.stringValue = "Base%";
searchCriteria.stringTest = "equal";
Java
//Create and configure a search criteria
SearchCriteria searchCriteria = new SearchFilter();
searchCriteria.setFieldName("name");
searchCriteria.setStringValue("Base%");
searchCriteria.setStringTest(StringTestEnum.EQUAL);
To disable wildcard searches, set the stringWildcards property of the SearchCriteria object to false:
Python
search_criteria.string_wildcards = "false"
JavaScript
searchCriteria.stringWildcards = "false";
Java
searchCriteria.stringWildcards(false);

Date-range searches

You can search fields that contains date values that fall within two specified dates. The following search criteria fields define the date range:

  • FirstDate: The earlier date in the range. The default value is the earliest possible date.
  • FirstDateInclusive: A boolean value that indicates whether the range includes the FirstDate (true) or not (false). The default value is false.
  • LastDate: The later date in the range. The default value is the latest possible date.
  • LastDateInclusive:  A boolean value that indicates whether the range includes the LasteDate (true) or not (false). The default value is false.

The values for FirstDate and LastDate are expressed as the number of milliseconds since January 1, 1970 (GMT).

Example: Search Intrusion Prevention rules based on date updated

The following example searches for Intrusion Prevention rules based on when they were last updated.

Python
def search_updated_intrusion_prevention_rules(client, configuration, api_version, api_exception, num_days):
    """ Searches for Intrusion Prevention rules that have been updated within a specific number of days.

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :param num_days: The number of days within which the rules were updated.
    :return: A IntrusionPreventionRulesApi object that contains the rules that were updated within num_days.
    """

    # Time that rules were last updated
    current_time_in_ms = int(round(time.time() * 1000))
    last_updated_in_ms = current_time_in_ms - (num_days * 24 * 60 * 60 * 1000)

    # Set search criteria for the date range
    search_criteria = client.SearchCriteria()
    search_criteria.field_name = "lastUpdated"
    search_criteria.first_date_value = last_updated_in_ms
    search_criteria.last_date_value = current_time_in_ms
    search_criteria.first_date_inclusive = True
    search_criteria.last_date_inclusive = True

    # Create a search filter
    search_filter = client.SearchFilter(None, [search_criteria])

    # Perform the search
    try:
        intrusion_prevention_rules_api = client.IntrusionPreventionRulesApi(client.ApiClient(configuration))
        return intrusion_prevention_rules_api.search_intrusion_prevention_rules(api_version, search_filter=search_filter)

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Searches for Intrusion Prevention rules that have been updated within a specific number of days.
* @param {object} api The api module.
* @param {Number} numDays The number of days within which the rules were updated.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains the found rules.
*/
exports.searchUpdatedIntrusionPreventionRules = function (api, numDays, apiVersion) {
  // Time that rules were last updated
  const updateTime = Date.now() - numDays * 24 * 60 * 60 * 1000;

  // Search criteria for the date range
  const searchCriteria = new api.SearchCriteria();
  searchCriteria.fieldName = "lastUpdated";
  searchCriteria.firstDateValue = updateTime;
  searchCriteria.lastDateValue = Date.now();
  searchCriteria.firstDateInclusive = true;
  searchCriteria.lastDateInclusive = true;

  // Add search criteria to a SearchFilter
  const searchFilter = new api.SearchFilter();
  searchFilter.searchCriteria = [searchCriteria];

  // Add search filter to a search options object
  const searchOptions = {
    searchFilter: searchFilter,
    overrides: false
  };

  // Perform the search
  const ipRulesApi = new api.IntrusionPreventionRulesApi();
  return ipRulesApi.searchIntrusionPreventionRules(apiVersion, searchOptions);
};
Java
/*
 * Searches for intrusion prevention rules that have been updated within a specific number of days
 * @param dsmClient An ApiClient object for the Deep Security Manager
 * @return A list of found rules
 */
public static IntrusionPreventionRules searchUpdatedIntrusionPreventionRules(int days){
    //Dates to search
    long last = Calendar.getInstance().getTimeInMillis();
    long first = last - TimeUnit.DAYS.toMillis(days);
    
    //Create a search criteria
    SearchCriteria searchCriteria = new SearchCriteria();
    searchCriteria.setFieldName("lastUpdated");
    searchCriteria.setFirstDateValue(first);
    searchCriteria.setLastDateValue(last);
    searchCriteria.setFirstDateInclusive(true);
    searchCriteria.setLastDateInclusive(true);
    
    //Create the search filter
    SearchFilter searchFilter = new SearchFilter();
    searchFilter.addSearchCriteriaItem(searchCriteria);
    
    //Perform the search
    IntrusionPreventionRulesApi ipRulesApi = new IntrusionPreventionRulesApi();
    IntrusionPreventionRules ipRules = new IntrusionPreventionRules();
    try {
        ipRules = ipRulesApi.searchIntrusionPreventionRules(searchFilter, "v1");
    } catch (ApiException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    return ipRules;
}
For information about authenticating API calls, see Authenticate with Deep Security Manager.

Sort order

The characteristics of the search critiera determine the sort order of search results:

  • Boolean, Choice, Null, and String searches: Sorted by the ID of the returned object, in ascending order.
  • ID searches: Sorted by ID. The operator determines whether the order is ascending or descending:
    • less-than and less-than-or-equal: descending
    • All other operators: ascending
  • Numeric searches: Sorted by the field that is searched. The operator determines whether the order is ascending or descending:
    • less-than and less-than-or-equal: descending
    • All other operators: ascending

    When multiple search results have the same value for the searched field, those objects are secondarily sorted by ID.

  • Date searches: Sorted by the field that is searched. The date range parameters that are provided for the search determine the sort order:
    • Only LastDate is provided: descending
    • Any other combination: ascending

    When multiple search results have the same value for the searched date field, those objects are secondarily sorted by ID.

  • Multiple search criteria: Searches that use multiple search criteria are sorted by ID (ascending), regardless of the default sort order of the individual criteria.

SearchFilter objects enable you to override the default sort order and order by the ID of the returned objects.

Limit search results and paging

Use the maxItems field of a search filter to limit the number of returned objects. The maximum number of returned objects is 5000 by default, and cannot exceed 5000.

You can also use the maxItems field to implement paging of the results of ID searches:

  • Search by ID using the greater-than operator
  • Use maxItems to estabish the page size
  • Calculate the value of the ID to search on based on the highest ID in the previous page of results.

The following example shows how to use searches to retrieve all computers in a series of pages.

Python
def paged_search_computers(client, configuration, api_version, api_exception):
    """ Uses a search filter to create a paged list of computers

    :param client: The Deep Security API modules.
    :param configuration: Configuration object to pass to the client.
    :param api_version: The version of the API to use.
    :param api_exception: The Deep Security API exception module.
    :return: A list of computer objects
    """

    # Set search criteria
    search_criteria = client.SearchCriteria()
    search_criteria.id_value = 0
    search_criteria.id_test = "greater-than"

    # Create a search filter with maximum returned items
    page_size = 10
    search_filter = client.SearchFilter()
    search_filter.max_items = page_size
    search_filter.search_criteria = [search_criteria]

    # Perform the search and do work on the results
    computers_api = client.ComputersApi(client.ApiClient(configuration))
    paged_computers = []

    try:
        while True:
            computers = computers_api.search_computers(api_version, search_filter=search_filter)
            num_found = len(computers.computers)
            current_paged_computers = []

            if num_found == 0:
                print("No computers found.")
                break

            for computer in computers.computers:
                current_paged_computers.append(computer)

            paged_computers.append(current_paged_computers)

            # Get the ID of the last computer in the page and return it with the number of computers on the page
            last_id = computers.computers[-1].id
            search_criteria.id_value = last_id
            print("Last ID: " + str(last_id), "Computers found: " + str(num_found))

            if num_found != page_size:
                break

        return paged_computers

    except api_exception as e:
        return "Exception: " + str(e)
JavaScript
/*
* Searches for computers in pages of 10.
* @param {object} api The api module.
* @param {String} apiVersion The api version to use.
* @return {Promise} A promise that contains an array of the pages of computers.
*/
exports.pagedSearchComputers = function (api, apiVersion) {
  return new Promise((resolve, reject) => {

    const results = [];
    const pageSize = 10;

    function getPageOfComputers(pageSearchOptions) {
      // Checks the search results to see if we're done
      function checkResults(searchResults) {
        // Get the ID of the last computer found, and the number found
        const lastID = searchResults.computers[searchResults.computers.length - 1].ID;
        const numFound = searchResults.computers.length;

        // See the page details as they are obtained
        console.log(`last ID:  ${lastID}; numfound: ${numFound}`);

        results.push(searchResults.computers);

        // If the number found is less than the page size we are done
        if (numFound < pageSize) {
          return results;
        }
        // Search filter for the next page of computers
        const nextSearchCriteria = new api.SearchCriteria();
        nextSearchCriteria.idValue = lastID;
        nextSearchCriteria.idTest = api.SearchCriteria.IdTestEnum["greater-than"];

        const nextSearchFilter = new api.SearchFilter();
        nextSearchFilter.maxItems = pageSize;
        nextSearchFilter.searchCriteria = [nextSearchCriteria];

        // Add search filter to a search options object
        const nextSearchOpts = {
          searchFilter: nextSearchFilter,
          overrides: false
        };
        // Get the next page of computers
        return getPageOfComputers(nextSearchOpts);
      }
      // Perform the next search
      const computersApi = new api.ComputersApi();
      return computersApi.searchComputers(apiVersion, pageSearchOptions).then(checkResults);
    }

    // Search criteria for first page of computers
    const searchCriteria = new api.SearchCriteria();
    searchCriteria.idValue = 0;
    searchCriteria.idTest = api.SearchCriteria.IdTestEnum["greater-than"];

    // Search filter with maximum returned items
    const computerSearchFilter = new api.SearchFilter();
    computerSearchFilter.maxItems = pageSize;
    computerSearchFilter.searchCriteria = [searchCriteria];

    // Add search filter to a search options object
    const searchOpts = {
      searchFilter: computerSearchFilter,
      overrides: false
    };

    // Perform the search
    getPageOfComputers(searchOpts)
      .then(results => {
        resolve(results);
      })
      .catch(error => {
        reject(error);
      });
  });
};
Java
/*
 * Searches computers and returns all in pages of 100
 * @param dsmClient An ApiClient for the Deep Security Manager
 */
public static void pagedSearchComputers() {
    //Create a search criteria
    SearchCriteria searchCriteria = new SearchCriteria();
    searchCriteria.setIdValue(0L);
    searchCriteria.setIdTest(SearchCriteria.IdTestEnum.GREATER_THAN);
    
    //Set up the search filter
    SearchFilter searchFilter = new SearchFilter();
    int pagesize = 100;
    searchFilter.setMaxItems(pagesize);
    searchFilter.addSearchCriteriaItem(searchCriteria);

    ComputersApi computersApi = new ComputersApi();
    //to use in loop exit expresssion
    int found;
    do {
        found = 0;
        Computers computers = new Computers();
        //Find a page of computers and save the number found
        try {
            computers = computersApi.searchComputers(searchFilter, false, "v1");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        found = computers.getComputers().size();
        if (found > 0 ) {
            for (Computer computer : computers.getComputers()) {
                System.out.println(computer.getHostName());
            }
            //Get the highest ID found and adjust the search filter for the next search
            int lastID = computers.getComputers().get(computers.getComputers().size()-1).getID();
            searchCriteria.setIdValue((long) lastID);
        }
    } while(found == pagesize);   //Exit loop when the page size is less than the maximum
}

For information about authenticating API calls, see Authenticate with Deep Security Manager.