AVRO 中的数据验证

2023-11-22

我是 AVRO 新手,如果这是一个简单的问题,请原谅。 我有一个使用 AVRO 模式进行记录调用的用例。

假设我有 avro 架构

{
    "name": "abc",
    "namepsace": "xyz",
    "type": "record",
    "fields": [
        {"name": "CustId", "type":"string"},
        {"name": "SessionId", "type":"string"},
     ]
}

现在如果输入是这样的

{
    "CustId" : "abc1234"
    "sessionID" : "000-0000-00000"
}

我想对这些字段使用一些正则表达式验证,并且仅当输入采用如上所示的特定格式时,我才想采用该输入。有没有办法在 avro 模式中指定包含正则表达式?

还有其他支持类似功能的数据序列化格式吗?


您应该能够使用自定义逻辑类型为了这。然后,您可以将正则表达式直接包含在架构中。

例如,以下是在 JavaScript 中实现的方法:

var avro = require('avsc'),
    util = require('util');

/**
 * Sample logical type that validates strings using a regular expression.
 *
 */
function ValidatedString(attrs, opts) {
  avro.types.LogicalType.call(this, attrs, opts);
  this._pattern = new RegExp(attrs.pattern);
}
util.inherits(ValidatedString, avro.types.LogicalType);

ValidatedString.prototype._fromValue = function (val) {
  if (!this._pattern.test(val)) {
    throw new Error('invalid string: ' + val);
  }
  return val;
};

ValidatedString.prototype._toValue = ValidatedString.prototype._fromValue;

以及如何使用它:

var type = avro.parse({
  name: 'Example',
  type: 'record',
  fields: [
    {
      name: 'custId',
      type: 'string' // Normal (free-form) string.
    },
    {
      name: 'sessionId',
      type: {
        type: 'string',
        logicalType: 'validated-string',
        pattern: '^\\d{3}-\\d{4}-\\d{5}$' // Validation pattern.
      }
    },
  ]
}, {logicalTypes: {'validated-string': ValidatedString}});

type.isValid({custId: 'abc', sessionId: '123-1234-12345'}); // true
type.isValid({custId: 'abc', sessionId: 'foobar'}); // false

您可以阅读有关实现和使用逻辑类型的更多信息here.

编辑:对于 Java 实现,我相信您会想要查看以下类:

  • LogicalType,您需要扩展的基础。
  • Conversion,执行数据的转换(或在您的情况下进行验证)。
  • LogicalTypes and Conversions,现有实现的一些示例。
  • TestGenericLogicalTypes,相关测试可以提供一个有用的起点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AVRO 中的数据验证 的相关文章

随机推荐