编辑知识图谱

字数统计: 1.2k
阅读时长: 约 3 分钟
当前版本: 4.29

支持对知识图谱执行三种不同类型的编辑:向图添加新实体关系;更新图中已存在的实体关系属性;从图中删除实体关系

注:用户必须具有编辑内容的足够权限并且必须启用编辑才能使知识图谱服务成功执行此操作。

定义编辑

添加新记录

在图中添加新记录,需要先定义新实体关系,以及它们的属性。这些属性要与添加记录的实体类型关系类型的属性相匹配。例如,如果要将一个实体添加到 Supplier 实体类型中,Supplier 实体类型具有两个属性 Name (必要属性) 和 employee_count,则新实体只能包含这两个属性,并且必须包含 Name,因为这是必要属性。

添加关系时,源实体和目标实体必须已存在于图中。

js
    //create new entity and relationship to add to the graph
    const newEntity = new Entity({
        typeName: "Supplier",
        properties: {
            Name: "Supplier 5",
            employee_count: 681
        }
    });
    const newRelationship = new Relationship({
        typeName: "buys_part",
        properties: {
            quantity: 5000
        },
        //origin and destination entities must already exist in the graph
        originId: "{1W5F4WA1-2A5W-1A5W-ANIW-1A5W4F8W4A1W}",
        destinationId: "{70CEBB71-3C04-4761-9026-3A761D471D09}"
    });

更新现有记录

更新现有记录,先根据 ID 指定需要编辑的实体或关系对象。支持更改或添加记录的属性值。例如,如果在添加 Supplier 实体时只指定了所需的 Name 属性值,则可通过添加 employee_count 的值来更新该实体。属性本身是无法添加或删除,因为它们与实体类型或关系类型相关联,只可以对属性值进行编辑修改。

js
    //update existing records
    const updateEntity1 = new Entity({
        typeName: "Supplier",
        //update the Employee_count from 681 to 685
        properties: {
            Name: "Supplier 5",
            employee_count: 685
        },
        id: "{1W5F4WA1-2A5W-1A5W-ANIW-1W5A1A5W4F8W}" //id of entity already in knowledge graph
    });
    const updateEntity2 = new Entity({
        typeName: "Supplier",
        //update the Employee_count from 700 to 750
        properties: {
            Name: "Supplier 6",
            employee_count: 750
        },
        id: "{8RDJ5R7-D1R4-E95H-D4R7-DR5D8R4EW3}" //id of entity already in knowledge graph
    });
    const updateRelationship = new Relationship({
        typeName: "buys_part",
        //update the quantity from 5000 to 5500
        properties: {
            quantity: 5500
        },
        id: "{1W5F4WA1-2A5W-1A5W-ANIW-9W5G4R8DJ7R2}" //id of relationship already in knowledge graph
    });

删除记录

通过指定实体类型或关系类型以及待删除类型的记录的 ID 列表,可指定要删除的记录。请注意,默认情况下,删除实体时还必须指定要删除的所有连接关系。如果希望自动删除这些关系,请在创建 GraphApplyEdits 对象时将 cascadeDelete 设置为 true。 (有关详细信息,请参阅应用编辑部分)

js
    //for each entity type,
    //provide a list of IDs for the entities to be deleted
    const delEntities = [
        {
            typeName: "Supplier",
            ids: ["{B1T9J5SK-1A9W-1A5W-19S6-1S9E4H8LC3TS}", "{1A9W6JM1-96A8-1A5W-1A6W-1A6W4K8PD26J}"]
        },
        {
            typeName: "Part",
            ids: ["{1B9E4S2D-2A5W-1S6E-ANIW-1S8E49G5E2S4}"]
        }
    ];
    //for each relationship type,
    //provide a list of IDs for the relationships to be deleted
    const delRelationships = [
        {
            typeName: "buys_part",
            ids: ["{T5DR8R1F-R4D8-94ES-JR5D-1D2R5S94G7ES}"]
        }
    ];

应用编辑

使用 executeApplyEdits() 将编辑应用于知识图谱。必须先定义并加载知识图谱,然后才能将其编辑内容应用于图层。如果删除实体,请指定是否自动删除所有连接的关系。有关选项参数的详细信息,请参阅 GraphApplyEdits结果将返回应用编辑时发生的任何错误,并列出每个命名类型的已修改记录的 ID。

js
    //define the function to update the graph
    const applyEdits = async () => {
        //fetch knowledge graph.
        //The knowledge graph must be loaded with a data model before other operations can be performed on it.
        let knowledgeGraph = await KnowledgeGraphModule.fetchKnowledgeGraph(url);

        //search the knowledge graph
        KnowledgeGraphModule.executeApplyEdits(
            //knowledge graph resources
            knowledgeGraph,
            //edits to the graph. Autocasts as new GraphApplyEdits
            {
                entityAdds: [newEntity],
                entityUpdates: [updateEntity1, updateEntity2],
                entityDeletes: delEntities,
                relationshipAdds: [newRelationship],
                relationshipUpdates: [updateRelationship],
                relationshipDeletes: delRelationships,
                //delete all relationships connected to the deleted entities.
                options: {
                    cascadeDelete: true
                }
            }
        ).then((applyEditResults) => {
            //review the results and notify the user of any errors.
            console.log(applyEditResults);
            if (applyEditResults.hasError) {
                alert(`Error Code: ${applyEditResults.error.errorCode}\nMessage: ${applyEditResults.error.errorMessage}`);
            }
            //otherwise, review the edits made
            else {
                let edits = applyEditResults.editResults;
                let editSummary = "";
                for (let type in edits) {
                    let edit = edits[type];
                    let added = edit.adds.map(getEditedIds);
                    let updated = edit.updates.map(getEditedIds);
                    let deleted = edit.deletes.map(getEditedIds);
                    editSummary += `<div><h3>${edit.typeName} edits</h3>
                    <p>Added IDs: ${added.length > 0 ? added.join(", ") : "None"}</p>
                    <p>Updated IDs: ${updated.length > 0 ? updated.join(", ") : "None"}</p>
                    <p>Deleted IDs: ${deleted.length > 0 ? deleted.join(", ") : "None"}</p>
                    </div>`;
                }
                document.getElementById("viewDiv").innerHTML = editSummary;
            }
        });
    };
    //call apply edits function
    applyEdits();

    //helper function to extract the Ids of the modified records from the edit results
    function getEditedIds(record) {
        return record.id;
    }