我正在尝试使用正则表达式将一条线拆分为一个数组。 我的行包含一个apache日志,我正在寻找使用sql进行拆分。
我尝试了分割和数组功能,但没有。
Select split('10.10.10.10 - - [08/Sep/2015:00:00:03 +0000] "GET /index.html HTTP/1.1" 206 - - "Apache-HttpClient" -', '^([^ ]+) ([^ ]+) ([^ ]+) \[([^\]]+)\] "([^"]+)" \d+ - - "([^"]+)".*') ;
我期待一个包含6个元素的数组
由于
答案 0 :(得分:3)
SPLIT
函数会在模式上拆分字符串。由于您提供的模式字符串匹配整个输入,因此无需返回任何内容。因此是一个空数组。
import org.apache.spark.sql.functions.{regexp_extract, array}
val pattern = """^([^ ]+) ([^ ]+) ([^ ]+) \[([^\]]+)\] "([^"]+)" \d+ - - "([^"]+)".*"""
val df = sc.parallelize(Seq((
1L, """10.10.10.10 - - [08/Sep/2015:00:00:03 +0000] "GET /index.html HTTP/1.1" 206 - - "Apache-HttpClient" -"""
))).toDF("id", "log")
这里需要的是regex_extract
:
val exprs = (1 to 6).map(i => regexp_extract($"log", pattern, i).alias(s"_$i"))
df.select(exprs:_*).show
// +-----------+---+---+--------------------+--------------------+-----------------+
// | _1| _2| _3| _4| _5| _6|
// +-----------+---+---+--------------------+--------------------+-----------------+
// |10.10.10.10| -| -|08/Sep/2015:00:00...|GET /index.html H...|Apache-HttpClient|
// +-----------+---+---+--------------------+--------------------+-----------------+
或例如UDF:
val extractFromLog = udf({
val ip = new Regex(pattern)
(s: String) => s match {
// Lets ignore some fields for simplicity
case ip(ip, _, _, ts, request, client) =>
Some(Array(ip, ts, request, client))
case _ => None
}
})
df.select(extractFromLog($"log"))