from pyspark.sql import functions as F
from pyspark.ml.feature import HashingTF, IDF
from pyspark.ml import Pipeline
from pyspark.sql.types import *
from pyspark.sql.functions import udf, split
import collections
def trim_array_elements(array_column):
return [e.strip() for e in array_column]
def buscar_palavras_chave(self):
# Prepare keywords for efficient lookup
keywords = self.categories_df.select(self.keyword_col)
keywords = keywords.withColumn('trimmed_keywords', trim_array_elements_udf(self.keyword_col))
# Create a map for fast keyword-to-category lookup
keyword_to_category_map = keywords.select('trimmed_keywords').distinct().rdd.flatMap(lambda x: x).collectAsMap()
# Create a HashingTF tokenizer
tokenizer = HashingTF(inputCol='trimmed_keywords', outputCol='tfFeatures')
# Create an IDF model
idf = IDF(inputCol='tfFeatures', outputCol='idfFeatures')
# Create the feature transform pipeline
feature_pipeline = Pipeline(stages=[tokenizer, idf])
# Apply the pipeline to the keywords
result = feature_pipeline.fit(keywords).transform(keywords)
# Function to process individual texts and identify matching categories
def processar_texto(text_features):
text_vec = text_features.idfFeatures
matching_categories = []
for keyword in keyword_to_category_map.keys():
if text_vec.indexOf(keyword_to_category_map[keyword]) >= 0:
matching_categories.append(keyword)
return matching_categories
# Apply the processing function to each text
result_df = self.text_df.withColumn('text_features', result.select('idfFeatures').where(col('id') == col('id')).collect()[0]['idfFeatures'])
result_df = result_df.withColumn("Categorias Encontradas", udf(processar_texto)(col('text_features')))
return result_df[['id', 'tx_trsc_segm', 'Categorias Encontradas']]
result_df.show(truncate=False) py4j.security.Py4JSecurityException: Method public org.apache.spark.rdd.RDD org.apache.spark.api.java.JavaRDD.rdd() is not whitelisted on class class org.apache.spark.api.java.JavaRDD
Assistant
The error you're encountering is due to an outdated or incorrect method for accessing RDDs within the Spark security context. This typically happens when you try to perform operations that are not allowed or require whitelisting in the current Spark context. Moreover, I noticed several issues and inefficiencies within your code, particularly with how you're trying to use the Spark DataFrame and ML APIs.
Here are some corrections and improvements that you can implement to resolve these issues:
Using UDF for Trimming: You don't actually need a UDF to trim strings in an array; you can use existing Spark SQL functions.
Proper Use of HashingTF and IDF: You're attempting to use HashingTF and IDF incorrectly for keyword-location purposes. Instead, you should tokenize the texts and look for occurrences of keyword tokens.
Correct Transformation: Collecting and indexing the features like you are doing might work with small datasets in local mode but will not scale with larger datasets or in a distributed setting.
Fix Missing Column Errors: Ensure the column names in your DataFrame operations match those specified.
File /databricks/spark/python/pyspark/sql/group.py:188, in GroupedData.agg(self, *exprs)
186 assert all(isinstance(c, Column) for c in exprs), "all exprs should be Column"
187 exprs = cast(Tuple[Column, ...], exprs)
--> 188 jdf = self._jgd.agg(exprs[0]._jc, _to_seq(self.session._sc, [c._jc for c in exprs[1:]]))
189 return DataFrame(jdf, self.session)
File /databricks/spark/python/pyspark/errors/exceptions/captured.py:194, in capture_sql_exception..deco(*a, **kw)
190 converted = convert_exception(e.java_exception)
191 if not isinstance(converted, UnknownException):
192 # Hide where the exception came from that shows a non-Pythonic
193 # JVM exception message.
--> 194 raise converted from None
195 else:
196 raise
AnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name id cannot be resolved. Did you mean one of the following? [keyword, Categoria, text_tokenized, prd.s_stbr_dcr_dcr_stt.stt_trsc.ma_liga, prd.s_stbr_dcr_dcr_stt.stt_trsc.].;
'Aggregate ['id, tx_trsc_segm#210], ['id, tx_trsc_segm#210, collect_set(Categoria#188, 0, 0) AS Categorias Encontradas#3669]
+- Join LeftOuter, array_contains(text_tokenized#3649, keyword#3646)
:- Project [ma_liga#218, tx_trsc_segm#210, split(lower(tx_trsc_segm#210), , -1) AS text_tokenized#3649]
: +- Filter ((ma_liga#218 = 202408) AND ((Contains(tx_trsc_segm#210, cartao) OR Contains(tx_trsc_segm#210, cartão)) OR Contains(tx_trsc_segm#210, cartões)))
: +- Project [ma_liga#218, tx_trsc_segm#210]
: +- SubqueryAlias prd.s_stbr_dcr_dcr_stt.stt_trsc
: +- Relation prd.s_stbr_dcr_dcr_stt.stt_trsc[ds_pipe#206,tx_nome_arqu#207,vl_inic_segm#208,vl_fina_segm#209,tx_trsc_segm#210,ds_pess_segm#211,dh_trsc#212,dh_refe_crga#213,tp_stmo_prdm#214,tx_stmo_scor#215,ds_mode_stmo_anls#216,dh_stmo_anls#217,ma_liga#218,dt_liga#219] parquet
+- Project [Categoria#188, keyword#3646]
+- Generate explode(trimmed_keywords#3641), false, [keyword#3646]
+- Project [Categoria#188, Palavras-Chave#189, trim_and_split_keywords(Palavras-Chave#189)#3640 AS trimmed_keywords#3641]
+- LogicalRDD [Categoria#188, Palavras-Chave#189], false
Assistant
The error you're encountering (UNRESOLVED_COLUMN.WITH_SUGGESTION) indicates that there is a column mismatch or a column that cannot be resolved in your groupBy clause. This can happen if the column names in your DataFrames do not match or get changed during transformations.
Let's go through the steps again to help you debug and correct the code:
Column Naming Consistency: Ensure that column names are consistent between the input DataFrames and all transformation steps.
Check for Column Addition and Changes During Joins and Explodes: Join transformations can inadvertently drop columns if not properly handled. Since you're using joins and array operations, ensure that the expected columns are present after each operation.
Let's modify and simplify the code to address these issues:
python
User
AnalysisException: [DATATYPE_MISMATCH.UNEXPECTED_INPUT_TYPE] Cannot resolve "lower(Palavras-Chave)" due to data type mismatch: Parameter 1 requires the "STRING" type, however "Palavras-Chave" has the type "ARRAY".;
mude a estrategia
Assistant
To address the AnalysisException you're encountering, it's important to consider how you handle the data type of the Palavras-Chave column. The error indicates that you're treating Palavras-Chave as a STRING when it is actually an ARRAY<STRING>.
Thus, you should adjust the processing strategy to correctly handle array data and perform operations on each element within the array. Let's rework the code to manage this properly:
Flatten Arrays: Explode the array of keywords to work with individual strings.
Perform Operations on Each Element: Use transformations like lower directly on the exploded strings.
Here's how you can rewrite the code to address these issues:
python
User
A column or function parameter with name id cannot be resolved. Did you mean one of the following? [keyword, Categoria, text_tokenized, prd.s_stbr_dcr_dcr_stt.stt_trsc.ma_liga, prd.s_stbr_dcr_dcr_stt.stt_trsc.tx_trsc_segm].;
'Aggregate ['id, tx_trsc_segm#210], ['id, tx_trsc_segm#210, collect_set(Categoria#188, 0, 0) AS Categorias Encontradas#3699]
+- Join LeftOuter, array_contains(text_tokenized#3679, keyword#3676)
:- Project [ma_liga#218, tx_trsc_segm#210, split(lower(tx_trsc_segm#210), , -1) AS text_tokenized#3679]
: +- Filter ((ma_liga#218 = 202408) AND ((Contains(tx_trsc_segm#210, cartao) OR Contains(tx_trsc_segm#210, cartão)) OR Contains(tx_trsc_segm#210, cartões)))
: +- Project [ma_liga#218, tx_trsc_segm#210]
: +- SubqueryAlias prd.s_stbr_dcr_dcr_stt.stt_trsc
: +- Relation prd.s_stbr_dcr_dcr_stt.stt_trsc[ds_pipe#206,tx_nome_arqu#207,vl_inic_segm#208,vl_fina_segm#209,tx_trsc_segm#210,ds_pess_segm#211,dh_trsc#212,dh_refe_crga#213,tp_stmo_prdm#214,tx_stmo_scor#215,ds_mode_stmo_anls#216,dh_stmo_anls#217,ma_liga#218,dt_liga#219] parquet
+- Project [Categoria#188, lower(keyword#3672) AS keyword#3676]
+- Project [Categoria#188, keyword#3672]
+- Generate explode(Palavras-Chave#189), false, [keyword#3672]
Assistant
The error suggests that the code is trying to group by a column named id which does not exist in the DataFrame after transformations. This could be because during the series of transformations and joins, the id column got lost or was never part of one of the DataFrames involved in the join operation.
Let's ensure the following:
Column Names After Join: Make sure that the id column is present in the DataFrame after any join operation.
Group by Existing Columns: Verify the column names in the DataFrame before performing any aggregation or grouping operation.
To fix the error, let's modify the code to ensure that the id column is retained through the transformations:
python
User
AnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name id cannot be resolved. Did you mean one of the following? [keyword, Categoria, Palavras-Chave].;
Assistant
It appears that the id column is missing from one of your DataFrames when attempting the aggregation step. This might happen if the transformations or joins inadvertently lead to the id column not being a part of the working DataFrame.
To troubleshoot and resolve this issue, we'll make sure that:
The id column exists in the text_df DataFrame before any join.
We're not losing this column in transformations.
We handle renaming correctly when such ambiguity arises.
Let's go through the code with added checks and ensure that the id column is clearly preserved:
python
User
AnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name id cannot be resolved. Did you mean one of the following? [keyword, Categoria, Palavras-Chave].;
Assistant
The error suggests that the column id cannot be resolved during grouping or selection and is not recognized in the context where you're attempting to use it. Therefore, let's methodically ensure that the id column is preserved through all transformations by focusing on maintaining the correct schema alignment through joins and manipulations:
Here is how you can adjust the code:
Ensure the id Column is Specifically Preserved in Both DataFrames: Before any transformations, make sure you retain id in text_df and correctly handle it through any joins.
Consistently Use the Correct id Column: Given the operations, make sure to maintain correct references and avoid shadowing it with aliases when not necessary.
Let's rewrite the code to ensure it explicitly keeps track of the id column through all steps:
python
User
AnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name id cannot be . Did you mean one of the following? [keyword, Categoria, Palavras-Chave].;
'Project ['id AS category_id#3706, Categoria#188, keyword#3708]
+- Generate explode(Palavras-Chave#189), false, [keyword#3708]
+- LogicalRDD [Categoria#188, Palavras-Chave#189], false mude a estrategia
Assistant
Given the AnalysisException you're experiencing, it suggests that the id column does not exist in the categories_df where you expect it. This is likely due to overlooking its necessity in the DataFrame creation or transformation.
Let's review and correct the approach to ensure the following:
We ensure that categories_df is correctly structured to include the id column.
Later operations are structured in a way that uses available and correct columns.
We'll switch to a new strategy that more explicitly creates and handles these columns with the expected structure:
Ensure DataFrame Schema: Make sure both DataFrames have the necessary columns before any processing step.
Use Explode Properly: Ensure the explode operation is correctly followed by lowercase transformation.
Here's a refactored approach:
python
User
AnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name id cannot be resolved. Did you mean one of the following? [keyword, Categoria, Palavras-Chave].;
desconsidere o id
Assistant
If we are encountering persistent issues with the id column and you've decided to proceed without it, we need to modify the solution so that it does not depend on the presence of id in your DataFrames. Instead, we'll focus on matching keywords within the text and associate categories based on keyword presence, and then we can directly show which categories relate to each text.
Here's a revised approach that removes dependencies on id:
python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Explode keywords to create a separate row for each keyword
exploded_keywords_df = self.categories_df.select(
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword'))) # Ensure keywords are lowercase
# Tokenize the text and lowercase it
tokenized_text_df = self.text_df.select(
col(self.text_col),
split(lower(col(self.text_col)), ' ').alias('text_tokenized')
)
# Join tokenized text with keywords
joined_df = tokenized_text_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy(self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# DataFrames de exemplo (ensure correct schema without using 'id')
categories_df = spark.createDataFrame([
('Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
('Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
('Cartões - Bloqueio', ['bloqueio'])
], ['Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
('Estou com problemas com a anuidade do meu cartão.'),
('Preciso de um bloqueio imediato no meu cartão.'),
('Gostaria de negociar a anuidade.')
], ['tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
User
tx_trsc_segm Categorias Encontradas
0 ...de outro cartão pelo site da Santander, né? []
1 ...descartões... Isso. []
2 ...transferência do senhor pra área de cartõe... []
3 ...visualizações que eles não saberam como é ... []
4 .com.br barra solicite seu cartão de crédito ... []
... ... ...
13135835 é um cartão on limit, tá? []
13135836 é, cartão com senha bloqueada você pode realiz... [] eliminar []
Assistant
If your resulting DataFrame is showing empty arrays ([]) for the column Categorias Encontradas and you wish to eliminate these records, you can apply a filter to remove rows where this column is empty. This can be achieved using the filter function in Spark DataFrames.
Here's how you can update the code to filter out rows with empty Categorias Encontradas before displaying the results:
python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains, size
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Explode keywords to create a separate row for each keyword
exploded_keywords_df = self.categories_df.select(
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword'))) # Ensure keywords are lowercase
# Tokenize the text and lowercase it
tokenized_text_df = self.text_df.select(
col(self.text_col),
split(lower(col(self.text_col)), ' ').alias('text_tokenized')
)
# Join tokenized text with keywords
joined_df = tokenized_text_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy(self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
# Filter to eliminate rows with empty 'Categorias Encontradas'
filtered_df = joined_df.filter(size(col('Categorias Encontradas')) > 0)
return filtered_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# DataFrames de exemplo (ensure correct schema without using 'id')
categories_df = spark.createDataFrame([
('Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
('Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
('Cartões - Bloqueio', ['bloqueio'])
], ['Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
('Estou com problemas com a anuidade do meu cartão.'),
('Preciso de um bloqueio imediato no meu cartão.'),
('Gostaria de negociar a anuidade.')
], ['tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search and filter
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
User
crie função separada
Assistant
To create a separate function for filtering out rows with empty Categorias Encontradas, we'll refactor the code by adding a specific function that handles this filtering step. This enhances modularity and makes the code cleaner and more maintainable.
Here's a revised version with a separate filtering function:
python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains, size
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Explode keywords to create a separate row for each keyword
exploded_keywords_df = self.categories_df.select(
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword'))) # Ensure keywords are lowercase
# Tokenize the text and lowercase it
tokenized_text_df = self.text_df.select(
col(self.text_col),
split(lower(col(self.text_col)), ' ').alias('text_tokenized')
)
# Join tokenized text with keywords
joined_df = tokenized_text_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy(self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
def filter_non_empty_categories(df):
# Filter to eliminate rows with empty 'Categorias Encontradas'
return df.filter(size(col('Categorias Encontradas')) > 0)
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# Example DataFrames (ensure correct schema without using 'id')
categories_df = spark.createDataFrame([
('Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
('Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
('Cartões - Bloqueio', ['bloqueio'])
], ['Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
('Estou com problemas com a anuidade do meu cartão.'),
('Preciso de um bloqueio imediato no meu cartão.'),
('Gostaria de negociar a anuidade.')
], ['tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search
result_df_with_categories = categorizer.buscar_palavras_chave()
# Apply the filter function to remove empty categories
filtered_result_df = filter_non_empty_categories(result_df_with_categories)
# Display the result
filtered_result_df.show(truncate=False)
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import ArrayType, StringType
from pyspark.sql.functions import array_contains, col
# Assuming SparkSession `spark` is already created
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col, keyword_col, text_col):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Define a UDF to trim and split the strings
def trim_and_split_keywords(keywords):
return [keyword.strip() for keyword in keywords.lower().split(',')]
trim_and_split_udf = F.udf(trim_and_split_keywords, ArrayType(StringType()))
# Preprocess the categories to maintain a mapping
keywords_df = self.categories_df.withColumn(
'trimmed_keywords', trim_and_split_udf(col(self.keyword_col))
)
# Explode the keywords to have one per row
exploded_keywords_df = keywords_df.select(
self.category_col,
F.explode('trimmed_keywords').alias('keyword')
)
# Join the keywords with the text
result_df = self.text_df.withColumn('text_tokenized', F.split(F.lower(col(self.text_col)), ' '))
joined_df = result_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy('id', self.text_col).agg(
F.collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# DataFrames de exemplo (categories_df e text_df)
categories_df = spark.createDataFrame([
(1, 'Cartões - Anuidade - Negociação', 'anuidade, negociação'),
(2, 'Cartões - Anuidade - Estorno', 'anuidade, estorno'),
(3, 'Cartões - Bloqueio', 'bloqueio')
], ['id', 'Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
(1, 'Estou com problemas com a anuidade do meu cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Gostaria de negociar a anuidade.')
], ['id', 'tx_trsc_segm'])
# Instanciar o objeto CategoriaKeyword
categorizer = CategoriaKeyword(
categories_df,
text_df,
category_col='Categoria',
keyword_col='Palavras-Chave',
text_col='tx_trsc_segm'
)
# Executar a busca de palavras-chave
result_df = categorizer.buscar_palavras_chave()
# Exibir o resultado
result_df.show(truncate=False)
Key Points:
Tokenizing and Matching: You should tokenize the text and match it against pre-defined keywords.
Joining and Grouping: Use Spark's native capabilities to join based on keyword existence and group the results.
Avoid Collecting RDD: This is crucial for maintaining performance and scalability in Spark.
This revised code structure should properly find the categories associated with the keywords found in the text. Ensure you adjust partition sizes and resources according to your actual Spark setup and data size.
tx_trsc_segm
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import ArrayType, StringType
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Preprocessing keywords: split strings into arrays and trim whitespace
keywords_df = self.categories_df.withColumn(
'trimmed_keywords', split(lower(col(self.keyword_col)), ',\\s*')
)
# Explode the keywords for joining
exploded_keywords_df = keywords_df.select(
col(self.category_col),
explode('trimmed_keywords').alias('keyword')
)
# Tokenize the text
result_df = self.text_df.withColumn('text_tokenized', split(lower(col(self.text_col)), ' '))
# Join the keywords with the text
joined_df = result_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy('id', self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# Example DataFrames for categories_df and text_df
categories_df = spark.createDataFrame([
(1, 'Cartões - Anuidade - Negociação', 'anuidade, negociação'),
(2, 'Cartões - Anuidade - Estorno', 'anuidade, estorno'),
(3, 'Cartões - Bloqueio', 'bloqueio')
], ['id', 'Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
(1, 'Estou com problemas com a anuidade do meu cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Gostaria de negociar a anuidade.')
], ['id', 'tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Run the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
Explanation:
Lowercase and Trim: Keywords are split, trimmed, and lowercased to ensure a consistent comparison.
Tokenization: The text_tokenized column splits the text into individual lowercase words.
Left Join and Grouping: The results are joined by checking if any keywords are contained within the texts and then grouped by id to collect all matching categories.
Ensure that your DataFrames have the expected schema, and columns id and tx_trsc_segm are present in your text_df and Categoria column in your categories_df. Adjust the categorie_keyword class accordingly if the schemas differ.
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import ArrayType, StringType
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Explode keywords to flatten arrays
exploded_keywords_df = self.categories_df.select(
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword')).alias('keyword')) # Convert keywords to lowercase
# Tokenize the text
result_df = self.text_df.withColumn('text_tokenized', split(lower(col(self.text_col)), ' ')) # Lowercase and split text
# Join keywords with tokenized text
joined_df = result_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy('id', self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# Example DataFrames for categories_df and text_df
categories_df = spark.createDataFrame([
(1, 'Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
(2, 'Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
(3, 'Cartões - Bloqueio', ['bloqueio'])
], ['id', 'Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
(1, 'Estou com problemas com a anuidade do meu cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Gostaria de negociar a anuidade.')
], ['id', 'tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
Key Adjustments:
Explode Arrays: Use explode() to work with individual elements from the array columns.
Lowercase Transformations: Use lower() on these exploded keyword strings and also apply it to the text column for better matching.
Matches via Join: Join on whether any tokenized words in the text are in the keywords array, using array_contains.
This approach ensures that each array element is treated individually, allowing you to perform the necessary operations such as lowercase conversion and matching correctly. Adjust based on the actual structure and types within your data.
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import ArrayType, StringType
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Explode keywords to flatten arrays and convert to lowercase
exploded_keywords_df = self.categories_df.select(
col('id').alias('category_id'), # Use distinct alias for joining clarity
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword'))) # Convert keywords to lowercase
# Tokenize the text and retain original id
result_df = self.text_df.select(
col('id'),
col(self.text_col),
split(lower(col(self.text_col)), ' ').alias('text_tokenized') # Lowercase and split text
)
# Join keywords with tokenized text, ensuring id is retained
joined_df = result_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy('id', self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# Example DataFrames for categories_df and text_df
categories_df = spark.createDataFrame([
(1, 'Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
(2, 'Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
(3, 'Cartões - Bloqueio', ['bloqueio'])
], ['id', 'Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
(1, 'Estou com problemas com a anuidade do meu cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Gostaria de negociar a anuidade.')
], ['id', 'tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
Key Points:
Alias for ID: Use a different alias for any ID columns in a join to manage potential name clashes, though in this case, id is preserved from the start.
Colum Preservation: Double-check that all required columns exist post-joins.
Debugging Column Presence: You can use printSchema() or show() methods at various steps to ensure the required columns (id) are present in the DataFrame. This helps to catch points at which columns might be dropped or transformed.
This should help retain the id column through all transformations and resolutely fix the AnalysisException you're facing.
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import ArrayType, StringType
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Explode keywords to flatten arrays and convert to lowercase
exploded_keywords_df = self.categories_df.select(
col('id').alias('category_id'), # Create an alias to avoid conflicts
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword')))
# Tokenize the text and ensure id is present
text_df_with_tokens = self.text_df.select(
col('id').alias('text_id'),
col(self.text_col),
split(lower(col(self.text_col)), ' ').alias('text_tokenized') # Lowercase and split text
)
# Debug: Check schema and data to ensure id is correctly set
text_df_with_tokens.show()
exploded_keywords_df.show()
# Join keywords with tokenized text
joined_df = text_df_with_tokens.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy('text_id', self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# Example DataFrames for categories_df and text_df
categories_df = spark.createDataFrame([
(1, 'Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
(2, 'Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
(3, 'Cartões - Bloqueio', ['bloqueio'])
], ['id', 'Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
(1, 'Estou com problemas com a anuidade do meu cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Gostaria de negociar a anuidade.')
], ['id', 'tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
Explanation:
Aliasing IDs: The id in categories_df is aliased as category_id, and id in text_df is aliased as text_id to avoid confusion.
Schema Verification: Before joining, the schema and data are displayed to confirm the presence of id/text_id. This helps in debugging where the column might be disappearing.
Preserve Columns: The critical columns throughout transformations are carefully managed to remain present.
Ensure the columns are consistently handled and verify their presence at each stage of transformation, as these are common points where column mismatches occur.
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Step 1: Explode keywords from categories_df
exploded_keywords_df = self.categories_df.select(
col('id').alias('category_id'),
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword'))) # Ensure keywords are lowercase
# Step 2: Tokenize the text and lower case
tokenized_text_df = self.text_df.select(
col('id'),
col(self.text_col),
split(lower(col(self.text_col)), ' ').alias('text_tokenized')
)
# Debugging output to check column presence
tokenized_text_df.show()
exploded_keywords_df.show()
# Step 3: Join tokenized text with keywords
joined_df = tokenized_text_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy('id', self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# Example DataFrames for categories_df and text_df
categories_df = spark.createDataFrame([
(1, 'Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
(2, 'Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
(3, 'Cartões - Bloqueio', ['bloqueio'])
], ['id', 'Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
(1, 'Estou com problemas com a anuidade do meu cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Gostaria de negociar a anuidade.')
], ['id', 'tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
Key Adjustments:
Alias Only When Necessary: Use aliasing where necessary to avoid overwriting or unnecessary conflicts.
Ensure Column Tracking: Insert printSchema() and show() statements after transformations to ensure the presence of required columns, especially before the join operation.
Column Reference Consistency: Always reference id from the input DataFrames unless split into different contexts (e.g., join keys).
These adjustments should resolve inconsistencies due to the handling of the id column. If issues persist, verify intermediate outputs to ensure column integrity.
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, explode, collect_set, split, lower, array_contains
class CategoriaKeyword:
def __init__(self, categories_df, text_df, category_col='Categoria', keyword_col='Palavras-Chave', text_col='tx_trsc_segm'):
self.categories_df = categories_df
self.text_df = text_df
self.category_col = category_col
self.keyword_col = keyword_col
self.text_col = text_col
def buscar_palavras_chave(self):
# Explode keywords to create a separate row for each keyword
exploded_keywords_df = self.categories_df.select(
col('id').alias('category_id'), # Make sure this ID exists
col(self.category_col),
explode(col(self.keyword_col)).alias('keyword')
).withColumn('keyword', lower(col('keyword'))) # Ensure keywords are lowercase
# Tokenize the text and lowercase it
tokenized_text_df = self.text_df.select(
col('id'),
col(self.text_col),
split(lower(col(self.text_col)), ' ').alias('text_tokenized')
)
# Join tokenized text with keywords
joined_df = tokenized_text_df.join(
exploded_keywords_df,
array_contains(col('text_tokenized'), col('keyword')),
how='left'
).groupBy('id', self.text_col).agg(
collect_set(self.category_col).alias('Categorias Encontradas')
)
return joined_df
# Example SparkSession
spark = SparkSession.builder.appName('CategoriaKeyword').getOrCreate()
# DataFrames de exemplo (ensure correct schema with 'id' column)
categories_df = spark.createDataFrame([
(1, 'Cartões - Anuidade - Negociação', ['anuidade', 'negociação']),
(2, 'Cartões - Anuidade - Estorno', ['anuidade', 'estorno']),
(3, 'Cartões - Bloqueio', ['bloqueio'])
], ['id', 'Categoria', 'Palavras-Chave'])
text_df = spark.createDataFrame([
(1, 'Estou com problemas com a anuidade do meu cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Gostaria de negociar a anuidade.')
], ['id', 'tx_trsc_segm'])
# Instantiate the CategoriaKeyword object
categorizer = CategoriaKeyword(categories_df, text_df)
# Execute the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
Key Points:
Correct Schema: Double-check the schema definitions when creating categories_df and text_df.
Explode Placement: Ensure column operations like explode and lower are in the right sequence to avoid inconsistencies.
Test with Smaller Steps: Utilize show() and printSchema() after key transformations to catch structural issues swiftly.
This approach should correctly aggregate categories based on keywords found. Adjust the DataFrame definitions if the actual dataset differs from assumptions.
Key Points:
No id Dependency: The approach does not require an id column, focusing solely on text content.
Maintains Keyword to Category Mapping: We still associate text with categories based directly on the presence of keywords.
Join by Content: Utilize content within the text, without needing a unique identifier, to join onto exploded keywords.
This version eliminates the issues related to non-existent or incorrectly handled id columns, and simply relates each text to its associated categories. Adjust the schema declarations if real datasets require column names to be different or additional columns are involved.
Key Points:
Filter Rows: The filter function is used to eliminate any rows where the Categorias Encontradas column has an empty list. This is done using the size function from Spark, which checks the size of the array.
Efficient Transformation: This filtering is done at the DataFrame level, leveraging Spark's distributed processing capabilities.
Ensure Column Usage: The logic for tokenization and keyword matching remains the same, ensuring that categories are correctly matched based on keywords.
With these modifications, the DataFrame will only display rows with non-empty Categorias Encontradas, effectively filtering out any text entries that do not map to any category based on the keywords.
Key Points:
Separate Function for Filtering: filter_non_empty_categories takes a DataFrame and returns a new DataFrame with only those rows that have non-empty arrays in Categorias Encontradas.
Modular Design: Separating the filtering logic into its own function makes the code easier to read and maintain. This separation also allows for potential reuse of the filtering function in other contexts if needed.
Functional Approach: Keeping the logic for category extraction and filtering separate encourages a functional approach, where data is processed in clear, distinct steps.