ArcGIS Pro 3.8 API Reference Guide
ArcGIS.Core.Data.Knowledge Namespace / KnowledgeGraphNamedObjectValue Class / GetObjectID Method
Example

In This Topic
    GetObjectID Method (KnowledgeGraphNamedObjectValue)
    In This Topic
    Gets the ObjectID or -1 if the named object does not have one. This method must be called on the MCT. Use QueuedTask.Run.
    Syntax
    public virtual long GetObjectID()
    Public Overridable Function GetObjectID() As Long

    Return Value

    Exceptions
    ExceptionDescription
    This method or property must be called within the lambda passed to QueuedTask.Run.
    Remarks
    Use GetHasObjectID to determine if a named object has an object ID.
    Example
    Convert an Open Cypher Query Result to a Selection
    {
      await QueuedTask.Run(async () =>
      {
        //Given an open-cypher qry against an entity or relationship type
        var qry = @"MATCH (p:PhoneNumber) RETURN p LIMIT 10";
    
        //create a KG query filter
        var kg_qry_filter = new KnowledgeGraphQueryFilter()
        {
          QueryText = qry
        };
    
        //save a list of the ids
        var oids = new List<long>();
        using (var kgRowCursor = kg.SubmitQuery(kg_qry_filter))
        {
          //wait for rows to be returned asynchronously from the server
          while (await kgRowCursor.WaitForRowsAsync())
          {
            //get the rows using "standard" move next
            while (kgRowCursor.MoveNext())
            {
              //current row is accessible via ".Current" prop of the cursor
              using (var graphRow = kgRowCursor.Current)
              {
                var cell_phone = graphRow[0] as KnowledgeGraphEntityValue;
                //note: some user-managed graphs do not have objectids
                oids.Add(cell_phone.GetObjectID());
              }
            }
          }
        }
        //create a query filter using the oids
        if (oids.Count > 0)
        {
          //select them on the layer
          var qf = new ArcGIS.Core.Data.QueryFilter()
          {
            ObjectIDs = oids //apply the oids to the ObjectIds property
          };
          //select the child feature layer or standalone table representing
          //the given entity or relate type whose records are to be selected
          var phone_number_fl = kgLayer.GetLayersAsFlattenedList()
              .OfType<FeatureLayer>().First(l => l.Name == "PhoneNumber");
    
          //perform the selection
          phone_number_fl.Select(qf);
        }
      });
    }
    Use Bind Parameters with an Open Cypher Query
    {
      await QueuedTask.Run(async () =>
      {
        //assume we have, in this case, a list of ids (perhaps retrieved
        //via a selection, hardcoded (like here), etc.
        var oids = new List<long>() { 3,4,7,8,9,11,12,14,15,19,21,25,29,
       31,32,36,37,51,53,54,55,56,59,63,75,78,80,84,86,88,96,97,98,101,
       103,106};
        //In the query, we refer to the "bind parameter" with the
        //"$" and a variable name - '$object_ids' in this example
        var qry = @"MATCH (p:PhoneNumber) " +
                  @" WHERE p.objectid IN $object_ids " +
                  @"RETURN p";
    
        //we provide the values to be substituted for the variable via the
        //KnowledgeGraphQueryFilter BindParameter property...
        var kg_qry_filter = new KnowledgeGraphQueryFilter()
        {
          QueryText = qry
        };
        //the bind parameter added to the query filter must refer to
        //the variable name used in the query string (without the "$")
        //Note:
        //Collections must be converted to a KnowledgeGraphArrayValue before
        //being assigned to a BindParameter
        var kg_oid_array = new KnowledgeGraphArrayValue();
        kg_oid_array.AddRange(oids);
        oids.Clear();
    
        kg_qry_filter.BindParameters["object_ids"] = kg_oid_array;
    
        //submit the query
        using (var kgRowCursor = kg.SubmitQuery(kg_qry_filter))
        {
          //wait for rows to be returned asynchronously from the server
          while (await kgRowCursor.WaitForRowsAsync())
          {
            //get the rows using "standard" move next
            while (kgRowCursor.MoveNext())
            {
              //current row is accessible via ".Current" prop of the cursor
              using (var graphRow = kgRowCursor.Current)
              {
                var cell_phone = graphRow[0] as KnowledgeGraphEntityValue;
                var oid = cell_phone.GetObjectID();
    
                var name = (string)cell_phone["FULL_NAME"];
                var ph_number = (string)cell_phone["PHONE_NUMBER"];
                System.Diagnostics.Debug.WriteLine(
                  $"[{oid}] {name}, {ph_number}");
              }
            }
          }
        }
      });
    }
    Use Bind Parameters with an Open Cypher Query2
    {
      var mapView = MapView.Active;
      if (mapView == null)
        return;
    
      await QueuedTask.Run(async () =>
      {
        //assume we have, in this case, a list of ids (perhaps retrieved
        //via a selection, hardcoded (like here), etc.
        var oids = new List<long>() { 3,4,7,8,9,11,12,14,15,19,21,25,29,
       31,32,36,37,51,53,54,55,56,59,63,75,78,80,84,86,88,96,97,98,101,
       103,106};
        //In the query, we refer to the "bind parameter" with the
        //"$" and a variable name - '$object_ids' and '$sel_geom'
        //in this example
        var qry = @"MATCH (p:PhoneNumber) " +
                    @"WHERE p.objectid IN $object_ids AND " +
                    @"esri.graph.ST_Intersects($sel_geom, p.shape) " +
                    @"RETURN p";
        //create a KG query filter
        var kg_qry_filter = new KnowledgeGraphQueryFilter()
        {
          QueryText = qry
        };
    
        //the bind parameter added to the query filter must refer to
        //the variable name used in the query string (without the "$")
        //Note:
        //Collections must be converted to a KnowledgeGraphArrayValue before
        //being assigned to a BindParameter
        var kg_oid_array = new KnowledgeGraphArrayValue();
        kg_oid_array.AddRange(oids);
        kg_qry_filter.BindParameters["object_ids"] = kg_oid_array;
    
        //Create a polygon based on current map extent
        var extent = mapView.Extent;
        var poly = PolygonBuilder.CreatePolygon(extent.Expand(0.25, 0.25, true));
        kg_qry_filter.BindParameters["sel_geom"] = poly;
        oids.Clear();
    
        //submit the query
        using (var kgRowCursor = kg.SubmitQuery(kg_qry_filter))
        {
          //wait for rows to be returned asynchronously from the server
          while (await kgRowCursor.WaitForRowsAsync())
          {
            //get the rows using "standard" move next
            while (kgRowCursor.MoveNext())
            {
              //current row is accessible via ".Current" prop of the cursor
              using (var graphRow = kgRowCursor.Current)
              {
                // cref: ArcGIS.Core.Data.Knowledge.KnowledgeGraphNamedObjectValue.GetObjectID()
                #region Process Row
                {
    
                  var cell_phone = graphRow[0] as KnowledgeGraphEntityValue;
                  var oid = cell_phone.GetObjectID();
    
                  var name = (string)cell_phone["FULL_NAME"];
                  var ph_number = (string)cell_phone["PHONE_NUMBER"];
                  System.Diagnostics.Debug.WriteLine(
                    $"[{oid}] {name}, {ph_number}");
    
                }
    Process a KnowledgeGraphRow Value
    void ProcessGraphNamedObjectValue(
      KnowledgeGraphNamedObjectValue kg_named_obj_val)
    {
      if (kg_named_obj_val is KnowledgeGraphEntityValue kg_entity)
      {
        var label = kg_entity.GetLabel();
        //TODO - use label
      }
      else if (kg_named_obj_val is KnowledgeGraphRelationshipValue kg_rel)
      {
        var has_entity_ids = kg_rel.GetHasRelatedEntityIDs();
        if (kg_rel.GetHasRelatedEntityIDs())
        {
          var origin_id = kg_rel.GetOriginID();
          var dest_id = kg_rel.GetDestinationID();
          //TODO - use ids
        }
      }
      var id = kg_named_obj_val.GetID();
      var oid = kg_named_obj_val.GetObjectID();
      //Note: Typename corresponds to the name of the feature class or table
      //in the relational gdb model -and- to the name of the KnowledgeGraphNamedObjectType
      //in the knowledge graph data model
      var type_name = kg_named_obj_val.GetTypeName();
      //TODO use id, object id, etc.
    }
    
    //Object values include entities, relationships, and anonymous objects
    void ProcessGraphObjectValue(KnowledgeGraphObjectValue kg_obj_val)
    {
      switch (kg_obj_val)
      {
        case KnowledgeGraphEntityValue kg_entity:
          ProcessGraphNamedObjectValue(kg_entity);
          break;
        case KnowledgeGraphRelationshipValue kg_rel:
          ProcessGraphNamedObjectValue(kg_rel);
          break;
        default:
          //Anonymous objects
          break;
      }
      //graph object values have a set of properties (equivalent
      //to a collection of key/value pairs)
      var keys = kg_obj_val.GetKeys();
      foreach (var key in keys)
      {
        ProcessKnowledgeGraphRowValue(kg_obj_val[key]);//Recurse
      }
    }
    
    //Process a KnowledgeGraphValue from a query or search
    void ProcessGraphValue(KnowledgeGraphValue kg_val)
    {
      switch (kg_val)
      {
        case KnowledgeGraphPrimitiveValue kg_prim:
          //KnowledgeGraphPrimitiveValue not currently used in
          //query and search
          ProcessKnowledgeGraphRowValue(kg_prim.GetValue());//Recurse
          return;
        case KnowledgeGraphArrayValue kg_array:
          var count = kg_array.GetSize();
          //Recursively process each value in the array
          for (ulong i = 0; i < count; i++)
          {
            ProcessKnowledgeGraphRowValue(kg_array[i]);//Recurse
          }
    
          return;
        case KnowledgeGraphPathValue kg_path:
          //Entities
          var entity_count = kg_path.GetEntityCount();
          //Recursively process each entity value in the path
          for (ulong i = 0; i < entity_count; i++)
          {
            ProcessGraphObjectValue(kg_path.GetEntity(i));//Recurse
          }
    
          //Recursively process each relationship value in the path
          var relate_count = kg_path.GetRelationshipCount();
          for (ulong i = 0; i < relate_count; i++)
          {
            ProcessGraphObjectValue(kg_path.GetRelationship(i));//Recurse
          }
    
          return;
        case KnowledgeGraphObjectValue kg_object:
          ProcessGraphObjectValue(kg_object);//Recurse
          return;
        default:
          var type_string = kg_val.GetType().ToString();
          System.Diagnostics.Debug.WriteLine(
            $"Unknown: '{type_string}'");
          return;
      }
    }
    
    //Process each value from the KnowledgeGraphRow array
    void ProcessKnowledgeGraphRowValue(object value)
    {
      switch (value)
      {
        //Graph value?
        case KnowledgeGraphValue kg_val:
          var kg_type = kg_val.KnowledgeGraphValueType.ToString();
          System.Diagnostics.Debug.WriteLine(
            $"KnowledgeGraphValue: '{kg_type}'");
          ProcessGraphValue(kg_val);//Recurse
          return;
        //Primitive types...add additional logic as needed
        case System.DBNull dbn:
          System.Diagnostics.Debug.WriteLine("DBNull.Value");
          return;
        case string str:
          System.Diagnostics.Debug.WriteLine($"'{str}' (string)");
          return;
        case long l_val:
          System.Diagnostics.Debug.WriteLine($"{l_val} (long)");
          return;
        case int i_val:
          System.Diagnostics.Debug.WriteLine($"{i_val} (int)");
          return;
        case short s_val:
          System.Diagnostics.Debug.WriteLine($"{s_val} (short)");
          return;
        case double d_val:
          System.Diagnostics.Debug.WriteLine($"{d_val} (double)");
          return;
        case float f_val:
          System.Diagnostics.Debug.WriteLine($"{f_val} (float)");
          return;
        case DateTime dt_val:
          System.Diagnostics.Debug.WriteLine($"{dt_val} (DateTime)");
          return;
        case DateOnly dt_only_val:
          System.Diagnostics.Debug.WriteLine($"{dt_only_val} (DateOnly)");
          return;
        case TimeOnly tm_only_val:
          System.Diagnostics.Debug.WriteLine($"{tm_only_val} (TimeOnly)");
          return;
        case DateTimeOffset dt_tm_offset_val:
          System.Diagnostics.Debug.WriteLine(
            $"{dt_tm_offset_val} (DateTimeOffset)");
          return;
        case System.Guid guid_val:
          var guid_string = guid_val.ToString("B");
          System.Diagnostics.Debug.WriteLine($"'{guid_string}' (Guid)");
          return;
        case ArcGIS.Core.Geometry.Geometry geom_val:
          var geom_type = geom_val.GeometryType.ToString();
          var is_empty = geom_val.IsEmpty;
          var wkid = geom_val.SpatialReference?.Wkid ?? 0;
          System.Diagnostics.Debug.WriteLine(
            $"geometry: {geom_type}, empty: {is_empty}, sr_wkid {wkid} (shape)");
          return;
        default:
          //Blob? Others?
          var type_str = value.GetType().ToString();
          System.Diagnostics.Debug.WriteLine($"Primitive: {type_str}");
          return;
      }
    }
    
    // ...submit query or search
    //using (var kgRowCursor = kg.SubmitQuery(kg_qf)) {
    //using (var kgRowCursor = kg.SubmitSearch(kg_sf)) {
    //  ...wait for rows ...
    //  while (await kgRowCursor.WaitForRowsAsync()) {
    //   ...rows have been retrieved
    //   while (kgRowCursor.MoveNext()) {
    //     ...get the current KnowledgeGraphRow
    //     using (var graph_row = kgRowCursor.Current) {
    //        var val_count = (int)graph_row.GetCount();
    //        for (int i = 0; i<val_count; i++)
    //           ProcessKnowledgeGraphRowValue(graph_row[i]);
    Create a Link Chart from a query
    {
      //use the results of a query to create an idset. Create the link chart
      //containing just records corresponding to the query results
      var qry = @"MATCH (p1:PhoneNumber)-[r1:MADE_CALL|RECEIVED_CALL]->(c1:PhoneCall)<-" +
                @"[r2:MADE_CALL|RECEIVED_CALL]-(p2:PhoneNumber)-[r3:MADE_CALL|RECEIVED_CALL]" +
                @"->(c2:PhoneCall)<-[r4:MADE_CALL|RECEIVED_CALL]-(p3:PhoneNumber) " +
                @"WHERE p1.FULL_NAME = ""Robert Johnson"" AND " +
                @"p3.FULL_NAME= ""Dan Brown"" AND " +
                @"p1.globalid <> p2.globalid AND " +
                @"p2.globalid <> p3.globalid " +
                @"RETURN p1, r1, c1, r2, p2, r3, c2, r4, p3";
    
      var dict = new Dictionary<string, List<long>>();
    
      var queryLinkChart = await QueuedTask.Run(async () =>
      {
        using (var kg_for_lc = kgLayer.GetDatastore())
        {
          var graphQuery = new KnowledgeGraphQueryFilter()
          {
            QueryText = qry
          };
    
          using (var kg_rc = kg_for_lc.SubmitQuery(graphQuery))
          {
            while (await kg_rc.WaitForRowsAsync())
            {
              while (kg_rc.MoveNext())
              {
                using (var graphRow = kg_rc.Current)
                {
                  // process the row
                  var cnt_val = (int)graphRow.GetCount();
                  for (int v = 0; v < cnt_val; v++)
                  {
                    var obj_val = graphRow[v] as KnowledgeGraphNamedObjectValue;
                    var type_name = obj_val.GetTypeName();
                    var oid = (long)obj_val.GetObjectID();
                    if (!dict.ContainsKey(type_name))
                    {
                      dict[type_name] = new List<long>();
                    }
                    if (!dict[type_name].Contains(oid))
                    {
                      dict[type_name].Add(oid);
                    }
                  }
                }
              }
            }
          }
          //make an ID Set to create the LinkChart
          var idSet = KnowledgeGraphLayerIDSet.FromDictionary(kg_for_lc, dict);
    
          //Create the link chart and show it
          return MapFactory.Instance.CreateLinkChart(
                   "KG With ID Set", kg_for_lc, idSet);
        }
      });
      await FrameworkApplication.Panes.CreateMapPaneAsync(queryLinkChart);
    }
    Append to Link Chart
    {
      //We create an id set to contain the records to be appended
      var dict = new Dictionary<string, List<long>>();
      dict["Suspects"] = new List<long>();
    
      //In this case, via results from a query...
      var qry2 = "MATCH (s:Suspects) RETURN s";
    
      await QueuedTask.Run(async () =>
      {
        using (var kg_for_lc = kgLayer.GetDatastore())
        {
          var graphQuery = new KnowledgeGraphQueryFilter()
          {
            QueryText = qry2
          };
    
          using (var kg_rc = kg_for_lc.SubmitQuery(graphQuery))
          {
            while (await kg_rc.WaitForRowsAsync())
            {
              while (kg_rc.MoveNext())
              {
                using (var graphRow = kg_rc.Current)
                {
                  var obj_val = graphRow[0] as KnowledgeGraphNamedObjectValue;
                  var oid = (long)obj_val.GetObjectID();
                  dict["Suspects"].Add(oid);
                }
              }
            }
          }
    
          //make an ID Set to append to the LinkChart
          var idSet = KnowledgeGraphLayerIDSet.FromDictionary(kg_for_lc, dict);
          //Get the relevant link chart to which records will be
          //appended...in this case, from an open map pane in the
          //Pro application...
          var mapPanes = FrameworkApplication.Panes.OfType<IMapPane>().ToList();
          var mapPane = mapPanes.First(
            mp => mp.MapView.IsLinkChartView &&
            mp.MapView.Map.Name == "Acme Link Chart");
          var linkChartMap = mapPane.MapView.Map;
    
          //or get the link chart from an item in the catalog...etc.,etc.
          //var projectItem = Project.Current.GetItems<MapProjectItem>()
          //      .FirstOrDefault(pi => pi.Name == "Acme Link Chart");
          //var linkChartMap = projectItem?.GetMap();
    
          //Call AppendToLinkChart with the id set
          if (linkChartMap.CanAppendToLinkChart(idSet))
          {
            linkChartMap.AppendToLinkChart(idSet);
          }
        }
      });
    }
    Requirements

    Target Platforms: Windows 11 Home, Pro, Enterprise (64 bit)

    ArcGIS Pro version: 3.2 or higher.
    See Also