簡體   English   中英

在卡夫卡流中左連接中僅在右流中獲取Null值

[英]Getting only Null values in the right stream for left join in kafka streams

我正在嘗試加入來自兩個kafka主題的兩個數據流。

每個主題都有一個鍵值對,其中key是Integer數據類型,值包含字符串格式的json 來自這兩個來源的數據看起來像下面的以下示例(鍵,值):

2232, {"uniqueID":"2164103","ConsumerID":"63357","CategoryID":"8","BrandID":"5","ProductID":"2232","ProductDetails":"[]","Date":"2013-03-28","Flag":"0"}

1795, {"ProductName":"Frost Free","ProductID":"1795","BrandID":"16","BrandName":"ABC","CategoryID":"3"}

現在,我嘗試根據ProductID 離開這兩個流,因此對於所有這些記錄,鍵均設置為ProductID。 但是不幸的是,我在正確的連接流值中不斷得到空值。 甚至沒有一條記錄可以正確加入。 以下是我將兩個記錄連接在一起的代碼:

import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.streams.kstream.*;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.concurrent.TimeUnit;
import java.util.*;

public class Tester {
    public static void main(String[] args){
        final Properties streamsConfiguration = new Properties();

        final Serde<String> stringSerde = Serdes.String();
        final Serde<Integer> intSerde = Serdes.Integer();

        streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "join-streams");
        streamsConfiguration.put(StreamsConfig.CLIENT_ID_CONFIG, "joining-Client");
        streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");

        streamsConfiguration.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, intSerde.getClass().getName());
        streamsConfiguration.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, stringSerde.getClass().getName());

        streamsConfiguration.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 100);
        streamsConfiguration.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
        streamsConfiguration.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 9000);

        final KStreamBuilder builder = new KStreamBuilder();
        KStream<Integer,String> pData = builder.stream(intSerde,stringSerde,"Ptopic");
        KStream<Integer,String> streamData = builder.stream(intSerde,stringSerde,"Dtopic");
// Test the data type and value of the key
        pbData.selectKey((k,v)->{System.out.println("Table : P, Type : "+k.getClass()+" Value : "+k);return k;});
        streamData.selectKey((k,v)->{System.out.println("Table : StreamRecord, Type : "+k.getClass()+" Value : "+k);return k;});

        KStream<Integer,String> joined = streamData.leftJoin(pbData,(table1Value,table2Value)->returnJoin(table1Value,table2Value),JoinWindows.of(TimeUnit.SECONDS.toMillis(30)));

        final KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration);
        streams.cleanUp();
        streams.start();

        // Add shutdown hook to respond to SIGTERM and gracefully close Kafka Streams
        Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
    }
    private static HashMap convertToHashMap(String jsonString, String tablename){
        try{
            HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());
            return map;
        }
        catch(Exception x){
            //couldn't properly parse json
            HashMap<String,String> record = new HashMap<>();
            if (tablename.equals("PB")){
                List<String> keys = new ArrayList<>(Arrays.asList("ProductName", ", "CategoryID", "ProductID", "BrandID", "BrandName", "ProductCategoryID"));
                for(String key : keys){
                    record.put(key,null);
                }
            }
            else{
                List<String> keys = new ArrayList<>(Arrays.asList("UniqueID", "ConsumerID", "CategoryID", "BrandID", "ProductID", "Date","Flag","ProductDetails"));
                for(String key : keys){
                    record.put(key,null);
                }
            }
            return record;
        }
    }
    private static String returnJoin(String map1, String map2){
        HashMap h1 = convertToHashMap(map1,"consumer_product");
        HashMap h2 = convertToHashMap(map2,"PB");
        HashMap map3 = new HashMap<>();

        System.out.println("First : " + map1);
        System.out.println("Second : " + map2);
        //else{System.out.println("Null only");}
        for (Object key : h1.keySet()) {
            key = key.toString();
            if (map3.containsKey(key)) {
                continue;
            }
            map3.put(key, h1.get(key));
        }
        try {
            for (Object key : h2.keySet()) {
                key = key.toString();
                if (map3.containsKey(key)) {
                    continue;
                }
                map3.put(key, h2.get(key));
            }
            System.out.println("Worked Okay PB!!!\n--------------------------------------------------------------------------------------");
        }
        catch (NullPointerException ex){
            /*System.out.println("Exception\n----------------------------------------------------------------------------");
            HashMap fakeC = getHashMap("{","consumer");
            for (Object key : fakeC.keySet()) {
                key = key.toString();
                if (map3.containsKey(key)) {
                    continue;
                }
                map3.put(key, fakeC.get(key));
            }*/
            return "INVALID";
        }
        //return map3;
        return serializeObjectJSON(map3);
    }
    private static String serializeObjectJSON(Map row){
        StringBuilder jsonString = new StringBuilder();
        jsonString.append("{");
        for ( Object key : row.keySet()){
            jsonString.append("\""+key.toString()+"\":");
            try {
                jsonString.append("\"" + row.get(key).toString() + "\",");
            }
            catch (NullPointerException Nexp){
                jsonString.append("\"" + "null" + "\",");
            }

        }
        jsonString.deleteCharAt(jsonString.length()-1);
        jsonString.append("}");
        String jsString = jsonString.toString();
        ////System.out.println("JString :"+jsString);
        return jsString;
    }
}

當我嘗試以任何一種方式同時連接兩個流時,我無法弄清楚為什么我只在左連接的右流中得到null,但是當我嘗試將同一流與自身連接時,該連接有效。

我確保兩個流中的所有記錄的鍵類型均為Integer,並且在我檢查兩個流的類型和鍵值時不存在空值(可以在上面的代碼中檢查)。 而且兩個流都具有重疊的鍵才能進行連接,因為我認為兩個鍵都不重疊或數據類型可能不同,因為那是在連接中獲得空值的時候。

誰能幫我弄清楚我在做什么錯?

更新

這兩個主題(我要加入的主題)中的數據來自兩個流。 其中一個流是類型為(Integer,recordHashmap)的自定義(Key,value)對的流,而另一個只是(Integer,string)的流。 在這里recordHashmap是我定義的自定義對象,用於將嵌套的json字符串解析為一個對象。 其定義如下:

public class recordHashmap {
    private String database;
    private String table;
    private String type;
    private Integer ts;
    private Integer xid;
    private Map<String,String> data;

    public Map getdata(){
        return data;
    }
    public String getdatabase(){return database;}
    public String gettable(){return table;}
    public String gettype(){return type;}
    public Integer getts(){return ts;}
    public Integer getxid(){return xid;}

    public void setdata(Map<String, String> dta){
        data=dta;
    }
    public void setdatabase(String db){ database=db; }
    public void settable(String tble){ table=tble; }
    public void settype(String optype){type=optype;}
    public void setts(Integer unixTime){ts = unixTime;}
    public void setxid(Integer Xid){xid = Xid;}

    public String toString() {
        return "Database=" + this.database + ", Table=" + this.table+", OperationType="+this.type+", UnixOpTime"+this.ts + ", Data="
                + this.data;
    }

}

並將代碼設置為產品ID的代碼如下所示:

KStream<Integer,recordHashmap> rekeyedProductID = inserts.selectKey((k,v)->setTheKey(v.getdata(),"ProductID"));
KStream<Integer,String> consumer_product_Stream = rekeyedProductID.mapValues((v)->serializeObjectJSON(v.getdata()));

函數setTheKey定義為

private static Integer setTheKey(Map map, String Key){
        try {
            //System.out.println("New Key : " + map.get(Key));
            return Integer.parseInt(map.get(Key).toString());
        }
        catch (NumberFormatException nmb){
            //fake return a custom value
            return -1;
        }
    }

下面顯示了以下兩個語句的控制台日志示例 (注意:總體日志太大,無法添加,但主要是兩個流鍵都是整數,並且鍵重疊):

pbData.selectKey((k,v)->{System.out.println("Table : P, Type : "+k.getClass()+" Value : "+k);return k;});
streamData.selectKey((k,v)->{System.out.println("Table : StreamRecord, Type : "+k.getClass()+" Value : "+k);return k;});

控制台日志:

Table : streamRecord, Type:class java.lang.Integer Value:1342
Table : streamRecord, Type:class java.lang.Integer Value:595
Table : streamRecord, Type:class java.lang.Integer Value:1934
Table : streamRecord, Type:class java.lang.Integer Value:2384
Table : streamRecord, Type:class java.lang.Integer Value:1666
Table : streamRecord, Type:class java.lang.Integer Value:665
Table : streamRecord, Type:class java.lang.Integer Value:2671
Table : streamRecord, Type:class java.lang.Integer Value:949
Table : streamRecord, Type:class java.lang.Integer Value:2455
Table : streamRecord, Type:class java.lang.Integer Value:928
Table : streamRecord, Type:class java.lang.Integer Value:1602
Table : streamRecord, Type:class java.lang.Integer Value:74
Table : P, Type:class java.lang.Integer Value:2
Table : streamRecord, Type:class java.lang.Integer Value:1795
Table : P, Type:class java.lang.Integer Value:21
Table : streamRecord, Type:class java.lang.Integer Value:1265
Table : P, Type:class java.lang.Integer Value:22
Table : streamRecord, Type:class java.lang.Integer Value:2420
Table : P, Type:class java.lang.Integer Value:23
Table : streamRecord, Type:class java.lang.Integer Value:1419
Table : P, Type:class java.lang.Integer Value:24
Table : streamRecord, Type:class java.lang.Integer Value:1395
Table : P, Type:class java.lang.Integer Value:26
Table : streamRecord, Type:class java.lang.Integer Value:1783
Table : P, Type:class java.lang.Integer Value:29
Table : streamRecord, Type:class java.lang.Integer Value:1177
Table : P, Type:class java.lang.Integer Value:34
Table : streamRecord, Type:class java.lang.Integer Value:1395
Table : P, Type:class java.lang.Integer Value:35
Table : streamRecord, Type:class java.lang.Integer Value:2551
Table : P, Type:class java.lang.Integer Value:36
Table : P, Type:class java.lang.Integer Value:2551
Table : streamRecord, Type:class java.lang.Integer Value:2530
Table : P, Type:class java.lang.Integer Value:37
Table : streamRecord, Type:class java.lang.Integer Value:541
Table : P, Type:class java.lang.Integer Value:39
Table : streamRecord, Type:class java.lang.Integer Value:787
Table : P, Type:class java.lang.Integer Value:40
Table : streamRecord, Type:class java.lang.Integer Value:2498
Table : P, Type:class java.lang.Integer Value:41
Table : streamRecord, Type:class java.lang.Integer Value:1439
Table : P, Type:class java.lang.Integer Value:44
Table : streamRecord, Type:class java.lang.Integer Value:784
Table : P, Type:class java.lang.Integer Value:284
Table : P, Type:class java.lang.Integer Value:285
Table : P, Type:class java.lang.Integer Value:929
Table : P, Type:class java.lang.Integer Value:286
Table : P, Type:class java.lang.Integer Value:287
Table : P, Type:class java.lang.Integer Value:2225
Table : P, Type:class java.lang.Integer Value:288
Table : P, Type:class java.lang.Integer Value:289
Table : P, Type:class java.lang.Integer Value:290
Table : P, Type:class java.lang.Integer Value:295
Table : P, Type:class java.lang.Integer Value:297
Table : P, Type:class java.lang.Integer Value:300
Table : P, Type:class java.lang.Integer Value:302
Table : P, Type:class java.lang.Integer Value:305
Table : P, Type:class java.lang.Integer Value:306
Table : P, Type:class java.lang.Integer Value:307
Table : P, Type:class java.lang.Integer Value:308
Table : P, Type:class java.lang.Integer Value:309
Table : P, Type:class java.lang.Integer Value:310
Table : streamRecord, Type:class java.lang.Integer Value:929
Table : streamRecord, Type:class java.lang.Integer Value:1509
Table : streamRecord, Type:class java.lang.Integer Value:136
Table : streamRecord, Type:class java.lang.Integer Value:2225
Table : streamRecord, Type:class java.lang.Integer Value:906
Table : streamRecord, Type:class java.lang.Integer Value:1013
Table : streamRecord, Type:class java.lang.Integer Value:1759
Table : streamRecord, Type:class java.lang.Integer Value:1759
Table : streamRecord, Type:class java.lang.Integer Value:885
Table : streamRecord, Type:class java.lang.Integer Value:1165
Table : streamRecord, Type:class java.lang.Integer Value:453

Update-2 :有趣的是,對於相同的鍵/值對集合, leftJoin對於KTables正常工作。 但是由於某種原因,不是針對KStreams 但是我需要使用KStreams,因為我有很多與鍵有關的記錄。 通常,大多數情況下,在流上進行這種連接就像是一種魅力,但是在這種特殊情況下,它的行為很奇怪。 我猜想這可能與RocksDB或內部緩存有關。

似乎您沒有將ProductID設置為鍵:

pbData.selectKey((k,v)->{System.out.println("Table : P, Type : "+k.getClass()+" Value : "+k);return k;});
streamData.selectKey((k,v)->{System.out.println("Table : StreamRecord, Type : "+k.getClass()+" Value : "+k);return k;});

在這兩個語句中,您都返回原始鍵-> return k ; 而是從JSON解析productId並將其返回。

更新資料

我仍然不確定是否可以將所有部分正確地組合在一起,因為在您的更新中,您使用

KStream<Integer,recordHashmap> rekeyedProductID = inserts.selectKey((k,v)->setTheKey(v.getdata(),"ProductID"));
KStream<Integer,String> consumer_product_Stream = 

rekeyedProductID.mapValues((v)-> serializeObjectJSON(v.getdata()));

還不清楚什么是insertsrekeyedProductID (類型是什么?)。 無論如何,我認為這部分是正確的。 正如您提到的那樣,如果右側是KTable(使用相同的數據),則可以正常工作,我只是假設您加入的窗口不夠大,以至於兩個具有相同鍵的記錄離(距離)更遠彼此之間比您指定的30秒要長。 您可以仔細檢查兩個輸入流的記錄時間戳嗎? (請參閱https://docs.confluent.io/current/streams/faq.html#accessing-record-metadata-such-as-topic-partition-and-offset-information

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM