Splunk 简明教程
Splunk - Search Macros
搜索宏是可重复使用的搜索处理语言(SPL)块,您可以将其插入到其他搜索中。在您希望对数据集中的不同部分或值动态应用相同的搜索逻辑时使用这些宏。它们可以动态获取参数,并且搜索结果将根据新值更新。
Search macros are reusable blocks of Search Processing Language (SPL) that you can insert into other searches. They are used when you want to use the same search logic on different parts or values in the data set dynamically. They can take arguments dynamically and the search result will be updated as per the new values.
Macro Creation
若要创建搜索宏,请转至 settings → Advanced Search → Search macros → Add new 。这会显示以下屏幕,您可以在其中开始创建宏。
To create the search macro, we go to the settings → Advanced Search → Search macros → Add new. This brings up the below screen where we start creating the macro.

Macro Scenario
我们希望从 web_applications 日志显示关于文件大小的各种统计信息。这些统计信息是关于日志中使用字节字段的文件大小的最大值、最小值和平均值。结果应针对日志中列出的每个文件显示这些统计信息。
We want to show various stats about the file size from the web_applications log. The stats are about max, min and avg value of the filesize using the bytes field in the log. The result should display these stats for each file listed in the log.
因此,此处统计信息类型本质上是动态的。统计函数的名称将作为参数传递给宏。
So here the type of the stats is dynamic in nature. The name of the stats function will be passed as an argument to the macro.
Defining the Macro
接下来,我们通过设置各种属性来定义宏,如下面的屏幕所示。宏的名称包含 (1),表示在搜索字符串中使用宏时要传入一个参数。 fun 是在搜索查询中执行期间将传递给宏的参数。
Next, we define the macro by setting various properties as shown in the below screen. The name of the macro contains (1), indicating that there is one argument to be passed into the macro when it is used in the search string. fun is the argument which will be passed on to the macro during execution in the search query.

Using the Macro
若要使用宏,我们需要将其作为搜索字符串的一部分。当为参数传递不同的值时,我们会看到预期的不同结果。
To use the macro, we make it a part of the search string. On passing different values for the argument we see different results as expected.
考虑查找文件(以字节为单位)的平均大小。我们传递 avg 作为参数,并获得以下所示的结果。宏已作为搜索查询的一部分保留在 ` 符号下。
Consider finding the average size in bytes of the files. We pass avg as the argument and get the result as shown below. The macro has been kept under ` sign as part of the search query.

类似地,如果我们想要日志中每个文件的文件大小最大值,那么我们将 max 用作参数。结果如下所示。
Similarly, if we want the maximum file size for each of the files present in the log, then we use max as the argument. The result is as shown below.
