Search code examples
splunksplunk-query

Assigning a subsearch result to a variable


I have a Splunk dashboard that shows traffic across two sites. I need to get a) the number of users for each domain and b) the total users for use in the dashboard. At this time, I have the following Simple XML:

  <search id="app_logs">
    <query>
      index=my_logs
      | eval domain1Count = [
          search "Middleware" "www.example-domain-1.com"
          | stats distinct_count(UserId) as domain1Users
        ] 

      | eval domain2Count = [
          search "Middleware 2" "www.example-domain-2.com"
          | stats distinct_count(UserId) as domain2Users
        ] 
    
      | eval totalCount = domain1Count + domain2Count
      | table 
        domain1Count
        domain2Count
        totalCount
    </query>

    <done>
      <set token="domain1Count">$result.domain1Count$</set>
      <set token="domain2Count">$result.domain2Count$</set>
      <set token="totalCount">$result.totalCount$</set>
    </done>
  </search>

The query doesn't work as is. The eval statements generate errors. However, the queries on the right side of the eval statements work as expected. How do I assign a variable the single value of a subsearch so that I can use the values as tokens?


Solution

  • I would probably do this as separate searches on the dashboard, unless there was an overwhelming need to have it all in one

    Alternatively, you could | append each search, & | stats values at the ed like this:

    index=ndx sourcetype=srctp "middleware 1" "domain1.tld" userid=*
    | stats dc(userid) as domain1users
    | append
        [| search index=ndx sourcetype=srctp "middleware 2" "domain2.tld" userid=*
        | stats dc(userid) as domain2users ]
    | stats values(*) as *
    

    Then in your <done>...</done> clause, have multiple <set token="...">$results.domain{N}users</set> pairs