How to work with saved searches using the Splunk SDK for JavaScript

The most fundamental feature in Splunk® 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. The default format for JavaScript is JSON_ROWS.

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 splunkjs.Service class. Retrieve a collection, and from there you can access individual items in the collection and create new ones.

Code examples

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

The following parameters are available for saved searches:

To list saved searches

This example shows how to retrieve and list the saved searches in the saved search collection. If you don't explicitly specify a namespace, the default one is used (to continue the How to connect to Splunk example, the current user is "admin" and the current app is the default "search").

// List all saved searches for the current username
var mySavedSearches = service.savedSearches();
mySavedSearches.fetch(function(err, mySavedSearches) {

    console.log("There are " + mySavedSearches.list().length + " saved searches");

    var savedSearchColl = mySavedSearches.list();

    for(var i = 0; i < savedSearchColl.length; i++) {
        var search = savedSearchColl[i];
        console.log(i + ": " + search.name);
        console.log("    Query: " + search.properties().search + "\n");
    }
});

To retrieve a collection for a specific namespace—for example, to list the saved searches available to a specific username—provide the namespace as arguments to the splunkjs.Service.SavedSearches method. This example lists the saved searches for the user "username":

// Get saved searches for "username"
var moreSavedSearches = service.savedSearches({owner: "username", app: "search"});

moreSavedSearches.fetch(function (err, moreSavedSearches) {
  console.log("There are " + moreSavedSearches.list().length + " saved searches for 'username'");
});

To view the history of a saved 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:

// Retrieve the collection of saved searches
var mySavedSearches = service.savedSearches();

mySavedSearches.fetch(function(err, mySavedSearches) {
  var savedSearchColl = mySavedSearches.list();

  // Loop through the collection and get info about each search
  for(var i = 0; i < savedSearchColl.length; i++) {
    var search = savedSearchColl[i];

    search.history(function(err, jobs, search) {
      console.log("Jobs for " + search.name + ": ");

      for(var j = 0; j < jobs.length; j++) {
        console.log("    " + jobs[j].sid);
      }

    });
  }
});

To create a saved search

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 (the possible properties are summarized in Saved search parameters). Or, modify properties after you have created the saved search.

This example shows how to create a basic saved search:

// Retrieve the collection of saved searches
var mySavedSearches = service.savedSearches();

// Specify a name and search query
var searchName = "Test Search"; 
// Note: Do not include the 'search' keyword for a saved search
var searchQuery = "* &#124; head 10";

// Create the saved search
mySavedSearches.create({
  name: searchName,
  search: searchQuery
}, function(err, newSearch) {
  console.log("A new saved search was created");
});

To view and modify the properties of a saved search

To access properties of a saved search, use the properties method of the saved search object along with the property's name (see Saved search parameters for a list of all the possible properties for a saved search).

To set properties, pass property key-value pairs to the entity's update method to make the changes on the server. Next, call the entity's fetch method to update your local, cached copy of the object with these changes.

This example shows how to view properties for the saved search that was created earlier, then shows how to set the description and schedule the saved search in cron format:

// The saved search created earlier
var searchName = "Test Search";

// Retrieve the saved search collection
var mySavedSearches = service.savedSearches();

mySavedSearches.fetch(function(err, mySavedSearches) {

  // Retrieve a specific saved search
  var mySavedSearch = mySavedSearches.item(searchName);

  // Display some properties
  console.log("Name:                " + mySavedSearch.name);
  console.log("Query:               " + mySavedSearch.properties().search);
  console.log("Description:         " + mySavedSearch.properties().description);
  console.log("Scheduled:           " + mySavedSearch.properties().is_scheduled);
  console.log("Next scheduled time: " + mySavedSearch.properties().next_scheduled_time);

  // Modify the description and schedule the saved search
  mySavedSearch.update({
    description: "This is a test search",
    is_scheduled: true,         // Schedule the search
    cron_schedule: "15 4 * * 6" // Runs the search on Saturdays at 4:15am
  }, function() {
    console.log("\n...properties were modified...")
  });

  // Create a small delay to allow time for the update between server and client
  splunkjs.Async.sleep(2000, function() {

    // Update the local copy of the object with changes
    mySavedSearch.fetch(function(err, mySavedSearch) {

      // Display the updated properties to verify
      console.log("\nUpdated properties:");
      console.log("Description:         " + mySavedSearch.properties().description);
      console.log("Scheduled:           " + mySavedSearch.properties().is_scheduled);
      console.log("Next scheduled time: " + mySavedSearch.properties().next_scheduled_time);
    });
  });
});

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 splunkjs.Service.SavedSearch.dispatch method to run a saved search, which returns a splunkjs.Service.Job object that corresponds to the search job. This 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.

Once the search has finished, retrieve the search results from the Job object. The default output format is JSON_ROWS.

This example runs the search that was created above, shows how to poll the status using the splunkjs.Job.track function to determine when the search has completed, and displays the raw results:

// The saved search created earlier
var searchName = "Test Search";

// Retrieve the saved search collection
var mySavedSearches = service.savedSearches();

mySavedSearches.fetch(function(err, mySavedSearches) {

  // Retrieve the saved search that was created earlier
  var mySavedSearch = mySavedSearches.item(searchName);

  // Run the saved search and poll for completion
  mySavedSearch.dispatch(function(err, job) {

    // Display the job's search ID
    console.log("Job SID: ", job.sid);

    // Poll the status of the search job
    job.track({
      period: 200
    }, {
      done: function(job) {
        console.log("Done!");

        // Print out the statics
        console.log("Job statistics:");
        console.log("  Event count:  " + job.properties().eventCount);
        console.log("  Result count: " + job.properties().resultCount);
        console.log("  Disk usage:   " + job.properties().diskUsage + " bytes");
        console.log("  Priority:     " + job.properties().priority);

        // Get 10 results and print them
        job.results({
          count: 10
        }, function(err, results, job) {
          console.log(JSON.stringify(results));
        });
      },
      failed: function(job) {
        console.log("Job failed")
      },
      error: function(err) {
        done(err);
      }
    });
  });
});

To delete a saved search

You can delete a saved search using the splunkjs.Service.Entity.remove method. Any jobs for the saved search are not deleted.

This example shows how to delete a saved search:

// The saved search created earlier
var searchName = "Test Search";

// Retrieve the saved search collection
var mySavedSearches = service.savedSearches();

mySavedSearches.fetch(function(err, mySavedSearches) {

  // Retrieve the saved search that was created earlier
  var mySavedSearch = mySavedSearches.item(searchName);

  // Determine whether the saved search exists before deleting it
  if(!mySavedSearch) {
    console.log("There is no saved search named '" + searchName + "'");
  } else {
    mySavedSearch.remove();
    console.log("Deleted the saved search '" + searchName + "'");
  }

});

Collection parameters

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

Parameter

Description

countA number that indicates the maximum number of entries to return. A value of 0 means all entries are returned.
earliest_timeA string that contains all the scheduled times starting from this time (not just the next run time).
latest_timeA string that contains all the scheduled times until this time.
offsetA 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.
searchA 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_dirAn enum value that specifies how to sort entries. Valid values are "asc" (ascending order) and "desc" (descending order).
sort_keyA string that specifies the field to sort by.
sort_modeAn 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 in the REST API.

This table summarizes the properties you can set for a saved search.

Parameter

Description

nameRequired. A string that contains the name of the saved search.
searchRequired. A string that contains the search query.
action.*A string with wildcard arguments to specify specific action arguments.
action.emailA Boolean that indicates the state of the email alert action. Read only.
action.email.auth_passwordA string that specifies the password to use when authenticating with the SMTP server. Normally this value is set while editing the email settings, but you can set a clear text password here that is encrypted when Splunk is restarted.
action.email.auth_usernameA string that specifies the username to use when authenticating with the SMTP server. If this is empty string, authentication is not attempted.
action.email.bccA string that specifies the BCC email address to use if "action.email" is enabled.
action.email.ccA string that specifies the CC email address to use if "action.email" is enabled.
action.email.commandA string that contains the search command (or pipeline) for running the action.
action.email.formatAn enum value that indicates the format of text and attachments in the email ("plain", "html", "raw", or "csv"). Use "plain" for plain text.
action.email.fromA string that specifies the email sender's address.
action.email.hostnameA string that specifies the hostname used in the web link (URL) that is sent in email alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.email.inlineA Boolean that indicates whether the search results are contained in the body of the email.
action.email.mailserverA string that specifies the address of the MTA server to be used to send the emails.
action.email.maxresultsThe maximum number of search results to send when "action.email" is enabled.
action.email.maxtimeA number indicating the maximum amount of time an email action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d"), for example "5d".
action.email.pdfviewA string that specifies the name of the view to deliver if "action.email.sendpdf" is enabled.
action.email.preprocess_resultsA string that specifies how to pre-process results before emailing them.
action.email.reportCIDFontListMembers of an enumeration in a space-separated list specifying the set (and load order) of CID fonts for handling Simplified Chinese(gb), Traditional Chinese(cns), Japanese(jp), and Korean(kor) in Integrated PDF Rendering.
action.email.reportIncludeSplunkLogoA Boolean that indicates whether to include the Splunk logo with the report.
action.email.reportPaperOrientationAn enum value that indicates the paper orientation ("portrait" or "landscape").
action.email.reportPaperSizeAn enum value that indicates the paper size for PDFs ("letter", "legal", "ledger", "a2", "a3", "a4", or "a5").
action.email.reportServerEnabledA Boolean that indicates whether the PDF server is enabled.
action.email.reportServerURLA string that contains the URL of the PDF report server, if one is set up and available on the network.
action.email.sendpdfA Boolean that indicates whether to create and send the results as a PDF.
action.email.sendresultsA Boolean that indicates whether to attach search results to the email.
action.email.subjectA string that specifies the subject line of the email.
action.email.toA string that contains a comma- or semicolon-delimited list of recipient email addresses. Required if this search is scheduled and "action.email" is enabled.
action.email.track_alertA Boolean that indicates whether running this email action results in a trackable alert.
action.email.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this email action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.email.use_sslA Boolean that indicates whether to use secure socket layer (SSL) when communicating with the SMTP server.
action.email.use_tlsA Boolean that indicates whether to use transport layer security (TLS) when communicating with the SMTP server.
action.email.width_sort_columnsA Boolean that indicates whether columns should be sorted from least wide to most wide, left to right. This value is only used when "action.email.format"="plain", indicating plain text.
action.populate_lookupA Boolean that indicates the state of the populate-lookup alert action. Read only.
action.populate_lookup.commandA string that specifies the search command (or pipeline) to run the populate-lookup alert action.
action.populate_lookup.destA string that specifies the name of the lookup table or lookup path to populate.
action.populate_lookup.hostnameA string that specifies the host name used in the web link (URL) that is sent in populate-lookup alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.populate_lookup.maxresultsThe maximum number of search results to send in populate-lookup alerts.
action.populate_lookup.maxtimeThe number indicating the maximum amount of time an alert action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
action.populate_lookup.track_alertA Boolean that indicates whether running this populate-lookup action results in a trackable alert.
action.populate_lookup.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this populate-lookup action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.rssA Boolean that indicates the state of the RSS alert action. Read only.
action.rss.commandA string that contains the search command (or pipeline) that runs the RSS alert action.
action.rss.hostnameA string that contains the host name used in the web link (URL) that is sent in RSS alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.rss.maxresultsThe maximum number of search results to send in RSS alerts.
action.rss.maxtimeThe maximum amount of time an RSS alert action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
action.rss.track_alertA Boolean that indicates whether running this RSS action results in a trackable alert.
action.rss.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this RSS action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.scriptA Boolean that indicates the state of the script alert action. Read only.
action.script.commandA string that contains the search command (or pipeline) that runs the script action.
action.script.filenameA string that specifies the file name of the script to call, which is required if "action.script" is enabled.
action.script.hostnameA string that specifies the hostname used in the web link (URL) that is sent in script alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.script.maxresultsThe maximum number of search results to send in script alerts.
action.script.maxtimeThe maximum amount of time a script action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
action.script.track_alertA Boolean that indicates whether running this script action results in a trackable alert.
action.script.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this script action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.summary_indexA Boolean that indicates the state of the summary index alert action. Read only.
action.summary_index._nameA string that specifies the name of the summary index where the results of the scheduled search are saved.
action.summary_index.commandA string that contains the search command (or pipeline) that runs the summary-index action.
action.summary_index.hostnameA string that specifies the hostname used in the web link (URL) that is sent in summary-index alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.summary_index.inlineA Boolean that indicates whether to run the summary indexing action as part of the scheduled search.
action.summary_index.maxresultsThe maximum number of search results to send in summary-index alerts.
action.summary_index.maxtimeA number indicating the maximum amount of time a summary-index action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d"), for example "5d".
action.summary_index.track_alertA Boolean that indicates whether running this summary-index action results in a trackable alert.
action.summary_index.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this summary-index action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
actionsA string that contains a comma-delimited list of actions to enable, for example "rss,email".
alert.digest_modeA Boolean that indicates whether Splunk applies the alert actions to the entire result set or digest ("true"), or to each individual search result ("false").
alert.expiresThe amount of time to show the alert in the dashboard. The valid format is number followed by a time unit ("s", "m", "h", or "d").
alert.severityA number that indicates the alert severity level (1=DEBUG, 2=INFO, 3=WARN, 4=ERROR, 5=SEVERE, 6=FATAL).
alert.suppressA Boolean that indicates whether alert suppression is enabled for this scheduled search.
alert.suppress.fieldsA string that contains a comma-delimited list of fields to use for alert suppression.
alert.suppress.periodA value that indicates the alert suppression period, which is only valid when "Alert.Suppress" is enabled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
alert.trackAn enum value that indicates how to track the actions triggered by this saved search. Valid values are: "true" (enabled), "false" (disabled), and "auto" (tracking is based on the setting of each action).
alert_comparatorA string that contains the alert comparator. Valid values are: "greater than", "less than", "equal to", "rises by", "drops by", "rises by perc", and "drops by perc".
alert_conditionA string that contains a conditional search that is evaluated against the results of the saved search.
alert_thresholdA value to compare to before triggering the alert action. Valid values are: integer or integer%. If this value is expressed as a percentage, it indicates the value to use when "alert_comparator" is set to "rises by perc" or "drops by perc".
alert_typeA string that indicates what to base the alert on. Valid values are: "always", "custom", "number of events", "number of hosts", and "number of sources". This value is overridden by "alert_condition" if specified.
args.*A string containing wildcard arguments for any saved search template argument, such as "args.username"="foobar" when the search is search $username$.
auto_summarizeA Boolean that indicates whether the scheduler ensures that the data for this search is automatically summarized.
auto_summarize.commandA string that contains a search template that constructs the auto summarization for this search.
auto_summarize.cron_scheduleA string that contains the cron schedule for probing and generating the summaries for this saved search.
auto_summarize.dispatch.earliest_timeA string that specifies the earliest time for summarizing this saved search. The time can be relative or absolute; if absolute, use the "dispatch.time_format" parameter to format the value.
auto_summarize.dispatch.latest_timeA string that contains the latest time for summarizing this saved search. The time can be relative or absolute; if absolute, use the "dispatch.time_format" parameter to format the value.
auto_summarize.dispatch.ttlThe number of seconds indicating the time to live (in seconds) for the artifacts of the summarization of the scheduled search. If the value is a number followed by "p", it is the number of scheduled search periods.
auto_summarize.max_disabled_bucketsA number that specifies the maximum number of buckets with the suspended summarization before the summarization search is completely stopped, and the summarization of the search is suspended for the "auto_summarize.suspend_period" parameter.
auto_summarize.max_summary_ratioA number that specifies the maximum ratio of summary size to bucket size, which specifies when to stop summarization and deem it unhelpful for a bucket. The test is only performed if the summary size is larger than the value of "auto_summarize.max_summary_size".
auto_summarize.max_summary_sizeA number that specifies the minimum summary size, in bytes, before testing whether the summarization is helpful.
auto_summarize.max_timeA number that specifies the maximum time (in seconds) that the summary search is allowed to run. Note that this is an approximate time because the summary search stops at clean bucket boundaries.
auto_summarize.suspend_periodA string that contains the time indicating when to suspend summarization of this search if the summarization is deemed unhelpful.
auto_summarize.timespanA string that contains a comma-delimited list of time ranges that each summarized chunk should span. This comprises the list of available granularity levels for which summaries would be available.
cron_scheduleA string that contains the cron-style schedule for running this saved search.
descriptionA string that contains a description of this saved search.
disabledA Boolean that indicates whether the saved search is enabled.
dispatch.*A string that specifies wildcard arguments for any dispatch-related argument.
dispatch.bucketsThe maximum number of timeline buckets.
dispatch.earliest_timeA time string that specifies the earliest time for this search. Can be a relative or absolute time. If this value is an absolute time, use "dispatch.time_format" to format the value.
dispatch.latest_timeA time string that specifies the latest time for this saved search. Can be a relative or absolute time. If this value is an absolute time, use "dispatch.time_format" to format the value.
dispatch.lookupsA Boolean that indicates whether lookups for this search are enabled.
dispatch.max_countThe maximum number of results before finalizing the search.
dispatch.max_timeThe maximum amount of time (in seconds) before finalizing the search.
dispatch.reduce_freqThe number of seconds indicating how frequently Splunk runs the MapReduce reduce phase on accumulated map values.
dispatch.rt_backfillA Boolean that indicates whether to back fill the real-time window for this search. This value is only used for a real-time search.
dispatch.spawn_processA Boolean that indicates whether Splunk spawns a new search process when running this saved search.
dispatch.time_formatA string that defines the time format that Splunk uses to specify the earliest and latest time.
dispatch.ttlThe number indicating the time to live (ttl) for artifacts of the scheduled search (the time before the search job expires and artifacts are still available), if no alerts are triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
displayviewA string that contains the default UI view name (not label) in which to load the results.
is_scheduledA Boolean that indicates whether this saved search runs on a schedule.
is_visibleA Boolean that indicates whether this saved search is visible in the saved search list.
max_concurrentThe maximum number of concurrent instances of this search the scheduler is allowed to run.
next_scheduled_timeA string that indicates the next scheduled time for this saved search. Read only.
qualifiedSearchA string that is computed during run time. Read only.
realtime_scheduleA Boolean that specifies how the scheduler computes the next time a scheduled search is run:
  • When "true": The schedule is based on the current time. The scheduler might skip some scheduled periods to make sure that searches over the most recent time range are run.
  • When "false": The schedule is based on the last search run time (referred to as "continuous scheduling") and the scheduler never skips scheduled periods. However, the scheduler might fall behind depending on its load. Use continuous scheduling whenever you enable the summary index option ("action.summary_index").

The scheduler tries to run searches that have real-time schedules enabled before running searches that have continuous scheduling enabled.

request.ui_dispatch_appA string that contains the name of the app in which Splunk Web dispatches this search.
request.ui_dispatch_viewA string that contains the name of the view in which Splunk Web dispatches this search.
restart_on_searchpeer_addA Boolean that indicates whether a real-time search managed by the scheduler is restarted when a search peer becomes available for this saved search. The peer can be one that is newly added or one that has become available after being down.
run_on_startupA Boolean that indicates whether this search is run when Splunk starts. If the search is not run on startup, it runs at the next scheduled time. It is recommended that you set this value to "true" for scheduled searches that populate lookup tables.
vsidA string that contains the view state ID that is associated with the view specified in the "displayview" attribute.