上面的 graphql 模式将生成以下谓词:
Customer.name
Customer.reviews
Product.name
Product.reviews
Review.about
Review.by
Review.comment
Review.rating
Schema.date
Schema.schema
即Type.property
批量导入值,不需要指定类型,使用正确的属性名即可。
这是一个工作示例:
const product = {
"dgraph.type":"Product",
"uid": "_:5678",
"Product.name": "Bluetooth headset"
};
const customer = {
"uid": "_:deadbeef",
"dgraph.type":"Customer",
"Customer.name": "Bill Gates",
"Customer.reviews": [
{
"uid": "_:1234",
"dgraph.type":"Review",
"Review.comment": "nice product",
"Review.rating": 5,
"Review.by": {"uid": "_:deadbeef"},
"Review.about": {"uid": "_:5678"}
}
]
};
// Run mutation.
const mu = new Mutation();
mu.setSetJson({set: [product, customer]});
如果要导入包含数千个条目的块,则需要找到一种方法来在交易中保留空白 ID。为了实现这一点,我建议使用一个类来负责在导入的块之间保存地图。这是我的 POC
import {DgraphClient, DgraphClientStub, Mutation} from "dgraph-js";
import * as jspb from 'google-protobuf';
type uidMap = jspb.Map<string, string>;
class UidMapper {
constructor(private uidMap: uidMap = UidMapper.emptyMap()) {
}
private static emptyMap(): uidMap {
return new jspb.Map<string, string>([]);
}
public uid(uid: string): string {
return this.uidMap.get(uid) || `_:${uid}`;
}
public addMap(anotherMap: uidMap): void {
anotherMap.forEach((value, key) => {
this.uidMap.set(key, value);
});
}
}
class Importer {
public async importTest(): Promise<void> {
try {
const clientStub = new DgraphClientStub(
"localhost:9080",
grpc.credentials.createInsecure(),
);
const dgraphClient: DgraphClient = new DgraphClient(clientStub);
await this.createData(dgraphClient);
clientStub.close();
} catch (error) {
console.log(error);
}
}
private async createData(dgraphClient: DgraphClient): Promise<void> {
const mapper = new UidMapper();
const product = {
"dgraph.type":"Product",
"uid": mapper.uid("5678"),
"Product.name": "Bluetooth headset"
};
const customer = ...;
const addMoreInfo = ...;
await this.setJsonData(dgraphClient, mapper, [product, customer]);
await this.setJsonData(dgraphClient, mapper, [addMoreInfo]);
}
private async setJsonData(dgraphClient: DgraphClient, mapper: UidMapper, data: any[]) {
// Create a new transaction.
const txn = dgraphClient.newTxn();
try {
// Run mutation.
const mu = new Mutation();
mu.setSetJson({set: data});
let response = await txn.mutate(mu);
// Commit transaction.
mapper.addMap(response.getUidsMap());
await txn.commit();
} finally {
// Clean up. Calling this after txn.commit() is a no-op and hence safe.
await txn.discard();
}
}
}