def buscar_palavras_chave(self):
# Processamento de pré-palavras-chave em um dicionário para busca mais rápida
keyword_to_category = {}
# Explodir as palavras-chave da coluna de palavras-chave fornecida
categories_df_exploded = self.categories_df.withColumn('Palavras-Chave', explode(split(col(self.keyword_col), ', '))) \
.select('Palavras-Chave', col(self.category_col).alias('Categoria'))
# Montar o dicionário de palavras-chave para categorias
for row in categories_df_exploded.collect():
keyword = row['Palavras-Chave'].strip()
categoria = row['Categoria']
if keyword in keyword_to_category:
keyword_to_category[keyword].append(categoria)
else:
keyword_to_category[keyword] = [categoria]
# Procura por palavras-chave no DataFrame de texto e atribui a categoria mais provável
resultados = []
for row in self.text_df.collect():
texto = row[self.text_col].lower()
word_count = collections.Counter(texto.split())
category_scores = {}
# Verificar a contagem de palavras-chave no texto
for keyword in keyword_to_category.keys():
keyword_count = word_count.get(keyword, 0)
if keyword_count > 0:
for categoria in keyword_to_category[keyword]:
if categoria in category_scores:
category_scores[categoria] += keyword_count
else:
category_scores[categoria] = keyword_count
# Determinar a categoria mais provável
categoria_mais_provavel = None
max_score = 0
for categoria, score in category_scores.items():
if score > max_score:
max_score = score
categoria_mais_provavel = categoria
# Obter palavras-chave localizadas
palavras_localizadas = [keyword for keyword in keyword_to_category.keys() if keyword in texto]
resultados.append({
self.text_col: row[self.text_col],
'Categoria Encontrada': categoria_mais_provavel,
'Palavras Localizadas': list(set(palavras_localizadas)),
'Contador Palavras Localizadas': len(set(palavras_localizadas))
})
# Criar DataFrame final com os resultados
return spark.createDataFrame(resultados)
(1, 'Estou com problemas com a fatura e a segunda via do cartão.'),
(2, 'Preciso de um bloqueio imediato no meu cartão.'),
(3, 'Qual o procedimento para contestar uma cobrança?')
], ['id', 'tx_trsc_segm'])
Criar o objeto CategoriaKeyword com nomes das colunas
categorizer = CategoriaKeyword(
df_spark,
df_filtrada,
category_col='Categoria', # Nome da coluna de categoria
keyword_col='Palavras-Chave', # Nome da coluna de palavras-chave
text_col='tx_trsc_segm' # Nome da coluna de texto
)
Executar a busca de palavras-chave
result_df = categorizer.buscar_palavras_chave()
Exibir o resultado
result_df.show(truncate=False)
Executar a busca de palavras-chave
result_df = categorizer.buscar_palavras_chave()
Exibir o resultado
result_df.show(truncate=False)351 args_command +
1352 proto.END_COMMAND_PART
1354 answer = self.gateway_client.send_command(command)
-> 1355 return_value = get_return_value(
1356 answer, self.gateway_client, self.target_id, self.name)
1358 for temp_arg in temp_args:
1359 if hasattr(temp_arg, "_detach"):
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: [DATATYPE_MISMATCH.UNEXPECTED_INPUT_TYPE] Cannot resolve "split(Palavras-Chave, , , -1)" due to data type mismatch: Parameter 1 requires the "STRING" type, however "Palavras-Chave" has the type "ARRAY".;
'Project [Categoria#79554, explode(split(Palavras-Chave#79555, , , -1)) AS Palavras-Chave#89746]
+- LogicalRDD [Categoria#79554, Palavras-Chave#79555], false
The error you're encountering is due to the data type mismatch in the split function used in your code. Specifically, the split function expects the first argument to be a string (STRING type), but in your case, it's receiving an array of strings (ARRAY<STRING> type). This happens because the column 'Palavras-Chave' in your categories_df DataFrame is already of type ARRAY<STRING>, not STRING.
In this line, you're trying to apply split on 'Palavras-Chave' which is an array. Applying split on an array doesn't make sense because split is designed to split a string into an array, not split an array.
Solution
Since your 'Palavras-Chave' column is already an array of strings, you don't need to split it. You can directly explode the array to get individual keywords. Here's how you can modify your code:
By removing the split function and directly applying explode to the array column, you eliminate the data type mismatch, and the code should work as expected.
Updated Code
Below is the updated buscar_palavras_chave method with the necessary correction:
python
def buscar_palavras_chave(self):
# Processamento de pré-palavras-chave em um dicionário para busca mais rápida
keyword_to_category = {}
# Explodir as palavras-chave da coluna de palavras-chave fornecida
categories_df_exploded = self.categories_df.withColumn('Palavras-Chave', explode(col(self.keyword_col))) \
.select('Palavras-Chave', col(self.category_col).alias('Categoria'))
# Montar o dicionário de palavras-chave para categorias
for row in categories_df_exploded.collect():
keyword = row['Palavras-Chave'].strip()
categoria = row['Categoria']
if keyword in keyword_to_category:
keyword_to_category[keyword].append(categoria)
else:
keyword_to_category[keyword] = [categoria]
# Procura por palavras-chave no DataFrame de texto e atribui a categoria mais provável
resultados = []
for row in self.text_df.collect():
texto = row[self.text_col].lower()
word_count = collections.Counter(texto.split())
category_scores = {}
# Verificar a contagem de palavras-chave no texto
for keyword in keyword_to_category.keys():
keyword_count = word_count.get(keyword.lower(), 0)
if keyword_count > 0:
for categoria in keyword_to_category[keyword]:
if categoria in category_scores:
category_scores[categoria] += keyword_count
else:
category_scores[categoria] = keyword_count
# Determinar a categoria mais provável
categoria_mais_provavel = None
max_score = 0
for categoria, score in category_scores.items():
if score > max_score:
max_score = score
categoria_mais_provavel = categoria
# Obter palavras-chave localizadas
palavras_localizadas = [keyword for keyword in keyword_to_category.keys() if keyword.lower() in texto]
resultados.append({
self.text_col: row[self.text_col],
'Categoria Encontrada': categoria_mais_provavel,
'Palavras Localizadas': list(set(palavras_localizadas)),
'Contador Palavras Localizadas': len(set(palavras_localizadas))
})
# Criar DataFrame final com os resultados
return spark.createDataFrame(resultados)
Explanation
Removed split Function: Since the 'Palavras-Chave' column is already an array, we removed the split function. We no longer need to split a string into an array; instead, we can directly use explode on the array.
Adjusted Keyword Matching: In the loop where you're matching keywords, I've added .lower() to keyword to ensure case-insensitive matching, which aligns with how you processed the texto variable.
Used .lower() in Keyword Count: When getting the keyword_count, it's important to ensure that both the text and the keywords are in the same case to accurately find matches.
Removed Unnecessary Strip: Since the keywords are likely already trimmed, you might not need to call strip(). However, if there's a possibility of leading or trailing spaces in your data, keeping strip() is appropriate.
Additional Recommendations
Broadcast Variables: If your keyword_to_category dictionary is large, consider broadcasting it to improve performance.
Optimize DataFrame Operations: Collecting data to the driver using .collect() can be inefficient for large datasets. You might want to refactor your code to use DataFrame operations rather than Python loops.
Case Sensitivity: Ensure consistency in case sensitivity when comparing keywords and text. Converting both to lowercase (as done in the updated code) helps in matching.
Testing: Test the updated code with a small subset of your data to ensure it behaves as expected before running it on the full dataset.
Example Usage
Assuming you have your DataFrames categories_df and text_df properly initialized, you can use the CategoriaKeyword class as follows:
python
# Create an instance of the CategoriaKeyword class
categorizer = CategoriaKeyword(
categories_df,
text_df,
category_col='Categoria', # Name of the category column
keyword_col='Palavras-Chave', # Name of the keyword column (should be an array column)
text_col='tx_trsc_segm' # Name of the text column
)
# Execute the keyword search
result_df = categorizer.buscar_palavras_chave()
# Display the result
result_df.show(truncate=False)
Conclusion
By adjusting your code to account for the data type of the 'Palavras-Chave' column, you should be able to resolve the AnalysisException and have your code run successfully.