Как убрать повторяющиеся записи и отклонить неверные?
В списке регистраций один и тот же человек встречается дважды с разным регистром букв, есть несуществующий тариф и запись без обязательного поля. Нужна одна запись на адрес, а неверные — в отдельном файле с причиной, а не бесследно исчезнувшие.
Обе задачи — стандартные пайпы. Ваше решение здесь только одно: какой ключ и какая схема.
Пайп — шаг обработки данных с объявленными входами и выходами; пайплайн соединяет пайпы.
Что понадобится
- Команда
openflange, релиз v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 - Пустой каталог. Создайте в нём файлы, приведённые ниже, точно под этими именами и выполняйте все команды из этого каталога.
- Больше ничего: все шаги рецепта выполняются в процессе раннера (программы, которая запускает пайпы). Ни сети, ни учётной записи, ни ключа.
Шаги
1. Сохраните входной файл
Семь регистраций. Записи 1 и 3 — один адрес в разном регистре, запись 5 в точности повторяет запись 2, в записи 4 неизвестный тариф и ноль мест, в записи 6 нет seats.
{"email":"Ada@Example.com","plan":"pro","seats":5}
{"email":"bob@example.org","plan":"free","seats":1}
{"email":"ada@example.com","plan":"free","seats":1}
{"email":"carol@example.net","plan":"enterprise","seats":0}
{"email":"bob@example.org","plan":"free","seats":1}
{"email":"dave@example.com","plan":"team"}
{"email":"erin@example.com","plan":"team","seats":12}2. Опишите пайплайн и его контракт
normalise делает ключ сравнимым, dedupe оставляет первую запись для каждого адреса, check разводит записи по схеме. Верхняя граница числа запоминаемых ключей вынесена в параметр maxKeys.
# records ─▶ normalise ─▶ dedupe ─▶ check ─┬─▶ valid
# └─▶ rejected
spec: openflange.org/pipeline/v0.1
nodes:
normalise:
pipe: std:map # the key must be comparable: lower-case the e-mail first
inputs:
in: {from: inputs.records}
parameters:
expr: 'dict(item, email=item["email"].strip().lower())'
dedupe:
pipe: std:distinct # the first record for every e-mail wins
inputs:
in: {from: normalise.outputs.out}
parameters:
fields: [email]
maxKeys: {$param: maxKeys}
check:
pipe: std:validate-schema # invalid records go to `rejected`, with the reasons
inputs:
in: {from: dedupe.outputs.out}
parameters:
schema:
type: object
required: [email, plan, seats]
properties:
email: {type: string, pattern: "^[^@ ]+@[^@ ]+$"}
plan: {enum: [free, team, pro]}
seats: {type: integer, minimum: 1}
outputs:
valid: {from: check.outputs.valid}
rejected: {from: check.outputs.rejected}---
spec: openflange.org/pipe/v0.1
id: deduplicate-validate
version: 0.1.0
title: Deduplicate and validate records
description: Keeps the first record for every e-mail address, then routes each record by validity against a JSON Schema.
license: Apache-2.0
keywords: [deduplicate, distinct, validate, json-schema, recipe]
maturity: experimental
scope: record
inputs:
records:
description: 'Sign-up records: {"email", "plan", "seats"}; `email` must be a string.'
outputs:
valid:
description: The first record for every e-mail address that matches the schema, in input order, with the e-mail lower-cased.
rejected:
required: false
description: 'Records that do not match the schema, as {"item", "errors"}. If not connected, the first invalid record fails the run.'
parameters:
maxKeys:
type: integer
default: 1000000
minimum: 1
description: Upper bound on the number of distinct e-mail addresses remembered; one more fails the run with E_RESOURCE.
implementation:
type: pipeline
path: pipeline.yaml
---
# Deduplicate and validate records
Implements the [OpenFlange](https://openflange.org/) specification.
Normalise the key, keep the first record per key, validate what is left.
Every node is a standard pipe and runs in-process; no permissions are needed.
Memory grows with the number of distinct keys, up to `maxKeys`.3. Проверьте и запустите
Вход берётся из файла, два выхода идут в два файла.
openflange validate .valid: . (3 nodes, 5 edges)openflange run . --input records=signups.ndjson --output valid=clean.ndjson --output rejected=rejected.ndjsoncompleted in 481µs — valid: 3 records, rejected: 2 records{"email":"ada@example.com","plan":"pro","seats":5}
{"email":"bob@example.org","plan":"free","seats":1}
{"email":"erin@example.com","plan":"team","seats":12}{"item":{"email":"carol@example.net","plan":"enterprise","seats":0},"errors":[{"path":"/plan","message":"value must be one of 'free', 'team', 'pro'"},{"path":"/seats","message":"minimum: got 0, want 1"}]}
{"item":{"email":"dave@example.com","plan":"team"},"errors":[{"path":"","message":"missing property 'seats'"}]}Три записи верны и уникальны. Две отклонены с причиной. Два дубликата поглотил std:distinct: удалять их — назначение этого пайпа.
4. Посмотрите на границу памяти
Единственное состояние — уже встреченные ключи. При maxKeys=3 четвёртый новый адрес останавливает запуск: ключи никогда не забываются, чтобы освободить место.
openflange run . --param maxKeys=3 --input records=signups.ndjson --output valid=/dev/null --output rejected=/dev/nullE_RESOURCE: std:distinct saw more than maxKeys=3 distinct keys (node dedupe)
hint: raise `maxKeys`, or reduce cardinality upstream; state must stay bounded
failed in 225µs — valid: 0 records, rejected: 0 records5. Протестируйте
Тесты покрывают дубликат в другом регистре, неверные записи, границу и пустой вход.
spec: openflange.org/test/v0.1
pipe: ..
tests:
- name: the first record for an e-mail wins, whatever its letter case
inputs:
records:
values:
- {email: "Ada@Example.com", plan: pro, seats: 5}
- {email: "ada@example.com", plan: free, seats: 1}
- {email: "bob@example.org", plan: free, seats: 1}
expect:
outputs:
valid:
values:
- {email: "ada@example.com", plan: pro, seats: 5}
- {email: "bob@example.org", plan: free, seats: 1}
rejected: {count: 0}
- name: invalid records are routed to rejected with the reasons
inputs:
records:
values:
- {email: "carol@example.net", plan: enterprise, seats: 0}
- {email: "dave@example.com", plan: team}
expect:
outputs:
valid: {count: 0}
rejected:
count: 2
schema:
type: object
required: [item, errors]
properties:
errors: {type: array, minItems: 1, items: {type: object, required: [path, message]}}
- name: more distinct keys than maxKeys fails the run instead of forgetting keys
parameters: {maxKeys: 2}
inputs:
records:
values:
- {email: "a@example.com", plan: free, seats: 1}
- {email: "b@example.com", plan: free, seats: 1}
- {email: "c@example.com", plan: free, seats: 1}
expect:
status: failed
error: {code: E_RESOURCE}
- name: without a rejected consumer an invalid record fails the run
inputs:
records:
values:
- {email: "dave@example.com", plan: team}
expect:
status: failed
error: {code: E_RUNTIME}
outputs:
rejected: {disabled: true}
- name: empty input
inputs:
records: {values: []}
expect:
outputs:
valid: {count: 0}
rejected: {count: 0}openflange test .tests/deduplicate-validate.test.yaml
ok the first record for an e-mail wins, whatever its letter case
ok invalid records are routed to rejected with the reasons
ok more distinct keys than maxKeys fails the run instead of forgetting keys
ok without a rejected consumer an invalid record fails the run
ok empty input
ok 5 tests passed in 1 file (12ms)Ограничения
- Побеждает первая запись. Режима «оставить последнюю» и слияния дубликатов нет; в
std0.1 нет пайпа сортировки, поэтому, если должна побеждать самая новая запись, упорядочьте вход до пайплайна. - Ключи сравниваются точно, как значения JSON, после вашей собственной нормализации. Нечёткого сопоставления и нормализации Unicode нет.
- Память растёт с числом разных ключей, до
maxKeys(по умолчанию 1 000 000; ключи длиннее 32 байт хранятся как дайджесты SHA-256). Ещё один ключ — и запуск завершается сE_RESOURCE. - Дубликаты ищутся в пределах одного запуска. Между запусками ничего не запоминается.
- Порядок узлов важен: здесь неверная первая запись заслоняет верный дубликат, пришедший позже. Поставьте
checkпередdedupe, если побеждать должна первая верная запись. formatиз JSON Schema не проверяется, а внешние$refотклоняются: схема должна быть самодостаточной.
Связанные страницы
- Стандартные пайпы в этом рецепте:
std:map,std:distinct,std:validate-schema - Концепции, на которых он построен: Пайплайны, Порты
- Собираете это с помощью ИИ-агента? Дайте ему руководство для агентов: правила, раскладку файлов и команды, которыми он проверит собственную работу.
Все команды на этой странице выполнены в Linux с openflange 0.0.1 (go1.27.1 linux/amd64), собранным из коммита 11cf8cc5378d70858724b16aa937d7f3b98c085d репозитория openflange-go. Файлы и записанный вывод хранятся в репозитории сайта в каталоге sites/dev/test/fixtures/recipes/deduplicate-validate/, и тест побайтно сравнивает с ними эту страницу.