Hi <#C065944F9M2|pyflink> I have been working wit...
# pyflink
n
Hi #pyflink I have been working with the pyflink datastream API to process and sink data to Kafka. Is there any way by which we can sink the data to kafka partitions based on KEY. I am using flink 1.18.
d
@Noufal Rijal It uses FlinkFixedPartitioner by default which maps each sink subtask to a single Kafka partition (i.e. all records received by a sink subtask will end up in the same Kafka partition). So I guess you could make a
key_by
before writing data to sink.
n
Hi @Dian Fu, I am using the following config for my kafka sync -
Copy code
sink = (
        sink_builder.set_record_serializer(
            KafkaRecordSerializationSchema.builder()
            .set_topic(topic_name)
            .set_key_serialization_schema(SimpleStringSchema())
            # .set_key_serialization_schema(lambda row: row[0].encode('utf-8'))
            .set_value_serialization_schema(SimpleStringSchema())
            .build()
        )
        .set_delivery_guarantee(DeliveryGuarantee.AT_LEAST_ONCE)
        .build()
    )
and below is the code that i am using to construct my final message which is to be synced to kafka -
Copy code
def setup_sink_pipeline(processed_stream):
    """
    Set up the Kafka sink part of the pipeline.

    Args:
        processed_stream: Processed tracking results stream

    Returns:
        DataStream: Output stream connected to sink
    """
    # Map the processed results to JSON strings
    def serialize_final_message(x):
        # Extract video_id for partitioning key

        id = str(x[0]) if x[9] == "-source" else str(x[1])

        
        json_message = json.dumps(
            {
                # values
            }
        )

        logger.info(f"type of json_message -- {type(json_message)}")

        # return json_message
        return (id, json_message)


    # Map processed data to key-value tuples
    kafka_output_stream = processed_stream.map(
        serialize_final_message,
        output_type=Types.TUPLE([Types.STRING(), Types.STRING()]),
    )

    # Add this map to force element type (Python native tuple[str, str])

    logger.info("Sink pipeline maintains partition consistency (no re-keying)")
    return kafka_output_stream
below is the code that consumes the messages and performs the keying process -
Copy code
output_stream = setup_sink_pipeline(detection_stream)
keyed_output_stream = output_stream.key_by(lambda x: str(x[0]), key_type=Types.STRING())
keyed_output_stream.sink_to(kafka_sink)
While doing so i am getting an error stating that java.lang.ClassCastException: class org.apache.flink.types.Row cannot be cast to class java.lang.String. Can you please help me, if there is any issues with the way i am trying to implement the solution.
d
What about changed it as following:
Copy code
output_stream = setup_sink_pipeline(detection_stream)
keyed_output_stream = output_stream.key_by(lambda x: str(x[0]), key_type=Types.STRING())
keyed_output_stream = keyed_output_stream.map(lambda x: x[1], output_type=Types.STRING())
keyed_output_stream.sink_to(kafka_sink)
and changed the sink as following:
Copy code
sink = (
        sink_builder.set_record_serializer(
            KafkaRecordSerializationSchema.builder()
            .set_topic(topic_name)
            # .set_key_serialization_schema(SimpleStringSchema())
            # .set_key_serialization_schema(lambda row: row[0].encode('utf-8'))
            .set_value_serialization_schema(SimpleStringSchema())
            .build()
        )
        .set_delivery_guarantee(DeliveryGuarantee.AT_LEAST_ONCE)
        .build()
    )
r
kafka_sink doesn't accept keyed_output_stream.
It uses the the same value for key and value serialization.
The only solution I found was to implement the serialization schema in Java and do some py4j magic to plug that in.
n
@Ridvan Duran @Dian Fu We had to create a custom java class that could perform the same. It's working fine for us now . The path to figure out the solution was very tiring 😔
d
@Noufal Rijal Nice to hear and sorry for inconvenience‌. It makes sense to improve this. Have created a ticket to improve this: https://issues.apache.org/jira/browse/FLINK-38189
n
@Dian Fu thank you for the support 😊, Is there a way by which I can contribute the same
d
@Noufal Rijal Sure. Of course. Do you want to contribute to this feature or would like to other features also?
n
@Dian Fu I am not sure the java code that i have created is very generic (i am not proficient in java 😕 )
d
@Noufal Rijal Could you submit a PR for this ticket: https://issues.apache.org/jira/browse/FLINK-38189? I can help to review.
n
@Dian Fu sure, i have raised a request for creating a Jira account, waiting for that to get approved
hi @Dian Fu, I have made the PR for the above-mentioned ticket - can you please review and share your thoughts. [FLINK-38189][core][python] Add RowFieldExtractorSchema for Row field serialization