2015-09-07 41 views
1

在Spark SQL的帮助下,我试图过滤掉属于特定组类别的所有业务项目。如何通过多值列过滤JSON数据

的数据是从JSON文件加载:

businessJSON = os.path.join(targetDir, 'yelp_academic_dataset_business.json') 
businessDF = sqlContext.read.json(businessJSON) 

文件的架构如下:

businessDF.printSchema() 

root 
    |-- business_id: string (nullable = true) 
    |-- categories: array (nullable = true) 
    | |-- element: string (containsNull = true) 
    .. 
    |-- type: string (nullable = true) 

我试图提取连接到餐饮业的所有业务:

restaurants = businessDF[businessDF.categories.inSet("Restaurants")] 

但它不工作,因为据我所知,预期的列类型应该是一个字符串,b在我的情况下,这是数组。关于它告诉我一个例外:

Py4JJavaError: An error occurred while calling o1589.filter. 
: org.apache.spark.sql.AnalysisException: invalid cast from string to array<string>; 

能否请您提出任何其他的方式来获得我想要什么?

+0

@亚切克,郭先生我不知道你的问题的修正是完全正确的。其实我没有尝试过使用inSet方法,但是找到了如何滤除基于多值字段的所有项目的方法。 –

回答

1

UDF如何?

from pyspark.sql.functions import udf, col, lit 
from pyspark.sql.types import BooleanType 

contains = udf(lambda xs, val: val in xs, BooleanType()) 
df = sqlContext.createDataFrame([Row(categories=["foo", "bar"])]) 

df.select(contains(df.categories, lit("foo"))).show() 
## +----------------------------------+ 
## |PythonUDF#<lambda>(categories,foo)| 
## +----------------------------------+ 
## |        true| 
## +----------------------------------+ 

df.select(contains(df.categories, lit("foobar"))).show() 
## +-------------------------------------+ 
## |PythonUDF#<lambda>(categories,foobar)| 
## +-------------------------------------+ 
## |        false| 
## +-------------------------------------+ 
+0

谢谢。这样可行。 –