4

我正在使用 Kafka-Connect 来实现 Kafka-Elasticsearch 连接器。

生产者向 Kafka 主题发送了一个复杂的 JSON,我的连接器代码将使用它来持久化到 Elastic 搜索。连接器以 Struct 的形式获取数据(https://kafka.apache.org/0100/javadoc/org/apache/kafka/connect/data/Struct.html)。

我能够在顶级 Json 中获取 struct 的字段值,但无法从嵌套的 json 中获取。

   {
    "after": {
        "test.test.employee.Value": {
            "id": 5671111,
            "name": {
                "string": "abc"
            }
        }
    },
    "op": "u",
    "ts_ms": {
        "long": 1474892835943
    }
}

我能够解析“op”,但不能解析“test.test.employee.Value”。

Struct afterStruct = struct.getStruct("after"); // giving me proper value.
String opValue = struct.getString("op"); // giving me proper value of "u". 

Struct valueStruct = afterStruct .getStruct("test.test.employee.Value"); // org.apache.kafka.connect.errors.DataException: test.test.employee.Value is not a valid field name
4

1 回答 1

2

Struct.getStruct本身不支持使用点表示法进行嵌套。

看来您的架构可能来自 Debezium,在这种情况下,他们有自己的“解包”消息转换器。

一种选择是,如果您可以控制此提取器代码,您可能会发现我为 Confluent Kafka Connect Storage 项目编写的代码很有用。它需要一个 Struct 或一个 Map 对象(见下文)

否则,您可能想尝试将Landoop 的 KCQL 插件添加到您的 Connect 类路径中。

  public static Object getNestedFieldValue(Object structOrMap, String fieldName) {
    // validate(structOrMap, fieldName); // can ignore this

    try {
      Object innermost = structOrMap;
      // Iterate down to final struct
      for (String name : fieldName.split("\\.")) {
        innermost = getField(innermost, name);
      }
      return innermost;
    } catch (DataException e) {
      throw new DataException(
            String.format("The field '%s' does not exist in %s.", fieldName, structOrMap),
            e
      );
    }
  }

  public static Object getField(Object structOrMap, String fieldName) {
    // validate(structOrMap, fieldName);

    Object field;
    if (structOrMap instanceof Struct) {
      field = ((Struct) structOrMap).get(fieldName);
    } else if (structOrMap instanceof Map) {
      field = ((Map<?, ?>) structOrMap).get(fieldName);
      if (field == null) {
        throw new DataException(String.format("Unable to find nested field '%s'", fieldName));
      }
      return field;
    } else {
      throw new DataException(String.format(
            "Argument not a Struct or Map. Cannot get field '%s' from %s.",
            fieldName,
            structOrMap
      ));
    }
    if (field == null) {
      throw new DataException(
            String.format("The field '%s' does not exist in %s.", fieldName, structOrMap));
    }
    return field;
  }
于 2018-12-11T04:31:36.450 回答