我正在使用Kafka传输JSON文件,并将每一行作为消息发送。密钥之一是用户的email
。
然后,我使用PySpark来计算每个窗口的唯一身份用户数,并使用他们的电子邮件进行识别。命令
def print_users_count(count):
print 'The number of unique users is:', count
print_users_count((lambda message: message['email']).distinct().count())
给我下面的错误。我该如何解决?
AttributeError Traceback (most recent call last)
<ipython-input-19-311ba744b41f> in <module>()
2 print 'The number of unique users is:', count
3
----> 4 print_users_count((lambda message: message['email']).distinct().count())
AttributeError: 'function' object has no attribute 'distinct'
这是我的PySpark代码:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import json
try:
sc.stop()
except:
pass
sc = SparkContext(appName="KafkaStreaming")
sc.setLogLevel("WARN")
ssc = StreamingContext(sc, 60)
# Define the PySpark consumer.
kafkaStream = KafkaUtils.createStream(ssc, bootstrap_servers, 'spark-streaming2', {topicName:1})
# Parse the incoming data as JSON.
parsed = kafkaStream.map(lambda v: json.loads(v[1]))
# Count the number of messages per batch.
parsed.count().map(lambda x:'Messages in this batch: %s' % x).pprint()
答案 0 :(得分:-1)
您未将lambda函数应用于任何内容。 message
引用了什么?不是lambda函数就是那个函数。这就是为什么您获得AttributeError: 'function' object has no attribute 'distinct'
的原因。它不会应用于任何数据,因此不会返回任何数据。您需要引用键email
所在的数据框。
有关pyspark.sql.functions.countDistinct(col, *cols)
和pyspark.sql.functions.approx_count_distinct
pyspark docs的信息,请参见pyspark文档。这应该是获得唯一计数的简单解决方案。