knowledgeGraphService

AMD: require(["geoscene/rest/knowledgeGraphService"], (knowledgeGraphService) => { /* code goes here */ });
ESM: import * as knowledgeGraphService from "@geoscene/core/rest/knowledgeGraphService";
类: geoscene/rest/knowledgeGraphService
起始版本:GeoScene Maps SDK for JavaScript 4.25
beta

知识图谱服务与多个资源相关联。一种资源是知识图谱,其中包含实体关系。另一种资源是定义图谱中实体类型和关系类型的数据模型。知识图谱服务允许用户查询知识图谱数据模型。可以使用 executeApplyEdits() 从知识图谱中添加、更新或删除实体和关系。

另请参阅
示例
require([
 "geoscene/rest/knowledgeGraphService"
], (knowledgeGraphModule) => {
 var knowledgeGraph;
 // define url to knowledge graph service
 const url = "https://myHostName.domain.com/server/rest/services/Hosted/myServiceName/KnowledgeGraphServer";
 // fetch knowledge graph
 KnowledgeGraphModule.fetchKnowledgeGraph(url)
  .then((kg) => {
    // do something with result
    knowledgeGraph = kg;
    console.log(knowledgeGraph);
 });
})

方法概述

名称 返回值类值 描述 对象
Promise<GraphApplyEditsResult>

知识图谱服务图谱资源中添加、删除或更新实体关系

更多详情
knowledgeGraphService
Promise<GraphQueryResult>

使用 openCypher 的 GeoScene 实现对知识图谱服务图谱资源执行查询并返回结果。

更多详情
knowledgeGraphService
Promise<GraphQueryStreamingResult>

知识图谱服务图谱资源执行流式查询。

更多详情
knowledgeGraphService
Promise<GraphQueryResult>

使用基于图谱中的属性值自动构建的全文索引搜索知识图谱,并返回结果。

更多详情
knowledgeGraphService
Promise<GraphQueryStreamingResult>

知识图谱服务图谱资源执行流式搜索。

更多详情
knowledgeGraphService
Promise<KnowledgeGraph>

根据提供的 URL 检索知识图谱服务。

更多详情
knowledgeGraphService

刷新知识图谱数据模型

更多详情
knowledgeGraphService

方法详细说明

executeApplyEdits(graph, edits, requestOptions){Promise<GraphApplyEditsResult>}

知识图谱服务图谱资源中添加、删除或更新实体关系。此操作不允许添加或删除实体类型或关系类型的属性。但是,用户可以更新实体或关系以更改其属性值。

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

与服务相关联的知识图谱

指定要添加、更新或删除的实体关系及其属性。

requestOptions RequestOptions
optional

用于数据请求的附加选项(将覆盖构造期间定义的 requestOptions)。

返回
类型 描述
Promise<GraphApplyEditsResult> 解析后,结果为 GraphApplyEditsResult
另请参阅
示例
// sample executeApplyEdits() to add a new entity to the `Supplier` entity type
const newEntity = new Entity({
  typeName: "Supplier",
  properties: {
    Name: "Supplier 5",
    EmployeeCount: 681
  }
});
KnowledgeGraphModule.executeApplyEdits(
  graph, {
      entityAdds: [newEntity]
    })
    .then((editResult) => {
      console.log("Graph Add Result", editResult);
    });
});
// Basic example results of adding one entity to the `Supplier` entity type
{
  editResults:[{
    adds:[
    {
      id: "{A1W5F4A8S-41F1-49A4-8412-ANIWN9906E88}",
      error: false
    }],
    deletes:[],
    typeName: "Supplier",
    updates:[]
  }],
  hasError: false,
  error: undefined
}
//update existing records
const updateEntity = new Entity({
  typeName: "Supplier",
  // update the EmployeeCount from 681 to 685
  properties: {
    Name: "Supplier 5",
    EmployeeCount: 685
  },
  id:"{A1W5F4A8S-41F1-49A4-8412-ANIWN9906E88}" //id of entity already in knowledge graph
});
const updateRelationship = new 关系({
  typeName: "buys_part",
  properties: {
    quantity: 5000
  },
  // origin and destination entities must already exist in the graph
  originId: "{AN4E4G85-41F1-49A4-8412-CACCC9906E88}",
  destinationId: "{9D2D6AFD-41F1-49A4-8412-1DGR8E5D6S1G4}"
});
KnowledgeGraphModule.executeApplyEdits(
  graph, {
      entityUpdates: [updateEntity],
      relationshipUpdates: [updateRelationship]
    })
    .then((editResult) => {
      console.log("Graph Update Result", editResult);
    });
});
//delete existing records
KnowledgeGraphModule.executeApplyEdits(
  graph, {
      entityDeletes: [{
        typeName: "Supplier",
        ids: ["{AMGIE541G-41F1-49A4-8412-CACCC9906E88}", "{HNWIGHE15-WH52-2GE6-1A5W-A1F8W4FS3A1S5}"]
      },{
        typeName: "Part",
        ids: ["{FNIW4GF1-ANFW-49A4-ANW7-GNWIGHAF4S51FS}"]
      }],
      relationshipDeletes: [{
        typeName: "Buys_part",
        ids: ["{MH4E54G8E-MF4W-1842-2S44-15AF5W8F4S2W8}"]
      }],
      //delete all relationships connected to the deleted entities.
      options:{
        cascadeDelete: true
      }
    })
    .then((editResult) => {
      console.log("Graph Delete Result", editResult);
    });
});
executeQuery(graph, queryArguments, requestOptions){Promise<GraphQueryResult>}

使用 openCypher 的 GeoScene 实现对知识图谱服务图谱资源执行查询并返回结果。

参数

与服务相关联的知识图谱

queryArguments GraphQuery

定义要对提供的知识图谱服务执行的查询

requestOptions RequestOptions
optional

用于数据请求的附加选项(将覆盖构造期间定义的 requestOptions)。

返回
类型 描述
Promise<GraphQueryResult> 解析后,结果为 GraphQueryResult
另请参阅
示例
// typical use case
KnowledgeGraphModule.executeQuery(
 knowledgeGraph, //graph
 { // queryArguments
   openCypherQuery: "MATCH (n) RETURN n LIMIT 100", //query
  }).then((queryResult) => {
    // do something with the result
});
executeQueryStreaming(graph, queryArguments, requestOptions){Promise<GraphQueryStreamingResult>}

知识图谱服务图谱资源执行流式查询。流式查询可返回一个可读的流,必须读取该流才能访问返回的图谱数据。与 executeQuery() 不同,executeQueryStreaming() 以小块形式返回结果,可立即进行处理,而无需等待返回所有结果。流式查询比 executeQuery() 更快、更高效。即使总数超过服务中定义的 maxRecordCount,流式查询也会检索所有匹配的记录,而无需额外的查询或分页。流式查询的另一个好处是查询是编码的,这意味着它比传统的 HTTP GET 或 JSON POST 的 body 小得多。当试图对非常大的参数进行查询时 (例如,大型 ID 集或与复杂几何体相交),这一点尤其重要。

通过发送 openCypher 查询的 GeoScene 实现来查询图谱中的实体和关系。

参数

与服务相关联的知识图谱

queryArguments GraphQueryStreaming

定义要对提供的知识图谱服务执行的查询。可选,指定其他查询参数

requestOptions RequestOptions
optional

用于数据请求的附加选项(将覆盖构造期间定义的 requestOptions)。

返回
类型 描述
Promise<GraphQueryStreamingResult> 解析后,结果为 GraphQueryStreamingResult
另请参阅
示例
// sample streaming query using bind parameters
// to search for entities with a the `name` property that matches a specific string
// or have their geometry within a bounding box.
// get all parts bought by each supplier.
// query returns both the supplier and the part it buys.
const query = `MATCH (s:Supplier)-[:buys_part]-(p:Part)
               WHERE s.name=$name OR geoscene.graph.ST_Intersects($geom, s.geometry)
               RETURN s,p`;

KnowledgeGraphModule.executeQueryStreaming(
  knowledgeGraph,
  {
    openCypherQuery: query,
    bindParameters: {
      name: "Supplier 5",
      //bounding box around the area of Washington DC, USA
      geom: new Polygon({
        rings: [
          [
            [38,-78],
            [39, -78],
            [39, -76],
            [-38, -76],
            [-38, -78],
          ],
       ],
    }),
  }
}).then((streamingQueryResult)=>{
  // streaming query returns a readableStream which must be read to access the returned graph data
  readStream(streamingQueryResult)
});
// a function to read the readable stream returned from the above query
const readStream = async (streamingQueryResult) => {
  let time = Date.now();
  let reader = streamingQueryResult.resultRowsStream.getReader();
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log(`Completed database requests: ${(Date.now() - time) / 1000} seconds`);
        break;
      }
      console.log(`Chunk returned in: ${(Date.now() - time) / 1000} seconds`);
      // use the results
      // list the parts bought by each supplier
      let supplierParts = {};
      // each element of the result array will contain one supplier and one part it buys
      for (var v in value){
        let supplier = value[v][0].properties.Name
        let part = value [v][1].properties.Name
        if(!(supplier in supplierParts)){
          supplierParts[supplier] = [];
        }
        // collect parts by supplier that buys them
        supplierParts[supplier].push(part);
        console.log(supplierParts);
        // result printed to the console: {Supplier 1:[Part1], Supplier 3:[Part2, Part3]}
    }
  } catch (err) {
    if (err.name === "AbortError") {
      console.log("Request aborted as expected");
    } else {
      throw err;
    }
  }
};
// result stream from above query after it has been read
"Streaming chunk returned in: 0.082 seconds"
[
  [{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Name": "Supplier 1",
      "City": "Washington DC",
      "EmployeeCount": 31
    },
    "typeName": "Supplier",
    "id": "{57FDF2F3-34C8-48EF-9A3B-76ED9314C4D2}"
  },{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Part_ID": 695401,
      "Name": "Part1",
      "Minimum_quantity": 360
    },
    "typeName": "Part",
    "id": "{IWN51W4-1AW8-A2W6-1AW5F-1AW8F9F4W51AS}",
  }],
  [{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Name": "Supplier 2",
      "City": "Baltimore",
      "EmployeeCount": 53
    },
    "typeName": "Supplier",
    "id": "{1A4W8F5W-1WA8-5W6A-A1W8-A1W5F8W3S482A}"
  },{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Part_ID": 695401,
      "Name": "Part2",
      "Minimum_quantity": 2500
    },
    "typeName": "Part",
    "id": "{A1W5F8W4F-A1W8-1894-16A5-A86WF4A8SFWD}",
  }],
  [{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Name": "Supplier 2",
      "City": "Baltimore",
      "EmployeeCount": 53
    },
    "typeName": "Supplier",
    "id": "{1A4W8F5W-1WA8-5W6A-A1W8-L5H4G8RT1PK3}"
  },{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Part_ID": 695401,
      "Name": "Part3",
      "Minimum_quantity": 5000
    },
    "typeName": "Part",
    "id": "{PTJ51FT-KY4H-1GY5-G1Y8-G1Y5K49G8Y4GHJ}",
  }]
]
// aborting the query
// create instance of native browser abort controller
const controller = new AbortController();

// create query
KnowledgeGraphModule.executeQueryStreaming(
    knowledgeGraph,
    {
      openCypherQuery: "MATCH (n) RETURN n LIMIT 100",
    },
    {
      signal: controller.signal,
    }
  )
  .then((streamingQueryResult) => {
    readStream(streamingQueryResult);
  })
  // indicate that the stream was aborted
  .catch((err) => {
    if (err.name === "AbortError") {
      console.log("Request aborted as expected");
    }

// abort the query after half a second
setTimeout(() => {
  console.log("Sending abort signal");
  controller.abort();
}, 500);
executeSearch(graph, searchArguments, requestOptions){Promise<GraphQueryResult>}

使用基于图谱中的属性值自动构建的全文索引搜索知识图谱,并返回结果。搜索接受 Lucene 搜索语法。使用 DataModel 查看每个 RelationshipTypeEntityType 的索引字段。

参数

与服务相关联的知识图谱

searchArguments GraphSearch

定义针对知识图谱运行的自由文本搜索

requestOptions RequestOptions
optional

用于数据请求的附加选项(将覆盖构造期间定义的 requestOptions)。

返回
类型 描述
Promise<GraphQueryResult> 解析后,结果为 GraphQueryResult,其中包含与搜索相匹配的所有记录。如果没有匹配项,结果将为空。
另请参阅
示例
// typical use case
KnowledgeGraphModule.executeSearch(
 knowledgeGraph, //graph
 { // searchArguments
   searchQuery: "Sun", //search term
   typeCategoryFilter: "both" //search entities, relationships or both.
  }).then((searchResult) => {
    // do something with the result
   console.log(searchResult)
});
// sample search result
{
  "declaredClass": "geoscene.rest.knowledgeGraph.GraphQueryResult",
  "resultRows": [
    [
      {
        "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
        "properties": {
          "shape": {
            "declaredClass": "geoscene.geometry.Point",
            "cache": {},
            "hasM": false,
            "hasZ": false,
            "latitude": 53.589000000000006,
            "longitude": -0.9633,
            "type": "point",
            "extent": null,
            "spatialReference": {
              "wkid": 4326
            },
            "x": -0.9633,
            "y": 53.589000000000006
          },
          "Name": "Suncommon",
          "Employee_Count": 400
        },
        "typeName": "Company",
        "id": "{WIPJ483T-U8UI-LLK9-YUI8-Y5YK8YGD88E9}",
      }
    ],
    [
       {
        "declaredClass": "geoscene.rest.Relationship.Relationship",
        "originID": "{44027400-4B48-4FF2-B526-E27FC17EC246}",
        "destinationID": "{CB0CF580-3899-491E-8F10-0AD1DA4EE49B}",
        "properties": {
          "orderDay": "Sunday",
          "quantity": 15000
        },
        "typeName": "buys_part",
        "id": "{ABCDEFG-0000-1111-2222-0AD1DA4EE49B}"
      }
    ]
  }
executeSearchStreaming(graph, searchArguments, requestOptions){Promise<GraphQueryStreamingResult>}

知识图谱服务图谱资源执行流式搜索。流式搜索可返回一个可读的流,必须读取该流才能访问返回的数据。与 executeSearch() 不同,executeSearchStreaming() 以小块形式返回结果,可立即进行处理,而无需等待返回所有结果。流式搜索比 executeSearch() 更快、更高效。即使总数超过服务中定义的 searchMaxRecordCount,流式搜索也会检索所有匹配的记录,而无需额外的查询或分页。流式搜索的另一个好处是请求是编码的,这意味着它比传统的 HTTP GET 或 JSON POST 的 body 小得多。当试图对非常大的参数进行搜索时 (例如,大型 ID 集),这一点尤其重要。

流式搜索接受 Lucene 搜索语法。流式搜索使用基于图谱中的属性值自动构建的全文索引。使用 DataModel 查看每个 RelationshipTypeEntityType 的索引字段。

参数

与服务相关联的知识图谱

searchArguments GraphSearchStreaming

定义针对知识图谱执行的自由文本搜索。可选,指定其他搜索参数。

requestOptions Object
optional

用于数据请求的附加选项(将覆盖构造期间定义的 requestOptions)。

返回
类型 描述
Promise<GraphQueryStreamingResult> 解析后,结果为 GraphQueryStreamingResult,其中包含与搜索相匹配的所有记录。如果没有匹配项,结果将为空。
另请参阅
示例
// example search for "solar"with additional parameters
KnowledgeGraphModule.executeSearchStreaming(
  knowledgeGraph,
  {
    searchQuery: "solar",
    typeCategoryFilter: "both",
    returnSearchContext: false,
    start: 1,
    num: 200, //return 200 records.
    namedTypesFilter: ["Company", "Supplier", "Part"],
    globalIdsFilter: ["{G4E8G2S8D-2GS5-98S4-3S5D-S1DE7G45DS48}",
                     "{FNWI1G5W-1A5W-3A5W-8412-A1W5F4W8F7AS}",
                     "{9D2D6AFD-41F1-49A4-8412-CACCC9906E88}"]
  }
).then((streamingSearchResult)=>{
  // the result of a streaming search is a readableStream which requires decoding.
  readStream(streamingSearchResult)
})
// a function to read the readable stream returned from the above query
const readStream = async (streamingQueryResult) => {
  let time = Date.now();
  let reader = streamingQueryResult.resultRowsStream.getReader();
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log(`Completed database requests: ${(Date.now() - time) / 1000} seconds`, value);
        break;
      }
      console.log(`Chunk returned in: ${(Date.now() - time) / 1000} seconds`, value)
    }
  } catch (err) {
    if (err.name === "AbortError") {
      console.log("Request aborted as expected");
    } else {
      throw err;
    }
  }
};
// sample result of streaming search result chunk read and printed to the console

"Streaming chunk returned in: 0.082 seconds"
[
  [{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Name": "Suncommon",
      "Employee_Count": 400,
      "energyType": "solar"
    },
    "typeName": "Company",
    "id": "{G4E8G2S8D-2GS5-98S4-3S5D-S1DE7G45DS48}"
  }],
  [{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Name": "Quality Solar Supply",
      "Supplier_code": "158B",
      "City": "New Orleans",
    },
    "typeName": "Supplier",
    "id": "{FNWI1G5W-1A5W-3A5W-8412-A1W5F4W8F7AS}"
  }],
  [{
    "declaredClass": "geoscene.rest.knowledgeGraph.Entity",
    "properties": {
      "Name": "Solar panel",
      "panel_type": "Polycrystalline",
      "price_per_unit": 400
    },
    "typeName": "Part",
    "id": "{9D2D6AFD-41F1-49A4-8412-CACCC9906E88}"
  }]
]
fetchKnowledgeGraph(url){Promise<KnowledgeGraph>}

根据提供的 URL 检索知识图谱服务。

参数
url String

表示知识图谱服务的 GeoScene Knowledge Server REST 资源的 URL。

返回
类型 描述
Promise<KnowledgeGraph> 解析后,结果为 KnowledgeGraph
示例
// typical use case
const url = "https://myHostName.domain.com/server/rest/services/Hosted/myServiceName/KnowledgeGraphServer";

KnowledgeGraphModule.fetchKnowledgeGraph(url)
.then((kg) => {
    // do something with result
});
refreshDataModel(graph)
参数

与服务相关联的知识图谱

示例
// typical use case
KnowledgeGraphModule.refreshDataModel(urlToKnowledgeGraph).then((newKG) => {
    // do something with result
});

您的浏览器不再受支持。请升级您的浏览器以获得最佳体验。请参阅浏览器弃用帖子以获取更多信息