Splunk Developer Day: Watch all Sessions!Access the Playlist here

How to work with saved searches using the Splunk Enterprise SDK for Python

The most fundamental feature in Splunk Enterprise is searching your data. But before diving into the details of how to use the SDK to search, let's clarify the terms:

  • A search query is a set of commands and functions you use to retrieve events from an index or a real-time stream, for example: "search * | head 10".
  • A saved search is a search query that has been saved to be used again and can be set up to run on a regular schedule. The results from the search are not saved with the query.
  • A search job is an instance of a completed or still-running search operation, along with the results. A search ID is returned when you create a job, allowing you to access the results of the search when they become available. Search results are returned in JSON, JSON_ROWS, JSON_COLS, XML, or CSV format.

This topic focuses on working with saved searches. For more about working with search jobs, see How to run searches and display results.

The search APIs

The classes for working with saved searches are:

Access these classes through an instance of the splunklib.client.Service(Opens new window) class. Retrieve a collection, and from there you can access individual items in the collection and create new ones. For example, here's a simplified program for getting a collection of saved searches and creating a new one:

# Connect to Splunk Enterprise
service = client.connect(...)
 
# Get the collection of saved searches
savedsearches = service.saved_searches
 
# Create a saved search
mysearch = savedsearches.create(name, query)

Code examples

This section provides examples of how to use the search APIs, assuming you first connect to a Splunk Enterprise instance.

To list saved searches

This example shows how to use the splunklib.client.SavedSearches(Opens new window) class to retrieve and list the saved searches in the saved search collection for the current namespace.

# List the saved searches that are available to the current user
savedsearches = service.saved_searches
 
for savedsearch in savedsearches:
print " " + savedsearch.name
print " Query: " + savedsearch["search"]

To retrieve a collection for a specific namespace—for example, to list the saved searches available to a specific user—create a second Service instance, specifying the owner and app. This example lists the saved searches for the user "username":

# Create a second Service instance
HOST = "localhost"
PORT = 8089
USERNAME = "admin"
PASSWORD = "yourpassword"
OWNER = "username" # Replace this with a valid username
APP = "search"

The history of a saved search contains the past and current instances (jobs) of the search. This example shows the history for all the saved searches in the current collection:

# Print the job history of saved searches
for savedsearch in service.saved_searches:
print savedsearch.name + ":"
 
history = savedsearch.history()
if len(history) > 0:
for job in history:
print " %s" % job.name

When you create a saved search, at a minimum you need to provide a search query and a name for the search. You can also specify additional properties for the saved search at this time by providing a dictionary of key-value pairs for the properties. Or, modify properties after you have created the saved search.

This example shows how to create a basic saved search:

# Create a saved search--search everything, return 1st 10 events
# Note: Do not include the 'search' keyword for a saved search
myquery = "* | head 10"
mysearchname = "Test Search"
 
mysavedsearch = service.saved_searches.create(mysearchname, myquery)
print "Created: " + mysavedsearch.name

This example shows how to iterate through all the saved searches in the current collection and list the properties for each:

# Iterate all saved searches and list properties
for savedsearch in service.saved_searches:
print "'" + savedsearch.name + "' properties"
 
searchprops = savedsearch.content
for key in sorted(searchprops.keys()):
value = searchprops[key]
print " %s: %s" % (key, value)

This example shows how to view specific properties of the new saved search:

# Retrieve the new search
mysavedsearch = service.saved_searches["Test Search"]
 
# Print the properties of the saved search
print "Description: ", mysavedsearch["description"]
print "Is scheduled: ", mysavedsearch["is_scheduled"]
print "Cron schedule: ", mysavedsearch["cron_schedule"]
print "Next scheduled time: ", mysavedsearch["next_scheduled_time"]

To set properties, create a dictionary of key-value pairs (keyword arguments, or kwargs), then pass that dictionary to the update method(Opens new window) to make the changes on the server. Next, call the refresh method(Opens new window) to update your local, cached copy of the object with these changes. See "Saved search parameters" for a list of all the possible properties you can set for a saved search.

This example continues from the previous one, showing how to set the description and schedule the saved search in cron(Opens new window) format:

# Retrieve the new search
mysavedsearch = service.saved_searches["Test Search"]
 
# Specify a description for the search
# Enable the saved search to run on schedule
# Run the search on Saturdays at 4:15am
# Search everything in a 24-hour time range starting June 19, 12:00pm
kwargs = {"description": "This is a test search",

To run a saved search and display search results

Running a saved search creates a search job that is scheduled to run right away. Use the SavedSearch.dispatch(Opens new window) method to run a saved search, which returns a Job(Opens new window) object that corresponds to the search job. The Job object gives you access to information about the search job, such as the search ID, the status of the search, and the search results once the search job has finished.

The dispatch method takes these optional parameters:

  • dispatch.now: A time string that is used to dispatch the search as though the specified time were the current time.
  • dispatch.*: Overwrites the value of the search field specified in *.
  • trigger_actions: A Boolean that indicates whether to trigger alert actions.
  • force_dispatch: A Boolean that indicates whether to start a new search if another instance of this search is already running.

This example runs the search that was created above and shows how to poll the status to determine when the search has completed. Once the search has finished, it retrieves the search results from the Job object, displaying the raw XML results.

from time import sleep
import sys
 
...
 
# Retrieve the new search
mysavedsearch = service.saved_searches["Test Search"]

For an example of using the XML reader to parse results, see the To create a basic oneshot search and display results example.

Delete a saved search using the splunklib.client.SavedSearches.delete(name)(Opens new window) method. Any jobs for the saved search are not deleted.

This example shows how to delete a saved search:

# Delete the test search
service.saved_searches.delete("Test Search")

Parameters

The following parameters are available for saved searches.

Collection parameters

The following parameters are available when retrieving a collection of saved searches.

Parameter
Description
count
A number that indicates the maximum number of entries to return. A value of 0 means all entries are returned.
earliest_time
A string that contains all the scheduled times starting from this time. (not just the next run time).
latest_time
A string that contains all the scheduled times until this time.
offset
A number that specifies the index of the first item to return. For oneshot inputs, this value refers to the current position in the source file, indicating how much of the file has been read.
search
A string that specifies a search expression to filter the response with, matching field values against the search expression. For example, "search=foo" matches any object that has "foo" as a substring in a field, and "search=field_name%3Dfield_value" restricts the match to a single field.
sort_dir
An enum value that specifies how to sort entries. Valid values are "asc" (ascending order) and "desc" (descending order).
sort_key
A string that specifies the field to sort by.
sort_mode
An enum value that specifies how to sort entries. Valid values are "auto", "alpha" (alphabetically), "alpha_case" (alphabetically, case sensitive), or "num" (numerically).

Saved search parameters

The properties that are available for saved searches correspond to the parameters for the saved/searches endpoint(Opens new window) in the Splunk Enterprise REST API Reference Manual.

For an example of setting properties, see To view and modify the properties of a saved search.