Search for Resources

Search is a powerful tool that is often useful when automating tasks. 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 search filter object that contains one or more search criteria. A search criteria 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 Notes about Resource Property Values, 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  — note that field names are case-sensitive
  • 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.

The following example performs a simple search on policy names.

Python

View source

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

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

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

except api_exception as e:
    return "Exception: " + str(e)
JavaScript

View source

// 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

View source

// 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();

// Return only one policy
searchFilter.setMaxItems(Integer.valueOf(1));
searchFilter.addSearchCriteriaItem(searchCriteria);

// Search
PoliciesApi policiesApi = new PoliciesApi();
Policies policies = policiesApi.searchPolicies(searchFilter, Boolean.FALSE, apiVersion);

The following example shows how to create a search filter that contains multiple criteria.

Python

View source

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

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

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

View source

// 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];
Java

View source

// Search criteria for platform
SearchCriteria relayCrit = new SearchCriteria();
relayCrit.setFieldName("relayListID");
relayCrit.setNumericValue(relayListID);
relayCrit.setNumericTest(SearchCriteria.NumericTestEnum.EQUAL);

// Search criteria for policy ID
SearchCriteria policyCrit = new SearchCriteria();
policyCrit.setFieldName("policyID");
policyCrit.setNumericValue(policyID);
policyCrit.setNumericTest(SearchCriteria.NumericTestEnum.EQUAL);

// Search filter
SearchFilter searchFilter = new SearchFilter();
searchFilter.addSearchCriteriaItem(relayCrit);
searchFilter.addSearchCriteriaItem(policyCrit);
For information about authenticating API calls, see Authenticate with Deep Security Manager

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.

Field names are case-sensitive.

The following fields are not searchable:

  • The locale field of any object
  • Most fields that have an object as a value, such as the policySettings field of a Policy object (see “Search computer sub-objects” below for exceptions).

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

Search computer sub-objects

Although fields that have an object as a value are generally not searchable, several exceptions are present in the computer class. For example, the value of the ec2VirtualMachineSummary field is an object and several of that object’s fields are searchable, such as accountID and the availabilityZone. Similarly, you can search the name field of computer interfaces. (See the API reference for more searchable sub-objects.) The following JSON shows these sub-objects in the computer object’s data structure:

{
    "hostName": "gui2-336",
    "displayName": "",
    "description": "",
    ...
    "interfaces": {
      "name": "ethernet",
      ...
    },
    "ec2VirtualMachineSummary": {
      "accountID": "123456789012",
      "availabilityZone": "ap-northeast-1",
      ...
    },
    ...
    "ID": 201
}

In search criteria, the field name of a sub-object is expressed as a path, for example ec2VirtualMachineSummary/publicIPAddress and interfaces/name.

Use the expand parameter when you search to include only the information that you need in the returned computer objects. For more information, see “Minimize computer response size” in the Performance Tips guide.

When you search on a computer sub-object, the sub-object is automatically included in the returned Computer objects, except when expand is set to none (no sub-objects are returned). For example, if you search on the EC2 account ID and expand is set to tasks, the returned Computer objects include the tasks and ec2VirtualMachineSummary properties. If expand is set to ec2VirtualMachineSummary, the returned Computer objects include the ec2VirtualMachineSummary property.

Python

View source

# Search criteria
computer_criteria = api.SearchCriteria()
computer_criteria.field_name = "ec2VirtualMachineSummary/accountID"
computer_criteria.string_test = "equal"
computer_criteria.string_value = account_id

# Search filter
max_items = None
search_filter = api.SearchFilter(max_items, computer_criteria)

# Include only the EC2 virtual machine summary in the returned computers
expand = api.Expand(api.Expand.ec2_virtual_machine_summary)

# Perform the search
computers_api = api.ComputersApi(api.ApiClient(configuration))
return computers_api.search_computers(api_version, search_filter=search_filter, expand=expand.list(), overrides=False)
JavaScript

View source

// Search criteria
const searchCriteria = new api.SearchCriteria();
searchCriteria.fieldName = "ec2VirtualMachineSummary/accountID";
searchCriteria.stringTest = api.SearchCriteria.StringTestEnum.equal;
searchCriteria.stringValue = accountID;

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

// Include only the EC2 virtual machine summary in the returned computers
const expand = new api.Expand.Expand(api.Expand.OptionsEnum.ec2VirtualMachineSummary);

// Search options object
const searchOptions = {
  searchFilter: searchFilter,
  expand: expand.list(),
  overrides: false
};

// Perform the search
const computersApi = new api.ComputersApi();
return computersApi.searchComputers(apiVersion, searchOptions);
Java

View source

// Search criteria for the account ID
SearchCriteria computerCriteria = new SearchCriteria();
computerCriteria.setFieldName("ec2VirtualMachineSummary/accountID");
computerCriteria.setStringValue(accountID);
computerCriteria.setStringTest(SearchCriteria.StringTestEnum.EQUAL);

// Search filter
SearchFilter searchFilter = new SearchFilter();
searchFilter.addSearchCriteriaItem(computerCriteria);

// Include only ec2VirtualMachineSummary in the returned computer objects 
Expand expand = new Expand();
expand.add(Expand.OptionsEnum.EC2_VIRTUAL_MACHINE_SUMMARY);

ComputersApi computersApi = new ComputersApi();
return computersApi.searchComputers(searchFilter, expand.list(), Boolean.FALSE, apiVersion);

Field names in Python code

When using the Python client libraries, ensure that you use the correct field name in your searches. Some field names are comprised of multiple concatenated words and use camel-case lettering, such as the lastUpdated property of Intrusion Prevention rules. The corresponding Python property uses an underscore character (_) to delimit concatenated words instead of camel-case lettering, for example  last_updated. When you search on a field, you must provide the field name that you are searching on  (lastUpdated) and not the class property (last_updated).

When you use an incorrect field name, you receive an error with the message Invalid SearchFilter: unknown fieldName.

Use the following algorithm to translate Python class properties to field names when the name of the property includes one or more underscore characters (_):

  1. Capitalize the letter that directly follows each underscore.
  2. Delete each underscore.

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 = api.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).

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

Python

View source

# 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 = api.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 = api.SearchFilter(None, [search_criteria])

# Perform the search
try:
    intrusion_prevention_rules_api = api.IntrusionPreventionRulesApi(api.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

View source

// 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

View source

// Dates to search
Long last = Long.valueOf(Calendar.getInstance().getTimeInMillis());
Long first = Long.valueOf(last.intValue() - TimeUnit.DAYS.toMillis(days));

// Create a search criteria
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setFieldName("lastUpdated");
searchCriteria.setFirstDateValue(first);
searchCriteria.setLastDateValue(last);
searchCriteria.setFirstDateInclusive(Boolean.TRUE);
searchCriteria.setLastDateInclusive(Boolean.TRUE);

// Create the search filter
SearchFilter searchFilter = new SearchFilter();
searchFilter.addSearchCriteriaItem(searchCriteria);

// Perform the search
IntrusionPreventionRulesApi ipRulesApi = new IntrusionPreventionRulesApi();
return ipRulesApi.searchIntrusionPreventionRules(searchFilter, apiVersion);
For information about authenticating API calls, see Authenticate with Deep Security Manager.

Sort order

The characteristics of the search criteria 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

View source

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

    :param api: The Deep Security API modules.
    :param configuration: Configuration object to pass to the api 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 = api.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 = api.SearchFilter()
    search_filter.max_items = page_size
    search_filter.search_criteria = [search_criteria]

    # Include the minimum information in the returned Computer objects
    expand = api.Expand(api.Expand.none)

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

    try:
        while True:
            computers = computers_api.search_computers(api_version, search_filter=search_filter, expand=expand.list(), overrides=False)
            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

View source

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;

        // Uncomment to 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 Options = api.Expand.OptionsEnum;
        const expand = new api.Expand.Expand(Options.none);
        const nextSearchOpts = {
          searchFilter: nextSearchFilter,
          expand: expand.list(),
          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 Options = api.Expand.OptionsEnum;
    const expand = new api.Expand.Expand(Options.none);
    const searchOpts = {
      searchFilter: computerSearchFilter,
      expand: expand.list(),
      overrides: false
    };

    // Perform the search
    getPageOfComputers(searchOpts)
      .then(results => {
        resolve(results);
      })
      .catch(error => {
        reject(error);
      });
  });
};
Java

View source

public static void pagedSearchComputers(Integer pageSize, String apiVersion) throws ApiException {

	// Create a search criteria
	SearchCriteria searchCriteria = new SearchCriteria();
	searchCriteria.setIdValue(Long.valueOf(0L));
	searchCriteria.setIdTest(SearchCriteria.IdTestEnum.GREATER_THAN);

	// Set up the search filter
	SearchFilter searchFilter = new SearchFilter();
	searchFilter.setMaxItems(pageSize);
	searchFilter.addSearchCriteriaItem(searchCriteria);
	
	// Include the minimum information in returned Computer objects
	Expand expand = new Expand(Expand.OptionsEnum.NONE);

	ComputersApi computersApi = new ComputersApi();

	// Use in loop exit expression
	int found;
	do {
		// Find a page of computers and save the number found
		Computers computers = computersApi.searchComputers(searchFilter, expand.list(), Boolean.FALSE, apiVersion);

		found = computers.getComputers().size();
		if (found > 0) {

			// Print some page details
			System.out.println("Computers in page:");
			for (Computer computer : computers.getComputers()) {
				System.out.println(computer.getHostName());
			}

			// Get the highest ID found and adjust the search filter for the next search
			Integer lastID = computers.getComputers().get(computers.getComputers().size() - 1).getID();
			searchCriteria.setIdValue(Long.valueOf(lastID.toString()));
		}
	} while (found == pageSize.intValue()); // Exit loop when the page size is less than the maximum
}

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