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

How to run searches and jobs using the Splunk Enterprise SDK for Python

Searches run in the following modes, which determine when and how you can retrieve results:

  • Normal: A normal search runs asynchronously. It returns a search job immediately. Poll the job to determine its status. You can retrieve the results when the search has finished. You can also preview the results if "preview" is enabled. Normal mode works with real-time searches.
  • Blocking: A blocking search runs synchronously. It does not return a search job until the search has finished, so there is no need to poll for status. Blocking mode doesn't work with real-time searches.
  • One-shot: A one-shot search is a blocking search that is scheduled to run immediately. Instead of returning a search job, this mode returns the results of the search once completed. Because this is a blocking search, the results are not available until the search has finished.
  • Export: An export search is another type of search operation that runs immediately, does not return a search job, and starts streaming results immediately.

For searches that produce search jobs (normal and blocking), the search results are saved for a period of time on the server and can be retrieved on request. For searches that stream the results (one-shot and export), the search results are not retained on the server. If the stream is interrupted for any reason, the results are not recoverable without running the search again.

The job APIs

The classes for working with jobs 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 jobs and creating a new one:

# Connect to Splunk Enterprise
service = client.connect(...)
 
# Get the collection of search jobs
jobs = service.jobs
 
# Create a search job
job = jobs.create(query)

Code examples

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

To list search jobs for the current user

This example shows how to use the splunklib.client.Jobs(Opens new window) class to retrieve the collection of jobs available to the current user:

# Get the collection of jobs and find out how many there are
jobs = service.jobs
 
print "There are", len(jobs), "jobs available to the current user"
print "\nSearch IDs:\n " + "\n ".join([job.sid for job in jobs])

To create a blocking search and display properties of the job

Running a blocking search creates a search job and runs the search synchronously in "blocking" mode. The job is returned after the search has finished and all the results are in.

When you create a search job, you need to set the parameters of the job as a dictionary of key-value pairs. For a list of all the possible parameters, see the parameters for the search/jobs endpoint(Opens new window) in the Splunk Enterprise REST API Reference Manual.

This example runs a blocking search, waits for the job to finish, and then displays some final statistics (see the example after this one to display the results):

# Get the collection of jobs
jobs = service.jobs
 
# Run a blocking search--search everything, return 1st 100 events
kwargs_blockingsearch = {"exec_mode": "blocking"}
searchquery_blocking = "search * | head 100"
 
print "Wait for the search to finish..."

To create a normal search, poll for completion, and display results

Running a normal search creates a search job and immediately returns the search ID, so you need to poll the job to find out when the search has finished.

When you create a search job, set the parameters of the job as named arguments to the Jobs.create(Opens new window) method. For a list of all the possible parameters, see the parameters for the search/jobs endpoint(Opens new window) in the Splunk Enterprise REST API Reference Manual.

This example runs a normal search, waits for the job to finish, and then displays the results as JSON objects using the JSONResultsReader(Opens new window) class along with some final statistics:

import sys
from time import sleep
import splunklib.results as results
 
# ...
#
# Initialize your service like so
# import splunklib.client as client
Info

JSONResultsReader requires the query parameter 'output_mode' set to 'json' for the search job.

To create a basic one-shot search and display results

The simplest way to get data out of Splunk Enterprise is with a one-shot search, which creates a synchronous search. Unlike normal or blocking searches, the one-shot search does not create and return a search job, but rather it blocks until the search finishes and then returns a stream containing the events. To set properties for the search (for example, to specify a time range to search), create a dictionary with the property key-value pairs. Some common properties are:

  • output_mode: Specifies the output format of the results (XML, JSON, JSON_COLS, JSON_ROWS, CSV, ATOM, or RAW).
  • earliest_time: Specifies the earliest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
  • latest_time: Specifies the latest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
  • rf: Specifies one or more fields to add to the search.

For a full list of possible properties, see the parameters for the search/jobs endpoint(Opens new window) in the Splunk Enterprise REST API Reference Manual, although most of these parameters don't apply to a one-shot search.

This example runs a one-shot search within a specified time range by calling the one-shot(Opens new window) method. It then displays the results as JSON objects using the JSONResultsReader(Opens new window) class.

Info

If you don't see any search results, that means there aren't any in the specified time range. Just modify the date and time as needed for your data set.

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
import splunklib.results as results
 
...
 
# Run a one-shot search and display the results using the results reader
 
# Set the parameters for the search:
Info

JSONResultsReader requires the query parameter output_mode set to json for the one-shot search job.

By default, one-shot searches will return a maximum of 100 events, even if there are more than 100 events in the search results. To return more than 100 events, add the following parameter to your one-shot search's arguments:

    "count": 0

The count parameter, when set to zero, indicates that there is no limit to the number of events to be returned.

To create a basic export search and display results

An export search is the most reliable way to return a large set of results because exporting returns results in a stream, rather than as a search job that is saved on the server. So any server-side limitations to the number of results that can be returned don't apply to export searches.

You can run an export search in normal and real-time modes. Export searches run right away, and immediately start streaming data. Running an export search is more efficient than running a preview search because it streams results directly to you, instead of having to write them out to disk to make them available later. As soon as results are ready, you receive them.

Like one-shot searches, export searches run immediately, do not create jobs for the search, and start streaming results immediately. To set properties for the search (for example, to specify a time range to search), create a dictionary with the property key-value pairs. Some common properties are:

  • search_mode: Specifies the search mode (normal or realtime).
  • earliest_time: Specifies the earliest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
  • latest_time: Specifies the latest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string.
  • rf: Specifies one or more fields to add to the search.

For a full list of possible properties, see the parameters for the search/jobs endpoint(Opens new window) in the Splunk Enterprise REST API Reference Manual.

This example runs an export search of your internal index over the last hour by calling the export(Opens new window) method. This example then displays the results as JSON objects using the JSONResultsReader class(Opens new window). Finally, it displays whether the results are a preview from a running search or from a completed search. For more about displaying preview results, see To display preview results.

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
import splunklib.results as results
 
...
 
# Run an export search and display the results using the results reader.
 
# Set the parameters for the search:
Info

JSONResultsReader requires the query parameter output_mode set to json for the export job.

Info

If you don't see any search results, that means there aren't any in the specified time range. Just modify the date and time as needed for your data set.

Parameters

The following parameters are available for search jobs.

Collection parameters

By default, all entries are returned when you retrieve a collection. But by using the parameters below, you can also specify the number of entities to return and how to sort them. These parameters are available whenever you retrieve a collection.

Parameter
Description
count
A number that indicates the maximum number of entities to return. A value of "0" indicates no maximum.
offset
A number that specifies the index of the first entity to return.
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 entities. 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 entities. Valid values are "auto", "alpha" (alphabetically), "alpha_case" (alphabetically, case sensitive), or "num" (numerically).

Search job parameters

For a full list, see the parameters for the search/jobs endpoint(Opens new window) in the Splunk Enterprise REST API Reference Manual.