AVRO中的数据验证

9

我是一名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模式中指定包含正则表达式?

其他支持此类功能的数据序列化格式有哪些?

1个回答

8
你可以使用自定义逻辑类型来实现此功能。然后,您可以直接在模式中包含正则表达式。
例如,以下是如何在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

您可以在此处阅读有关实现和使用逻辑类型的更多信息。

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


这是 JavaScript 库独有的功能吗? - sksamuel
Java的实现也已经支持逻辑类型。它们在规范中是相对较新的,但希望很快会在大多数实现中出现。 - mtth
这是一个很棒的例子。Java实现现在发布了吗?如果可能的话,你能给我指一下Javadocs吗?谢谢您的帮助。 - user2166328
当然,@user2166328;我编辑了我的答案并添加了一些链接。Java实现已经发布(1.8.0+)。 - mtth
谢谢提供的链接,解答了我的问题。 :) - user2166328
1
请问您能否提供使用正则表达式和自定义逻辑类型进行验证的Java实现方法,因为我没有找到任何相关资源或信息。 - Santhosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接