arcgis.features module
Thearcgis.features
module contains types and functions for working with features and feature layers in theGIS
.
Entities located in space with a geometrical representation (such as points, lines or polygons) and a set of propertiescan be represented as features. Thearcgis.features
module is used for working with feature data, feature layers andcollections of feature layers in the GIS. It also contains the spatial analysis functions which operate againstfeature data.
In theGIS
, entities located in space with a set of properties can be represented as features. Features are storedas feature classes, which represent a set of features located using a single spatial type (point, line, polygon) and acommon set of properties. This is the geographic extension of the classic tabular or relational representation forentities - a set of entities is modelled as rows in a table. Tables represent entity classes with uniformproperties. In addition to working with entities with location as features, the system can also work withnon-spatial entities as rows in tables. The system can also model relationships between entities using propertieswhich act as primary and foreign keys. A collection of feature classes and tables, with the associatedrelationships among the entities, is a feature layer collection.FeatureLayerCollection
are one of the dataset types contained in aDatastore
.
Note
Features are not simply entitiesin a dataset. Features have a visual representation and user experience - on a map, in a 3D scene,as entities with a property sheet or popups.
Feature
- classarcgis.features.Feature(geometry=None,attributes=None)
Entities located in space with a set of properties can be represented as features.
# Obtain a feature from a feature layer:# Query a Feature Layer to get a Feature Set>>>feature_set=feature_layer.query(where="OBJECTID=1")# Assign a variable to the list of features in the Feature Set>>>feature_list=feature_set.features# Get an individual feature>>>feature=feature_list[0]# Verify the object type>>>type(feature)arcgis.features.feature.Feature# Print the string representation of the feature>>>feature{"geometry":{"x":-8238318.738276444,"y":4970309.724235498,"spatialReference":{"wkid":102100,"latestWkid":3857}},"attributes":{"Incident_Type":"Structural-Sidewalk Collapse","Location":"927 Broadway","Borough":"Manhattan","Creation_Date":1477743211000,"Closed_Date":null,"Latitude":40.7144215406227,"Longitude":-74.0060763804198,"ObjectId":1}}
- propertyas_row
Retrieves the feature as a tuple containing two lists:
List of:
Description
row values
the specific attribute values and geometry for this feature
field names
the name for each attribute field
- Returns:
A tuple of two lists: row values and field names
- propertyattributes
Get/Set the attribute values for a feature
Parameter
Description
value
Required dict.
- Returns:
A dictionary of feature attribute values with field names as the key
#Example to set attribute values>>>feat_set=feature_layer.query(where="1=1")>>>feat_list=feat_set.features>>>feat=feat_list[0]>>>feat.attributes={"field1 : "value", field2 : "value"}
- propertyfields
Retrieves the attribute field names for the feature as a list of strings
- Returns:
A list of strings
- classmethodfrom_dict(feature:str,sr:dict[str,str]|None=None)
Creates a Feature object from a dictionary.
- Returns:
- propertygeometry
Get/Set the geometry of the feature, if any.
Parameter
Description
value
Required string.Values: ‘Polyline’ | ‘Polygon’ | ‘Point’
Note
Setting this value will override the current geometry dictionaryif already present.
- Returns:
The feature’s geometry as a dictionary.
# Get the current geometry>>>feat_set=feature_layer.query(where="1=1")>>>feat_list=feat_set.features>>>feat=feat_list[0]>>>feat.geometry{'x':-8238318.738276444,'y':4970309.724235498,'spatialReference':{'wkid':102100,'latestWkid':3857}}
- propertygeometry_type
Retrieves the geometry type of the Feature as a string.
- Returns:
The geometry type of the
Feature
as a string
- get_value(field_name:str)
Retrieves the value for a specified field name.
Parameter
Description
field_name
Required String. The name for each attribute field.
Note
feature.fields
will return a list of all field names.- Returns:
The value for the specified attribute field of the
Feature
- set_value(field_name:str,value:dict|BaseGeometry|Point|MultiPoint|Polyline|Polygon)
Sets an attribute value for a given field name.
Parameter
Description
field_name
Required String. The name of the field to update.
value
Required. Value to update the field with.
- Returns:
A boolean indicating whether
field_name
value was updated (True), or not updated (False).
# Usage Example>>>feat_set=feature_layer.query(where="OBJECTID=1")>>>feat=feat_set.features[0]>>>feat.fields['OBJECTID','FID_Commun','AREA','PERIMETER','NAME','COUNTY','CONAME']>>>feat.get_value("NAME")'Original Name'>>>feat.set_value(field_name="NAME",value="New Name")True
Note
To save edits from the above snippet, use
edit_features()
withfeat_set in a list as theupdates argument.
FeatureLayer
- classarcgis.features.FeatureLayer(url,gis=None,container=None,dynamic_layer=None)
The
FeatureLayer
class is the primary concept for working withFeature
objectsin aGIS
.User
objects create, import, export, analyze, edit, and visualize features,i.e. entities in space as feature layers.Featurelayers
can be added to and visualized using maps. They act as inputs to and outputs from featureanalysis tools.Feature layers are created by publishing feature data to a GIS, and are exposed as a broader resource(
Item
) in theGIS. Feature layer objects can be obtained through the layers attribute on feature layer Items in the GIS.- append(item_id:str|None=None,upload_format:str='featureCollection',source_table_name:str|None=None,field_mappings:list[dict[str,str]]|None=None,edits:dict|None=None,source_info:dict|None=None,upsert:bool=False,skip_updates:bool=False,use_globalids:bool=False,update_geometry:bool=True,append_fields:list[str]|None=None,rollback:bool=False,skip_inserts:bool|None=None,upsert_matching_field:str|None=None,upload_id:str|None=None,layer_mappings:list[dict[str,int]]|None=None,*,return_messages:bool|None=None,future:bool=False)
The
append
method is used to update an existing hostedFeatureLayer
object.See theAppend (Feature Service/Layer)page in the ArcGIS REST API documentation for more information.Note
The
append
method is only available in ArcGIS Online and ArcGIS Enterprise 10.8.1+Note
Please reference specific deployment documentation for important information on criteria thatmust be met before appending data will work:
Parameter
Description
item_id
Optional string. The ID for the Portal item that contains the sourcefile.Used in conjunction with editsUploadFormat.
upload_format
Required string. The source append data format. Supported formatsvary by deployment and layer. See documentation for details:
Note
You can find whether append is supported on a Feature Layer,and the specific formats the layer supports by checking theproperties:
>>>featurelayer.properties.supportsAppendTrue>>>featureLayer.properties.supportedAppendFormats'sqlite,geoPackage,shapefile,filegdb,featureCollection''geojson,csv,excel,jsonl,featureService,pbf'
source_table_name
Required string. Required even when the source data contains onlyone table, e.g., for file geodatabase.
# Example usage:source_table_name="Building"
field_mappings
Optional list. Used to map source data to a destination layer.Syntax: field_mappings=[{“name” : <”targetName”>,
“sourceName” : < “sourceName”>}, …]
# Example usage:field_mappings=[{"name":"CountyID","sourceName":"GEOID10"}]
edits
Optional dictionary. Only feature collection json is supported. Appendsupports all format through the upload_id or item_id.
source_info
Optional dictionary. This is only needed when appending data fromexcel or csv. The appendSourceInfo can be the publishing parameterreturned from analyze the csv or excel file.
upsert
Optional boolean. Optional parameter specifying whether the editsneeds to be applied as updates if the feature already exists.Default is false.
skip_updates
Optional boolean. Parameter is used only when upsert is true.
use_globalids
Optional boolean. Specifying whether upsert needs to use GlobalIdwhen matching features.
update_geometry
Optional boolean. The parameter is used only when upsert is true.Skip updating the geometry and update only the attributes forexisting features if they match source features by objectId orglobalId.(as specified by useGlobalIds parameter).
append_fields
Optional list. The list of destination fields to append to. This issupported when upsert=true or false.
#Values:["fieldName1","fieldName2",....]
rollback
Optional boolean. Optional parameter specifying whether the upsertedits needs to be rolled back in case of failure. Default is false.
skip_inserts
Used only when upsert is true. Used to skip inserts if the value istrue. The default value is false.
upsert_matching_field
Optional string. The layer field to be used when matching featureswith upsert. ObjectId, GlobalId, and any other field that has aunique index can be used with upsert.This parameter overrides use_globalids; e.g., specifyingupsert_matching_field will be used even if you specifyuse_globalids = True.Example: upsert_matching_field=”MyfieldWithUniqueIndex”
upload_id
Optional string. The itemID field from an
upload()
response, corresponding withtheappendUploadId REST API argument. This argument should not beused along side theitem_id argument.layer_mappings
Optional list of dictionaries. This is needed if the source is afeature service. It is used to map a source layer to a destinationlayer. Only one source can be mapped to a layer.
Syntax: layerMappings=[{“id”: <layerID>, “sourceId”: <layer id>}]
return_messages
Optional Boolean. When set toTrue, the messages returned fromthe append will be returned. IfFalse, the response messages willnot be returned. This alters the output to be a tuple consisting ofa (Boolean, Dictionary).
future
Optional boolean.
IfTrue, method runs asynchronously and a future object will bereturned. The process will return control to the user.
IfFalse, method runs synchronously and process waits until theoperation completes before returning control back to user. This isthe default value.
- Returns:
Iffuture=False, A boolean indicating success (True), or failure (False). Whenreturn_messages isTrue, the response will return a tuple with a boolean indicatingsuccess or failure, and dictionary with the return messages.
If
future=True
, then the result is aFuture
object.Callresult()
to get the response.
# Usage Example>>>feature_layer.append(source_table_name="Building",field_mappings=[{"name":"CountyID","sourceName":"GEOID10"}],upsert=True,append_fields=["fieldName1","fieldName2",....,fieldname22],return_messages=False)<True>
- calculate(where:str,calc_expression:list[dict[str,Any]],sql_format:str='standard',version:str|None=None,sessionid:str|None=None,return_edit_moment:bool|None=None,future:bool=False)
The
calculate
operation is performed on aFeatureLayer
resource.calculate
updates the values of one or more fields in anexisting feature service layer based on SQL expressions or scalarvalues. Thecalculate
operation can only be used if thesupportsCalculate
property of the layer isTrue.Neither the Shape field nor system fields can be updated usingcalculate
. System fields includeObjectId
andGlobalId
.Inputs
Description
where
Required String. A where clause can be used to limitthe updated records. Any legal SQL where clauseoperating on the fields in the layer is allowed.
calc_expression
Required List. The array of field/value info objectsthat contain the field or fields to update and theirscalar values or SQL expression. Allowed types aredictionary and list. List must be a list ofdictionary objects.
Calculation Format is as follows:
{“field” : “<field name>”, “value” : “<value>”}
sql_format
Optional String. The SQL format for thecalc_expression. It can be either standard SQL92(standard) or native SQL (native). The default isstandard.
Values:standard,native
version
Optional String. The geodatabase version to applythe edits.
sessionid
Optional String. A parameter which is set by aclient during long transaction editing on a branchversion. The sessionid is a GUID value that clientsestablish at the beginning and use throughout theedit session.The sessionid ensures isolation during the editsession. This parameter applies only if theisDataBranchVersioned property of the layer istrue.
return_edit_moment
Optional Boolean. This parameter specifies whetherthe response will report the time edits wereapplied. If true, the server will return the timeedits were applied in the response’s edit momentkey. This parameter applies only if theisDataBranchVersioned property of the layer istrue.
future
Optional boolean. If True, a future object will bereturned and the processwill not wait for the task to complete. The default isFalse, which means wait for results.
This applies to 10.8+ only
- Returns:
- A dictionary with the following format:
{‘updatedFeatureCount’: 1,‘success’: True}
If
future=True
, then the result is aFuture
object. Callresult()
to get the response.
# Usage Example 1:print(fl.calculate(where="OBJECTID < 2",calc_expression={"field":"ZONE","value":"R1"}))
# Usage Example 2:print(fl.calculate(where="OBJECTID < 2001",calc_expression={"field":"A","sqlExpression":"B*3"}))
- propertycontainer
Get/Set the
FeatureLayerCollection
to which thislayer belongs.Parameter
Description
value
Required
FeatureLayerCollection
.- Returns:
The Feature Layer Collection where the layer is stored
- propertycontingent_values:dict[str,Any]
Returns the define contingent values for the given layer.:returns: Dict[str,Any]
- delete_features(deletes:str|None=None,where:str|None=None,geometry_filter:GeometryFilter|None=None,gdb_version:str|None=None,rollback_on_failure:bool=True,return_delete_results:bool=True,future:bool=False)
Deletes features in a
FeatureLayer
orTable
Parameter
Description
deletes
Optional string. A comma separated string of OIDs to remove from theservice.
where
Optional string. A where clause for the query filter. Any legal SQLwhere clause operating on the fields in the layer is allowed.Features conforming to the specified where clause will be deleted.
geometry_filter
Optional
SpatialFilter
. A spatial filter fromarcgis.geometry.filters module to filter results by a spatialrelationship with another geometry.gdb_version
Optional string. The geodatabase version. This parameter applies onlyif theisDataVersioned property of the layer is true.
rollback_on_failure
Optional boolean. Optional parameter to specify if the edits shouldbe applied only if all submitted edits succeed. If false, the serverwill apply the edits that succeed even if some of the submittededits fail. If true, the server will apply the edits only if alledits succeed. The default value is true.
return_delete_results
Optional Boolean. Optional parameter that indicates whether a resultis returned per deleted row when the deleteFeatures operation is run.The default is true.
future
Optional boolean. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.
- Returns:
A dictionary if future=False (default), else If
future=True
,then the result is aFuture
object. Callresult()
to get the response.
# Usage Example with only a "where" sql statement>>>fromarcgis.featuresimportFeatureLayer>>>gis=GIS("pro")>>>buck=gis.content.search("owner:"+gis.users.me.username)>>>buck_1=buck[1]>>>lay=buck_1.layers[0]>>>la_df=lay.delete_features(where="OBJECTID > 15")>>>la_df{'deleteResults':[{'objectId':1,'uniqueId':5,'globalId':None,'success':True},{'objectId':2,'uniqueId':5,'globalId':None,'success':True},{'objectId':3,'uniqueId':5,'globalId':None,'success':True},{'objectId':4,'uniqueId':5,'globalId':None,'success':True},{'objectId':5,'uniqueId':5,'globalId':None,'success':True},{'objectId':6,'uniqueId':6,'globalId':None,'success':True},{'objectId':7,'uniqueId':7,'globalId':None,'success':True},{'objectId':8,'uniqueId':8,'globalId':None,'success':True},{'objectId':9,'uniqueId':9,'globalId':None,'success':True},{'objectId':10,'uniqueId':10,'globalId':None,'success':True},{'objectId':11,'uniqueId':11,'globalId':None,'success':True},{'objectId':12,'uniqueId':12,'globalId':None,'success':True},{'objectId':13,'uniqueId':13,'globalId':None,'success':True},{'objectId':14,'uniqueId':14,'globalId':None,'success':True},{'objectId':15,'uniqueId':15,'globalId':None,'success':True}]}
- edit_features(adds:FeatureSet|list[dict]|None=None,updates:FeatureSet|list[dict]|None=None,deletes:FeatureSet|list[dict]|None=None,gdb_version:str|None=None,use_global_ids:bool=False,rollback_on_failure:bool=True,return_edit_moment:bool=False,attachments:dict[str,list[Any]]|None=None,true_curve_client:bool=False,session_id:str|None=None,use_previous_moment:bool=False,datum_transformation:int|dict[str,Any]|None=None,future:bool=False)
Adds, updates, and deletes features to theassociated
FeatureLayer
orTable
in a single call.Note
When making large number (250+ records at once) of edits,
append
should be used overedit_features
to improveperformance and ensure service stability.Inputs
Description
adds
Optional
FeatureSet
/List. The array of features to be added.updates
Optional
FeatureSet
/List. The array of features to be updated.deletes
Optional
FeatureSet
/List. string of OIDs to remove from serviceuse_global_ids
Optional boolean. Instead of referencing the default Object ID field, the servicewill look at a GUID field to track changes. This means the GUIDs will be passedinstead of OIDs for delete, update or add features.
gdb_version
Optional string. The geodatabase version to apply edits. This parameterapplies only if theisDataVersioned property of the layer is true.
rollback_on_failure
Optional boolean. Optional parameter to specify if the edits should be applied onlyif all submitted edits succeed. If false, the server will apply the edits that succeedeven if some of the submitted edits fail. If true, the server will apply the editsonly if all edits succeed. The default value is true.
return_edit_moment
Optional boolean. Introduced at 10.5, only applicable with ArcGIS Server servicesonly. Specifies whether the response will report the time edits were applied. If setto true, the server will return the time in the response’s editMoment key. The defaultvalue is false.
attachments
Optional Dict. This parameter adds, updates, or deletes attachments. It applies onlywhen theuse_global_ids parameter is set to true. For adds, the globalIds of theattachments provided by the client are preserved. When useGlobalIds is true, updatesand deletes are identified by each feature or attachment globalId, rather than theirobjectId or attachmentId. This parameter requires the layer’ssupportsApplyEditsWithGlobalIds property to be true.
Attachments to be added or updated can use either pre-uploaded data or base 64encoded data.
Inputs
Inputs
Description
adds
List of attachments to add.
updates
List of attachments to update
deletes
List of attachments to delete
See theApply Edits to a Feature Service layerin the ArcGIS REST API for more information.
true_curve_client
Optional boolean. Introduced at 10.5. Indicates to the server whether the client istrue curve capable. When set to true, this indicates to the server that true curvegeometries should be downloaded and that geometries containing true curves should beconsumed by the map service without densifying it. When set to false, this indicatesto the server that the client is not true curves capable. The default value is false.
session_id
Optional String. Introduced at 10.6. Thesession_id is a GUID value that clientsestablish at the beginning and use throughout the edit session. The sessionID ensuresisolation during the edit session. Thesession_id parameter is set by a clientduring long transaction editing on a branch version.
use_previous_moment
Optional Boolean. Introduced at 10.6. Theuse_previous_moment parameter is used toapply the edits with the same edit moment as the previous set of edits. This allows aneditor to apply single block of edits partially, complete another task and thencomplete the block of edits. This parameter is set by a client during long transactionediting on a branch version.
When set to true, the edits are applied with the same edit moment as the previous setof edits. When set to false or not set (default) the edits are applied with a newedit moment.
datum_transformation
Optional Integer/Dictionary. This parameter applies a datum transformation whileprojecting geometries in the results when out_sr is different than the layer’s spatialreference. When specifying transformations, you need to think about which datumtransformation best projects the layer (not the feature service) to theoutSR andsourceSpatialReference property in the layer properties. For a list of valid datumtransformation ID values ad well-known text strings, seeUsing spatial references.For more information on datum transformations please see the transformationparameter in theProject operation documentation.
Examples
Inputs
Description
WKID
Integer. Ex: datum_transformation=4326
WKT
Dict. Ex: datum_transformation={“wkt”: “<WKT>”}
Composite
Dict. Ex: datum_transformation=```{‘geoTransforms’:[{‘wkid’:<id>,’forward’:<true|false>},{‘wkt’:’<WKT>’,’forward’:<True|False>}]}```
future
Optional Boolean. If theFeatureLayer hassupportsAsyncApplyEdits settoTrue, then edits can be applied asynchronously. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.
- Returns:
A dictionary by default, or If
future=True
, then the result is aFuture
object. Callresult()
to get the response.The dictionary will contain keys “addResults”, “updateResults”, “deleteResults”, and “attachments” with the results of the operation.
# Usage Example 1:feature=[{'attributes':{'ObjectId':1,'UpdateDate':datetime.datetime.now(),}}]lyr.edit_features(updates=feature)>>>{'addResults':[],'updateResults':[{'objectId':1,'success':True}]},'deleteResults':[],}
# Usage Example 2:adds={"geometry":{"x":500,"y":500,"spatialReference":{"wkid":102100,"latestWkid":3857}},"attributes":{"ADMIN_NAME":"Fake Location"}}lyr.edit_features(adds=[adds])>>>{'addResults':[{'objectId':2542,'success':True}],'updateResults':[],'deleteResults':[],}
# Usage Example 3:lyr.edit_features(deletes=[2542])>>>{'addResults':[],'updateResults':[],'deleteResults':[{'objectId':2542,'success':True}],}
- propertyestimates:dict[str,Any]
Returns up-to-date approximations of layer information, such as row countand extent. Layers that support this property will includeinfoInEstimates information in the layer’s
properties
.Currently available with ArcGIS Online and Enterprise 10.9.1+
- Returns:
Dict[str, Any]
- export_attachments(output_folder:str,label_field:str|None=None)
Exports attachments from the
FeatureLayer
in Imagenetformat using theoutput_label_field
.Parameter
Description
output_folder
Required string. Output folder where the attachments will be stored.If None, a default folder is created
label_field
Optional string. Field which contains the label/category of each feature.
- Returns:
Nothing is returned from this method
- propertyfield_groups:dict[str,Any]
Returns the defined list of field groups for a given layer.
- Returns:
dict[str,Any]
- classmethodfromitem(item:Item,layer_id:int=0)
The
fromitem
method creates aFeatureLayer
from anItem
object.Parameter
Description
item
Required
Item
object. The type of item should be aFeatureService
that represents aFeatureLayerCollection
layer_id
Required Integer. the id of the layer in feature layer collection (feature service).The default for
layer_id
is 0.- Returns:
A
FeatureSet
object
# Usage Example>>>fromarcgis.featuresimportFeatureLayer>>>gis=GIS("pro")>>>buck=gis.content.search("owner:"+gis.users.me.username)>>>buck_1=buck[1]>>>buck_1.type'Feature Service'>>>new_layer=FeatureLayer.fromitem(item=buck_1)>>>type(new_layer)<class'arcgis.features.layer.FeatureLayer'>
- generate_renderer(definition:dict,where:str|None=None)
Groups data using the supplied definition (classification definition) and an optional where clause. Theresult is a renderer object.
Note
Use baseSymbol and colorRamp to definethe symbols assigned to each class. If the operation is performedon a table, the result is a renderer object containing the dataclasses and no symbols.
Parameter
Description
definition
Required dict. The definition using the renderer that is generated.Use either class breaks or unique value classification definitions.SeeClassification Objects for additional details.
where
Optional string. A where clause for which the data needs to beclassified. Any legal SQL where clause operating on the fields inthe dynamic layer/table is allowed.
- Returns:
A JSON Dictionary
# Example UsageFeatureLayer.generate_renderer(definition={"type":"uniqueValueDef","uniqueValueFields":["Has_Pool"],"fieldDelimiter":",","baseSymbol":{"type":"esriSFS","style":"esriSLSSolid","width":2},"colorRamp":{"type":"algorithmic","fromColor":[115,76,0,255],"toColor":[255,25,86,255],"algorithm":"esriHSVAlgorithm"}},where="POP2000 > 350000")
- get_html_popup(oid:str|None)
The
get_html_popup
method provides details about the HTML pop-upauthored by theUser
using ArcGIS Pro or ArcGIS Desktop.Parameter
Description
oid
Optional string. Object id of the feature to get the HTML popup.
- Returns:
A string
- get_unique_values(attribute:str,query_string:str='1=1')
Retrieves a list of unique values for a given attribute in the
FeatureLayer
.Parameter
Description
attribute
Required string. The feature layer attribute to query.
query_string
Optional string. SQL Query that will be used to filter attributesbefore unique values are returned.ex. “name_2 like ‘%K%’”
- Returns:
A list of unique values
# Usage Example with only a "where" sql statement>>>fromarcgis.featuresimportFeatureLayer>>>gis=GIS("pro")>>>buck=gis.content.search("owner:"+gis.users.me.username)>>>buck_1=buck[1]>>>lay=buck_1.layers[0]>>>layer=lay.get_unique_values(attribute="COUNTY")>>>layer['PITKIN','PLATTE','TWIN FALLS']
- propertymanager
The
manager
property is a helper object to manage theFeatureLayer
, such asupdating its definition.- Returns:
# Usage Example>>>manager=FeatureLayer.manager
- propertymetadata
Get the Feature Layer’s metadata.
Note
If metadata is disabled on the GIS or thelayer does not support metadata,
None
will be returned.- Returns:
String of the metadata, if any
- query(where:str='1=1',out_fields:str|list[str]='*',time_filter:list[datetime]|None=None,geometry_filter:GeometryFilter|None=None,return_geometry:bool=True,return_count_only:bool=False,return_ids_only:bool=False,return_distinct_values:bool=False,return_extent_only:bool=False,group_by_fields_for_statistics:str|None=None,statistic_filter:StatisticFilter|None=None,result_offset:int|None=None,result_record_count:int|None=None,object_ids:list[str]|None=None,distance:int|None=None,units:str|None=None,max_allowable_offset:int|None=None,out_sr:dict[str,int]|str|None=None,geometry_precision:int|None=None,gdb_version:str|None=None,order_by_fields:str|None=None,out_statistics:list[dict[str,Any]]|None=None,return_z:bool=False,return_m:bool=False,multipatch_option:tuple=None,quantization_parameters:dict[str,Any]|None=None,return_centroid:bool=False,return_all_records:bool=True,result_type:str|None=None,historic_moment:int|datetime|None=None,sql_format:str|None=None,return_true_curves:bool=False,return_exceeded_limit_features:bool|None=None,as_df:bool=False,datum_transformation:int|dict[str,Any]|None=None,time_reference_unknown_client:bool|None=None,**kwargs)
The
query
method queries aFeatureLayer
based on asql
statement.Parameter
Description
where
Optional string. SQL-92 WHERE clause syntax on the fields in the layeris supported for most data sources. Some data sources have restrictionson what is supported. Hosted feature services in ArcGIS Enterprise runningon a spatiotemporal data source only support a subset of SQL-92.Below is a list of supported SQL-92 with spatiotemporal-based feature services:
( ‘<=’ | ‘>=’ | ‘<’ | ‘>’ | ‘=’ | ‘!=’ | ‘<>’ | LIKE )(AND | OR)(IS | IS_NOT)(IN | NOT_IN) ( ‘(’ ( expr ( ‘,’ expr )* )? ‘)’ )COLUMN_NAME BETWEEN LITERAL_VALUE AND LITERAL_VALUE
out_fields
Optional list of fields to be included in the returned result set.This list is a comma-delimited list of field names. You can also specifythe wildcard “*” as the value of this parameter. In this case, the queryresults include all the field values.
Note
If specifyingreturn_count_only,return_id_only, orreturn_extent_onlyas True, do not specify this parameter in order to avoid errors.
object_ids
Optional string. The object IDs of this layer or table to be queried.The object ID values should be a comma-separated string.
Note
There might be a drop in performance if the layer/table datasource resides in an enterprise geodatabase and more than1,000 object_ids are specified.
distance
Optional integer. The buffer distance for the input geometries.The distance unit is specified by units. For example, if thedistance is 100, the query geometry is a point, units is set tometers, and all points within 100 meters of the point are returned.
units
Optional string. The unit for calculating the buffer distance. Ifunit is not specified, the unit is derived from the geometry spatialreference. If the geometry spatial reference is not specified, theunit is derived from the feature service data spatial reference.This parameter only applies ifsupportsQueryWithDistance is true.
- Values:`esriSRUnit_Meter | esriSRUnit_StatuteMile |
esriSRUnit_Foot | esriSRUnit_Kilometer |esriSRUnit_NauticalMile | esriSRUnit_USNauticalMile`
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp inmilliseconds
geometry_filter
Optional from
filters
. Allows for the information tobe filtered on spatial relationship with another geometry.max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation.The max_allowable_offset is in the units of out_sr. If out_sr is notspecified, max_allowable_offset is assumed to be in the unit of thespatial reference of the layer.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
geometry_precision
Optional Integer. This option can be used to specify the number ofdecimal places in the response geometries returned by the queryoperation.This applies to X and Y values only (not m or z-values).
gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer is true.If this is not specified, the query will apply to the publishedmap’s version.
return_geometry
Optional boolean. If true, geometry is returned with the query.Default is true.
return_distinct_values
Optional boolean. If true, it returns distinct values based on thefields specified in out_fields. This parameter applies only if thesupportsAdvancedQueries property of the layer is true. This parametercan be used with return_count_only to return the count of distinctvalues of subfields.
Note
Make sure to set return_geometry to False if this is set to True.Otherwise, reliable results will not be returned.
return_ids_only
Optional boolean. Default is False. If true, the response onlyincludes an array of object IDs. Otherwise, the response is afeature set. When object_ids are specified, setting this parameter totrue is invalid.
return_count_only
Optional boolean. If true, the response only includes the count(number of features/records) that would be returned by a query.Otherwise, the response is a feature set. The default is false. Thisoption supersedes the returnIdsOnly parameter. IfreturnCountOnly = true, the response will return both the count andthe extent.
return_extent_only
Optional boolean. If true, the response only includes the extent ofthe features that would be returned by the query. IfreturnCountOnly=true, the response will return both the count andthe extent.The default is false. This parameter applies only if thesupportsReturningQueryExtent property of the layer is true.
order_by_fields
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
Note
If specifyingreturn_count_only,return_id_only, orreturn_extent_onlyas True, do not specify this parameter in order to avoid errors.
group_by_fields_for_statistics
Optional string. One or more field names on which the values need tobe grouped for calculating the statistics.example: STATE_NAME, GENDER
out_statistics
Optional list of dictionaries. The definitions for one or more field-basedstatistics to be calculated.
Syntax:
- [
- {
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field1”,“outStatisticFieldName”: “Out_Field_Name1”
},{
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field2”,“outStatisticFieldName”: “Out_Field_Name2”
}
]
statistic_filter
Optional
StatisticFilter
instance. The definitions for one or more field-basedstatistics can be added, e.g. statisticType, onStatisticField, oroutStatisticFieldName.Syntax:
sf = StatisticFilter()sf.add(statisticType=”count”, onStatisticField=”1”, outStatisticFieldName=”total”)sf.filter
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is False.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
multipatch_option
Optional x/y footprint. This option dictates how the geometry ofa multipatch feature will be returned.
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th). This option is ignoredif return_all_records is True (i.e. by default).This parameter cannot be specified if the service does not support pagination.
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property. This option is ignored ifreturn_all_records is True (i.e. by default).
quantization_parameters
Optional dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
return_centroid
Optional boolean. Used to return the geometry centroid associatedwith each feature returned. If true, the result includes the geometrycentroid. The default is false. Only supported on layer withpolygon geometry type.
return_all_records
Optional boolean. When True, the query operation will call theservice until all records that satisfy the where_clause arereturned. Note: result_offset and result_record_count will beignored if return_all_records is True. Also, if return_count_only,return_ids_only, or return_extent_only are True, this parameterwill be ignored. If this parameter is set to False but no other limit isspecified, the default is True.
result_type
Optional string. The result_type parameter can be used to controlthe number of features returned by the query operation.Values: None | standard | tile
historic_moment
Optional integer. The historic moment to query. This parameterapplies only if the layer is archiving enabled and thesupportsQueryWithHistoricMoment property is set to true. Thisproperty is provided in the layer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values: none | standard | native
return_true_curves
Optional boolean. When set to true, returns true curves in outputgeometries. When set to false, curves are converted to densifiedpolylines or polygons.
return_exceeded_limit_features
Optional boolean. Optional parameter which is true by default. Whenset to true, features are returned even when the results include‘exceededTransferLimit’: True.
When set to false and querying with resultType = tile features arenot returned when the results include ‘exceededTransferLimit’: True.This allows a client to find the resolution in which the transferlimit is no longer exceeded without making multiple calls.
as_df
Optional boolean. If True, the results are returned as a DataFrameinstead of a FeatureSet.
datum_transformation
Optional Integer/Dictionary. This parameter applies a datum transformation whileprojecting geometries in the results when out_sr is different than the layer’s spatialreference. When specifying transformations, you need to think about which datumtransformation best projects the layer (not the feature service) to theoutSR andsourceSpatialReference property in the layer properties. For a list of valid datumtransformation ID values ad well-known text strings, seeCoordinate systems andtransformations.For more information on datum transformations, please see the transformationparameter in theProject operation.
Examples
Inputs
Description
WKID
Integer. Ex: datum_transformation=4326
WKT
Dict. Ex: datum_transformation={“wkt”: “<WKT>”}
Composite
Dict. Ex: datum_transformation=```{‘geoTransforms’:[{‘wkid’:<id>,’forward’:<true|false>},{‘wkt’:’<WKT>’,’forward’:<True|False>}]}```
kwargs
Optional dict. Optional parameters that can be passed to the Queryfunction. This will allow users to pass additional parameters notexplicitly implemented on the function. A complete list of functionsavailable is documented on the Query REST API.
- Returns:
A
FeatureSet
containing the features matching the query unless another return typeis specified, such asreturn_count_only
,return_extent_only
, orreturn_ids_only
.
# Usage Example with only a "where" sql statement>>>feat_set=feature_layer.query(where="OBJECTID= 1")>>>type(feat_set)<arcgis.Features.FeatureSet>>>>feat_set[0]<Feature1>
# Usage Example of an advanced query returning the object IDs instead of Features>>>id_set=feature_layer.query(where="OBJECTID1",out_fields=["FieldName1, FieldName2"],distance=100,units='esriSRUnit_Meter',return_ids_only=True)>>>type(id_set)<Array>>>>id_set[0]<"Item_id1">
# Usage Example of an advanced query returning the number of features in the query>>>search_count=feature_layer.query(where="OBJECTID1",out_fields=["FieldName1, FieldName2"],distance=100,units='esriSRUnit_Meter',return_count_only=True)>>>type(search_count)<Integer>>>>search_count<149>
# Usage Example with "out_statistics" parameter>>>stats=[{'onStatisticField':"1",'outStatisticFieldName':"total",'statisticType':"count"}]>>>feature_layer.query(out_statistics=stats,as_df=True)# returns a DataFrame containing total count
# Usage Example with "StatisticFilter" parameter>>>fromarcgis._impl.common._filtersimportStatisticFilter>>>sf1=StatisticFilter()>>>sf1.add(statisticType="count",onStatisticField="1",outStatisticFieldName="total")>>>sf1.filter# This is to print the filter content>>>feature_layer.query(statistic_filter=sf1,as_df=True)# returns a DataFrame containing total count
- query_3d(where:str|None=None,out_fields:str|None=None,object_ids:str|None=None,distance:int|None=None,units:str|None=None,time_filter:str|int|None=None,geometry_filter:Geometry|dict|None=None,gdb_version:str|None=None,return_distinct_values:bool|None=None,order_by_fields:str|None=None,group_by_fields_for_statistics:str|None=None,out_statistics:list[dict]|None=None,result_offset:int|None=None,result_record_count:int|None=None,historic_moment:int|None=None,sql_format:str|None=None,format_3d_objects:str|None=None,time_reference_unknown_client:bool|None=None)
The query3D operation allows clients to query 3D object features and isbased on the feature service layer query operation. The 3D object featurelayer still supports layer and service level feature service query operations.
Parameter
Description
where
Optional string. SQL-92 WHERE clause syntax on the fields in the layeris supported for most data sources. Some data sources have restrictionson what is supported. Hosted feature services in ArcGIS Enterprise runningon a spatiotemporal data source only support a subset of SQL-92.Below is a list of supported SQL-92 with spatiotemporal-based feature services:
( ‘<=’ | ‘>=’ | ‘<’ | ‘>’ | ‘=’ | ‘!=’ | ‘<>’ | LIKE )(AND | OR)(IS | IS_NOT)(IN | NOT_IN) ( ‘(’ ( expr ( ‘,’ expr )* )? ‘)’ )COLUMN_NAME BETWEEN LITERAL_VALUE AND LITERAL_VALUE
out_fields
Optional list of fields to be included in the returned result set.This list is a comma-delimited list of field names. You can also specifythe wildcard “*” as the value of this parameter to return allfields in the result.
object_ids
Optional string. The object IDs of this layer or table to be queried.The object ID values should be a comma-separated string.
Note
There might be a drop in performance if the layer/table datasource resides in an enterprise geodatabase and more than1,000 object_ids are specified.
distance
Optional integer. The buffer distance for the input geometries.The distance unit is specified by units. For example, if thedistance is 100, the query geometry is a point, units is set tometers, and all points within 100 meters of the point are returned.
units
Optional string. The unit for calculating the buffer distance. Ifunit is not specified, the unit is derived from the geometry spatialreference. If the geometry spatial reference is not specified, theunit is derived from the feature service data spatial reference.This parameter only applies ifsupportsQueryWithDistance is true.
- Values:`esriSRUnit_Meter | esriSRUnit_StatuteMile |
esriSRUnit_Foot | esriSRUnit_Kilometer |esriSRUnit_NauticalMile | esriSRUnit_USNauticalMile`
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp inmilliseconds
geometry_filter
Optional from
filters
. Allows for the information tobe filtered on spatial relationship with another geometry.gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer is true.If this is not specified, the query will apply to the publishedmap’s version.
return_distinct_values
Optional boolean. If true, it returns distinct values based on thefields specified in out_fields. This parameter applies only if thesupportsAdvancedQueries property of the layer is true. This parametercan be used with return_count_only to return the count of distinctvalues of subfields.
Note
Make sure to set return_geometry to False if this is set to True.Otherwise, reliable results will not be returned.
order_by_fields
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
Note
If specifyingreturn_count_only,return_id_only, orreturn_extent_onlyas True, do not specify this parameter in order to avoid errors.
group_by_fields_for_statistics
Optional string. One or more field names on which the values need tobe grouped for calculating the statistics.example: STATE_NAME, GENDER
out_statistics
Optional list of dictionaries. The definitions for one or more field-basedstatistics to be calculated.
Syntax:
- [
- {
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field1”,“outStatisticFieldName”: “Out_Field_Name1”
},{
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field2”,“outStatisticFieldName”: “Out_Field_Name2”
}
]
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th). This option is ignoredif return_all_records is True (i.e. by default).
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property. This option is ignored ifreturn_all_records is True (i.e. by default).
historic_moment
Optional integer. The historic moment to query. This parameterapplies only if the layer is archiving enabled and thesupportsQueryWithHistoricMoment property is set to true. Thisproperty is provided in the layer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values: none | standard | native
format_3d_objects
Optional string. Specifies the 3D format that will be used to requesta feature. If set to a valid format ID (see layer resource), the geometryof the feature response will be a 3D envelope of the 3D object and willinclude asset maps for the 3D object. Since formats are created asynchronously,review the flags field in the asset map to determine if the format is available(conversionStatus is COMPLETED). If conversionStatus is INPROGRESS, the formatis not ready. Request the feature again later.
If a feature does not have the specified format, the feature will still be returnedaccording to the query parameters (such as the where clause), but theasset mapping will be missing.
Values: “3D_dae” | “3D_dwg” | “3D_fbx” | “3D_glb” | “3D_gltf” | “3D_ifc”| “3D_obj” | “3D_shapebuffer” | “3D_shapebufferg” | “3D_usdc” | “3D_usdz”
time_reference_unknown_client
Optional boolean. Settingtime_reference_unknown_client as Trueindicates that the client is capable of working with data values thatare not in UTC. If its not set to true, and the service layer’sdatesInUnknownTimeZone property is true, then an error is returned.The default is False
Its possible to define a service’s time zone of date fields as unknown.Setting the time zone as unknown means that date values will be returnedas-is from the database, rather than as date values in UTC. Non-hostedfeature services can be set to use an unknown time zone usingArcGIS Server Manager. Setting the time zones to unknown alsosets the datesInUnknownTimeZone layer property as true. Currently,hosted feature services do not support this setting. This setting doesnot apply to editor tracking date fields which are stored and returnedin UTC even when the time zone is set to unknown.
Most clients released prior to ArcGIS Enterprise 10.9 will not be ableto work with feature services that have an unknown time setting.
- Returns:
A dictionary containing the feature, asset map, and asset information for the layer.
USAGEEXAMPLE:Query3Dobjects# Import the required modulesfromarcgis.gisimportGISfromarcgis.featuresimportFeatureLayer# Connect to your GISgis=GIS(profile="your_enterprise_profile")# Search for the feature layersearch_result=gis.content.search("3D Object Feature Layer","Feature Layer")feature_layer=search_result[0]# Create a FeatureLayer objectlayer=FeatureLayer(feature_layer.url,gis)# Query the 3D objectsresult=layer.query_3d(where="OBJECTID < 10",out_fields="*",format_3d_objects="3D_dae")print(result)
- query_analytics(out_analytics:list[dict],where:str='1=1',out_fields:str|list[str]='*',analytic_where:str|None=None,geometry_filter:GeometryFilter|None=None,out_sr:dict[str,int]|str|None=None,return_geometry:bool=True,order_by:str|None=None,result_type:str|None=None,cache_hint:str|None=None,result_offset:int|None=None,result_record_count:int|None=None,quantization_param:dict[str,Any]|None=None,sql_format:str|None=None,future:bool=True,**kwargs)
The
query_analytics
exposes the standardSQL
windows functions that computeaggregate and ranking values based on a group of rows called windowpartition. The window function is applied to the rows after thepartitioning and ordering of the rows.query_analytics
defines awindow or user-specified set of rows within a query result set.query_analytics
can be used to compute aggregated values such as movingaverages, cumulative aggregates, or running totals.Note
See the
query
method for a similar function.SQL Windows Function
A window function performs a calculation across a set of rows (SQL partitionor window) that are related to the current row. Unlike regular aggregatefunctions, use of a window function does not return single output row. Therows retain their separate identities with each calculation appended to therows as a new field value. The window function can access more than justthe current row of the query result.
query_analytics
currently supports the following windows functions:Aggregate functions
Analytic functions
Ranking functions
Aggregate Functions
Aggregate functions are deterministic function that perform a calculation ona set of values and return a single value. They are used in the select listwith optional HAVING clause. GROUP BY clause can also be used to calculatethe aggregation on categories of rows.
query_analytics
can be used tocalculate the aggregation on a specific range of value. Supported aggregatefunctions are:Min
Max
Sum
Count
AVG
STDDEV
VAR
Analytic Functions
Several analytic functions available now in all SQL vendors to compute anaggregate value based on a group of rows or windows partition. Unlikeaggregation functions, analytic functions can return single or multiple rowsfor each group.
CUM_DIST
FIRST_VALUE
LAST_VALUE
LEAD
LAG
PERCENTILE_DISC
PERCENTILE_CONT
PERCENT_RANK
Ranking Functions
Ranking functions return a ranking value for each row in a partition. Dependingon the function that is used, some rows might receive the same value as other rows.
RANK
NTILE
DENSE_RANK
ROW_NUMBER
Partitioning
Partitions are extremely useful when you need to calculate the same metric overdifferent group of rows. It is very powerful and has many potential usages. Forexample, you can add partition by to your window specification to look atdifferent groups of rows individually.
partitionBy
clause divides the query result set into partitions and the sqlwindow function is applied to each partition.The ‘partitionBy’ clause normally refers to the column by which the result ispartitioned. ‘partitionBy’ can also be a value expression (column expression orfunction) that references any of the selected columns (not aliases).Parameter
Description
out_analytics
Required List. A set of analytics to calculate on the Feature Layer.
The definitions for one or more field-based or expression analyticsto be computed. This parameter is supported only on layers/tables thatreturntrue forsupportsAnalytics property.
Note
IfoutAnalyticFieldName is empty or missing, the server assignsa field name to the returned analytic field.
The argument should be a list of dictionaries that define analystics.An analytic definition specifies:
the type of analytic - key:analyticType
the field or expression on which it is to be computed - key:onAnalyticField
the resulting output field name -key:outAnalyticFieldName
the analytic specifications -analysticParameters
SeeOverviewfor details.
# Dictionary structure and options for this parameter[{"analyticType":"<COUNT | SUM | MIN | MAX | AVG | STDDEV | VAR | FIRST_VALUE, LAST_VALUE, LAG, LEAD, PERCENTILE_CONT, PERCENTILE_DISC, PERCENT_RANK, RANK, NTILE, DENSE_RANK, EXPRESSION>","onAnalyticField":"Field1","outAnalyticFieldName":"Out_Field_Name1","analyticParameters":{"orderBy":"<orderBy expression","value":<doublevalue>,//percentilevalue"partitionBy":"<field name or expression>","offset":<integer>,//usedbyLAG/LEAD"windowFrame":{"type":"ROWS"|"RANGE","extent":{"extentType":"PRECEDING"|"BOUNDARY","PRECEDING":{"type":<"UNBOUNDED"|"NUMERIC_CONSTANT"|"CURRENT_ROW">"value":<numericconstantvalue>}"BOUNDARY":{"start":"UNBOUNDED_PRECEDING","NUMERIC_PRECEDING","CURRENT_ROW","startValue":<numericconstantvalue>,"end":<"UNBOUNDED_FOLLOWING"|"NUMERIC_FOLLOWING"|"CURRENT_ROW","endValue":<numericconstantvalue>}}}}}}]
# Usage Example:>>>out_analytics=[{"analyticType":"FIRST_VALUE","onAnalyticField":"POP1990","analyticParameters":{"orderBy":"POP1990","partitionBy":"state_name"},"outAnalyticFieldName":"FirstValue"}]
where
Optional string. The default is 1=1. The selection sql statement.
out_fields
Optional List of field names to return. Field names can be specifiedeither as a List of field names or as a comma separated string.The default is “*”, which returns all the fields.
analytic_where
Optional String. A where clause for the query filter that applies tothe result set of applying the source where clause and all other params.
geometry_filter
Optional from arcgis.geometry.filter. Allows for the information tobe filtered on spatial relationship with another geometry.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
return_geometry
Optional boolean. If true, geometry is returned with the query.Default is true.
order_by
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
result_type
Optional string. The result_type parameter can be used to controlthe number of features returned by the query operation.Values: None | standard | tile
cache_hint
Optional Boolean. If you are performing the same query multiple times,a user can ask the server to cache the call to obtain the resultsquicker. The default isFalse.
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th).
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property.
quantization_parameters
Optional dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values:none | standard | native
future
Optional Boolean. This determines if aFuture object is returned(True) the method returns the results directly (False).
- Returns:
A Pandas DataFrame (pd.DataFrame)
- query_date_bins(bin_field:str|datetime,bin_specs:dict,out_statistics:list[dict[str,Any]],time_filter:TimeFilter|None=None,geometry_filter:GeometryFilter|dict|None=None,bin_order:str|None=None,where:str|None=None,return_centroid:bool|None=False,in_sr:int|dict[str,Any]|None=None,out_sr:int|dict[str,Any]|None=None,spatial_rel:str|None=None,quantization_params:dict[str,Any]|None=None,result_offset:int|None=None,result_record_count:int|None=None,return_exceeded_limit_features:bool|None=False)
The
query_date_bins
operation is performed on aFeatureLayer
.This operation returns a histogram of features divided into bins based on a date field.The response can include statistical aggregations for each bin, such as a count orsum, and may also include the aggregate geometries (in other words, centroid) forpoint layers.The parameters define the bins, the aggregate information returned, and the includedfeatures. Bins are defined using the bin parameter. The
out_statistics
andreturn_centroid
parameters define the information each bin will provide. Includedfeatures can be specified by providing atime
extent,where
condition, and aspatial filter, similar to a query operation.The contents of the
bin_specs
parameter provide flexibility for defining binboundaries. Thebin_specs
parameter’sunit
property defines the time width of eachbin, such as one year, quarter, month, day, or hour. Fixed bins can use multiple units forthese time widths. Theresult_offset
property defines an offset within that time unit.For example, if your bin unit isday
, and you want bin boundaries to go from noon tonoon on the next day, the offset would be 12 hours.Features can be manipulated with the
time_filter
,where
, andgeometry_filter
parameters. By default, the result will expand to fit the feature’s earliest and latestpoint of time. Thetime_filter
parameter defines a fixed starting point and endingpoint of the features based on the field used in binField. Thewhere
andgeometry_filter
parameters allow additional filters to be put on the data.This operation is only supported on feature services using a spatiotemporal datastore. As well, the service property
supportsQueryDateBins
must be set to true.To use pagination with aggregated queries on hosted feature services in ArcGISEnterprise, the
supportsPaginationOnAggregatedQueries
property must betrue
onthe layer. Hosted feature services using a spatiotemporal data store do not currentlysupport pagination on aggregated queries.Parameter
Description
bin_field
Required String. The date field used to determine which bin eachfeature falls into.
bin_specs
Required Dict. A dictionary that describes the characteristics ofbins, such as the size of the bin and its starting position. Thesize of each bin is determined by the number of time units denotedby the
number
andunit
properties.The starting position of the bin is the earliest moment in thespecified unit. For example, each year begins at midnight of January1. An offset inside the bin parameter can provide an offset to thestarting position of the bin. This can contain a positive ornegative integer value.
A bin can take two forms: either a calendar bin or a fixed bin. Acalendar bin is aware of calendar-specific adjustments, such asdaylight saving time and leap seconds. Fixed bins are, by contrast,always a specific unit of measurement (for example, 60 seconds in aminute, 24 hours in a day) regardless of where the date and time ofthe bin starts. For this reason, some calendar-specific units areonly supported as calendar bins.
# Calendar bin>>>bin_specs={"calendarBin":{"unit":"year","timezone":"US/Arizona","offset":{"number":5,"unit":"hour"}}}# Fixed bin>>>bin_specs={"fixedBin":{"number":12,"unit":"hour","offset":{"number":5,"unit":"hour"}}}
out_statistics
Required List of Dicts. The definitions for one or more field-basedstatistics to be calculated:
{"statisticType":"<count | sum | min | max | avg | stddev | var>","onStatisticField":"Field1","outStatisticFieldName":"Out_Field_Name1"}
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.
geometry_filter
Optional from
filters
. Allows for theinformation to be filtered on spatial relationship with anothergeometry.bin_order
Optional String. Either “ASC” or “DESC”. Determines whether resultsare returned in ascending or descending order. Default is ascending.
where
Optional String. A WHERE clause for the query filter. SQL ‘92 WHEREclause syntax on the fields in the layer is supported for most datasources.
return_centroid
Optional Boolean. Returns the geometry centroid associated with allthe features in the bin. If true, the result includes the geometrycentroid. The default is false. This parameter is only supported onpoint data.
in_sr
Optional Integer. The WKID for the spatial reference of the inputgeometry.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
spatial_rel
Optional String. The spatial relationship to be applied to the inputgeometry while performing the query. The supported spatialrelationships include intersects, contains, envelop intersects,within, and so on. The default spatial relationship is intersects(
esriSpatialRelIntersects
). Other options areesriSpatialRelContains
,esriSpatialRelCrosses
,esriSpatialRelEnvelopeIntersects
,esriSpatialRelIndexIntersects
,esriSpatialRelOverlaps
,esriSpatialRelTouches
, andesriSpatialRelWithin
.quantization_params
Optional Dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
# upperLeft origin position{"mode":"view","originPosition":"upperLeft","tolerance":1.0583354500042335,"extent":{"type":"extent","xmin":-18341377.47954369,"ymin":2979920.6113554947,"xmax":-7546517.393554582,"ymax":11203512.89298139,"spatialReference":{"wkid":102100,"latestWkid":3857}}}# lowerLeft origin position{"mode":"view","originPosition":"lowerLeft","tolerance":1.0583354500042335,"extent":{"type":"extent","xmin":-18341377.47954369,"ymin":2979920.6113554947,"xmax":-7546517.393554582,"ymax":11203512.89298139,"spatialReference":{"wkid":102100,"latestWkid":3857}}}
SeeQuantization parameters JSON propertiesfor details on format of this parameter.
Note
This parameter only applies if the layer’s
supportsCoordinateQuantization
property istrue
.result_offset
Optional Int. This parameter fetches query results by skipping thespecified number of records and starting from the next record. Thedefault is 0.
- Note:
This parameter only applies if the layer’s
supportsPagination
property istrue
.
result_record_count
Optional Int. This parameter fetches query results up to the valuespecified. When
result_offset
is specified, but this parameteris not, the map service defaults to the layer’smaxRecordCount
property. The maximum value for this parameter is the value of themaxRecordCount
property. The minimum value entered for thisparameter cannot be below 1.- Note:
This parameter only applies if the layer’s
supportsPagination
property istrue
.
return_exceeded_limit_features
Optional Boolean. When set to
True
, features are returned evenwhen the results include"exceededTransferLimit":true
. Thisallows a client to find the resolution in which the transfer limitis no longer exceeded without making multiple calls. The defaultvalue isFalse
.- Returns:
A Dict containing the resulting features and fields.
# Usage Example>>>flyr_item=gis.content.search("*","Feature Layer")[0]>>>flyr=flyr_item.layers[0]>>>qy_result=flyr.query_date_bins(bin_field="boundary",bin_specs={"calendarBin":{"unit":"day","timezone":"America/Los_Angeles","offset":{"number":8,"unit":"hour"}}},out_statistics=[{"statisticType":"count","onStatisticField":"objectid","outStatisticFieldName":"item_sold_count"},{"statisticType":"avg","onStatisticField":"price","outStatisticFieldName":"avg_daily_revenue "}],time=[1609516800000,1612195199999])>>>qy_result{"features":[{"attributes":{"boundary":1609516800000,"avg_daily_revenue":300.40,"item_sold_count":79}},{"attributes":{"boundary":1612108800000,"avg_daily_revenue":null,"item_sold_count":0}}],"fields":[{"name":"boundary","type":"esriFieldTypeDate"},{"name":"item_sold_count","alias":"item_sold_count","type":"esriFieldTypeInteger"},{"name":"avg_daily_revenue","alias":"avg_daily_revenue","type":"esriFieldTypeDouble"}],"exceededTransferLimit":false}
- query_related_records(object_ids:str,relationship_id:str,out_fields:str='*',definition_expression:str|None=None,return_geometry:bool=True,max_allowable_offset:float|None=None,geometry_precision:int|None=None,out_wkid:int|None=None,gdb_version:str|None=None,return_z:bool=False,return_m:bool=False,historic_moment:int|datetime|None=None,return_true_curve:bool=False)
The
query_related_records
operation is performed on aFeatureLayer
resource. The result of this operation are feature sets groupedby source layer/table object IDs. Each feature set containsFeature objects including the values for the fields requested bythe user. For related layers, if you request geometryinformation, the geometry of each feature is also returned inthe feature set. For related tables, the feature set does notinclude geometries.Note
See the
query
method for a similar function.Parameter
Description
object_ids
Required string. The object IDs of the table/layer to be queried
relationship_id
Required string. The ID of the relationship to be queried.
out_fields
Required string. the list of fields from the related table/layerto be included in the returned feature set. This list is a commadelimited list of field names. If you specify the shape field in thelist of return fields, it is ignored. To request geometry, setreturn_geometry to true. You can also specify the wildcard “*” asthe value of this parameter. In this case, the results will includeall the field values.
definition_expression
Optional string. The definition expression to be applied to therelated table/layer. From the list of objectIds, only those recordsthat conform to this expression are queried for related records.
return_geometry
Optional boolean. If true, the feature set includes the geometryassociated with each feature. The default is true.
max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation. The max_allowable_offset is in the units ofthe outSR. If out_wkid is not specified, then max_allowable_offsetis assumed to be in the unit of the spatial reference of the map.
geometry_precision
Optional integer. This option can be used to specify the number ofdecimal places in the response geometries.
out_wkid
Optional Integer. The spatial reference of the returned geometry.
gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer queried istrue.
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is false.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
historic_moment
Optional Integer/datetime. The historic moment to query. This parameterapplies only if the supportsQueryWithHistoricMoment property of thelayers being queried is set to true. This setting is provided in thelayer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
Syntax: historic_moment=<Epoch time in milliseconds>
return_true_curves
Optional boolean. Optional parameter that is false by default. Whenset to true, returns true curves in output geometries; otherwise,curves are converted to densified
Polyline
orPolygon
objects.- Returns:
Dictionary of the query results
# Usage Example:# Query returning the related records for a feature with objectid value of 2,# returning the values in the 6 attribute fields defined in the `field_string`# variable:>>>field_string="objectid,attribute,system_name,subsystem_name,class_name,water_regime_name">>>rel_records=feat_lyr.query_related_records(object_ids="2",relationship_id=0,out_fields=field_string,return_geometry=True)>>>list(rel_records.keys())['fields','relatedRecordGroups']>>>rel_records["relatedRecordGroups"][{'objectId':2,'relatedRecords':[{'attributes':{'objectid':686,'attribute':'L1UBHh','system_name':'Lacustrine','subsystem_name':'Limnetic','class_name':'Unconsolidated Bottom','water_regime_name':'Permanently Flooded'}}]}]
- query_top_features(top_filter:dict[str,str]|None=None,where:str|None=None,objectids:list[str]|None=None,start_time:datetime|None=None,end_time:datetime|None=None,geometry_filter:GeometryFilter|None=None,out_fields:str='*',return_geometry:bool=True,return_centroid:bool=False,max_allowable_offset:float|None=None,out_sr:dict[str,int]|str|None=None,geometry_precision:int|None=None,return_ids_only:bool=False,return_extents_only:bool=False,order_by_field:str|None=None,return_z:bool=False,return_m:bool=False,result_type:str|None=None,as_df:bool=True)
The
query_top_features
is performed on aFeatureLayer
. This operation returns afeature set or spatially enabled dataframe based on the top features by order within a group. For example, whenquerying counties in the United States, you want to return the top five counties by population ineach state. To do this, you can usequery_top_features
to group by state name, order by desc onthe population and return the first five rows from each group (state).The
top_filter
parameter is used to set the group by, order by, and count criteria used ingenerating the result. The operation also has many of the same parameters (for example, whereand geometry) as the layer query operation. However, unlike the layer query operation,query_top_features
does not support parameters such as outStatistics and its related parametersor return distinct values. Consult theadvancedQueryCapabilities
layer property for more details.If the feature layer collection supports thequery_top_features operation, it will include“supportsTopFeaturesQuery”: True, in the
advancedQueryCapabilities
layer property.Note
See the
query
method for a similar function.Parameter
Description
top_filter
Required Dict. Thetop_filter define the aggregation of the data.
groupByFields define the field or fields used to aggregate
your data.
topCount defines the number of features returned from the top
features query and is a numeric value.
orderByFields defines the order in which the top features will
be returned. orderByFields can be specified ineither ascending (asc) or descending (desc)order, ascending being the default.
- Example: {“groupByFields”: “worker”, “topCount”: 1,
“orderByFields”: “employeeNumber”}
where
Optional String. A WHERE clause for the query filter. SQL ‘92 WHEREclause syntax on the fields in the layer is supported for most datasources.
objectids
Optional List. The object IDs of the layer or table to be queried.
start_time
Optional Datetime. The starting time to query for.
end_time
Optional Datetime. The end date to query for.
geometry_filter
Optional from arcgis.geometry.filter. Allows for the information tobe filtered on spatial relationship with another geometry.
out_fields
Optional String. The list of fields to include in the return results.
return_geometry
Optional Boolean. If False, the query will not return geometries.The default is True.
return_centroid
Optional Boolean. If True, the centroid of the geometry will beadded to the output.
max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation.The max_allowable_offset is in the units of out_sr. If out_sr is notspecified, max_allowable_offset is assumed to be in the unit of thespatial reference of the layer.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
geometry_precision
Optional Integer. This option can be used to specify the number ofdecimal places in the response geometries returned by the queryoperation.This applies to X and Y values only (not m or z-values).
return_ids_only
Optional boolean. Default is False. If true, the response onlyincludes an array of object IDs. Otherwise, the response is afeature set.
return_extent_only
Optional boolean. If true, the response only includes the extent ofthe features that would be returned by the query. IfreturnCountOnly=true, the response will return both the count andthe extent.The default is false. This parameter applies only if thesupportsReturningQueryExtent property of the layer is true.
order_by_field
Optional Str. Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is False.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
result_type
Optional String. The result_type can be used to control the numberof features returned by the query operation.Values: none | standard | tile
as_df
Optional Boolean. If False, the result is returned as a FeatureSet.If True (default) the result is returned as a spatially enabled dataframe.
- Returns:
Default is a pd.DataFrame, but when
`as_df=False`
returns aFeatureSet
.If`return_count_only=True`
, the return type is Integer.If`return_ids_only=True`
, a list of value is returned.
- propertyrenderer
Get/Set the Renderer of the Feature Layer.
Parameter
Description
value
Required dict.
Note
When set, this overrides the default symbology when displaying it on a webmap.
- Returns:
`InsensitiveDict`
: A case-insensitivedict
like object used to update and alter JSONA varients of a case-less dictionary that allows for dot and bracket notation.
- propertytime_filter
The
time_filter
method is used to set a time filter instead of querying time-enabled mapservice layers or time-enabled feature service layers, a time filtercan be specified. Time can be filtered as a single instant or byseparating the two ends of a time extent with a comma.Note
The
time_filter
method is supported starting at Enterprise 10.7.1+.Input
Description
value
Required Datetime/List Datetime. This is a singleor list of start/stop date.
- Returns:
A string of datetime values as milliseconds from epoch
- update_metadata(file_path:str)
The
update_metadata
updates aFeatureLayer
metadata from an xml file.Parameter
Description
file_path
Required String. The path to the .xml file that contains the metadata.
- Returns:
A boolean indicating success (True), or failure (False)
- validate_sql(sql:str,sql_type:str='where')
The
validate_sql
operation validates anSQL-92
expression or WHEREclause.Thevalidate_sql
operation ensures that anSQL-92
expression, suchas one written by a user through a user interface, is correctbefore performing another operation that uses the expression.Note
For example,
validateSQL
can be used to validate information that issubsequently passed in as part of the where parameter of the calculate operation.validate_sql
also prevents SQL injection. In addition, all tableand field names used in the SQL expression or WHERE clause arevalidated to ensure they are valid tables and fields.Parameter
Description
sql
Required String. The SQL expression of WHERE clause to validate.Example: “Population > 300000”
sql_type
- Optional String. Three SQL types are supported in validate_sql
where(default)
- Represents the custom WHERE clause the usercan compose when querying a layer or using calculate.expression
- Represents an SQL-92 expression. Currently,expression is used as a default value expression when adding anew field or using the calculate API.statement
- Represents the full SQL-92 statement that can bepassed directly to the database. No current ArcGIS REST APIresource or operation supports using the full SQL-92 SELECTstatement directly. It has been added to the validateSQL forcompleteness.Values:where | expression | statement
- Returns:
A JSON Dictionary indicating ‘success’ or ‘error’
Oriented Imagery Layer
- classarcgis.features.OrientedImageryLayer(url,gis=None,container=None,dynamic_layer=None)
- append(item_id:str|None=None,upload_format:str='featureCollection',source_table_name:str|None=None,field_mappings:list[dict[str,str]]|None=None,edits:dict|None=None,source_info:dict|None=None,upsert:bool=False,skip_updates:bool=False,use_globalids:bool=False,update_geometry:bool=True,append_fields:list[str]|None=None,rollback:bool=False,skip_inserts:bool|None=None,upsert_matching_field:str|None=None,upload_id:str|None=None,layer_mappings:list[dict[str,int]]|None=None,*,return_messages:bool|None=None,future:bool=False)
The
append
method is used to update an existing hostedFeatureLayer
object.See theAppend (Feature Service/Layer)page in the ArcGIS REST API documentation for more information.Note
The
append
method is only available in ArcGIS Online and ArcGIS Enterprise 10.8.1+Note
Please reference specific deployment documentation for important information on criteria thatmust be met before appending data will work:
Parameter
Description
item_id
Optional string. The ID for the Portal item that contains the sourcefile.Used in conjunction with editsUploadFormat.
upload_format
Required string. The source append data format. Supported formatsvary by deployment and layer. See documentation for details:
Note
You can find whether append is supported on a Feature Layer,and the specific formats the layer supports by checking theproperties:
>>>featurelayer.properties.supportsAppendTrue>>>featureLayer.properties.supportedAppendFormats'sqlite,geoPackage,shapefile,filegdb,featureCollection''geojson,csv,excel,jsonl,featureService,pbf'
source_table_name
Required string. Required even when the source data contains onlyone table, e.g., for file geodatabase.
# Example usage:source_table_name="Building"
field_mappings
Optional list. Used to map source data to a destination layer.Syntax: field_mappings=[{“name” : <”targetName”>,
“sourceName” : < “sourceName”>}, …]
# Example usage:field_mappings=[{"name":"CountyID","sourceName":"GEOID10"}]
edits
Optional dictionary. Only feature collection json is supported. Appendsupports all format through the upload_id or item_id.
source_info
Optional dictionary. This is only needed when appending data fromexcel or csv. The appendSourceInfo can be the publishing parameterreturned from analyze the csv or excel file.
upsert
Optional boolean. Optional parameter specifying whether the editsneeds to be applied as updates if the feature already exists.Default is false.
skip_updates
Optional boolean. Parameter is used only when upsert is true.
use_globalids
Optional boolean. Specifying whether upsert needs to use GlobalIdwhen matching features.
update_geometry
Optional boolean. The parameter is used only when upsert is true.Skip updating the geometry and update only the attributes forexisting features if they match source features by objectId orglobalId.(as specified by useGlobalIds parameter).
append_fields
Optional list. The list of destination fields to append to. This issupported when upsert=true or false.
#Values:["fieldName1","fieldName2",....]
rollback
Optional boolean. Optional parameter specifying whether the upsertedits needs to be rolled back in case of failure. Default is false.
skip_inserts
Used only when upsert is true. Used to skip inserts if the value istrue. The default value is false.
upsert_matching_field
Optional string. The layer field to be used when matching featureswith upsert. ObjectId, GlobalId, and any other field that has aunique index can be used with upsert.This parameter overrides use_globalids; e.g., specifyingupsert_matching_field will be used even if you specifyuse_globalids = True.Example: upsert_matching_field=”MyfieldWithUniqueIndex”
upload_id
Optional string. The itemID field from an
upload()
response, corresponding withtheappendUploadId REST API argument. This argument should not beused along side theitem_id argument.layer_mappings
Optional list of dictionaries. This is needed if the source is afeature service. It is used to map a source layer to a destinationlayer. Only one source can be mapped to a layer.
Syntax: layerMappings=[{“id”: <layerID>, “sourceId”: <layer id>}]
return_messages
Optional Boolean. When set toTrue, the messages returned fromthe append will be returned. IfFalse, the response messages willnot be returned. This alters the output to be a tuple consisting ofa (Boolean, Dictionary).
future
Optional boolean.
IfTrue, method runs asynchronously and a future object will bereturned. The process will return control to the user.
IfFalse, method runs synchronously and process waits until theoperation completes before returning control back to user. This isthe default value.
- Returns:
Iffuture=False, A boolean indicating success (True), or failure (False). Whenreturn_messages isTrue, the response will return a tuple with a boolean indicatingsuccess or failure, and dictionary with the return messages.
If
future=True
, then the result is aFuture
object.Callresult()
to get the response.
# Usage Example>>>feature_layer.append(source_table_name="Building",field_mappings=[{"name":"CountyID","sourceName":"GEOID10"}],upsert=True,append_fields=["fieldName1","fieldName2",....,fieldname22],return_messages=False)<True>
- calculate(where:str,calc_expression:list[dict[str,Any]],sql_format:str='standard',version:str|None=None,sessionid:str|None=None,return_edit_moment:bool|None=None,future:bool=False)
The
calculate
operation is performed on aFeatureLayer
resource.calculate
updates the values of one or more fields in anexisting feature service layer based on SQL expressions or scalarvalues. Thecalculate
operation can only be used if thesupportsCalculate
property of the layer isTrue.Neither the Shape field nor system fields can be updated usingcalculate
. System fields includeObjectId
andGlobalId
.Inputs
Description
where
Required String. A where clause can be used to limitthe updated records. Any legal SQL where clauseoperating on the fields in the layer is allowed.
calc_expression
Required List. The array of field/value info objectsthat contain the field or fields to update and theirscalar values or SQL expression. Allowed types aredictionary and list. List must be a list ofdictionary objects.
Calculation Format is as follows:
{“field” : “<field name>”, “value” : “<value>”}
sql_format
Optional String. The SQL format for thecalc_expression. It can be either standard SQL92(standard) or native SQL (native). The default isstandard.
Values:standard,native
version
Optional String. The geodatabase version to applythe edits.
sessionid
Optional String. A parameter which is set by aclient during long transaction editing on a branchversion. The sessionid is a GUID value that clientsestablish at the beginning and use throughout theedit session.The sessionid ensures isolation during the editsession. This parameter applies only if theisDataBranchVersioned property of the layer istrue.
return_edit_moment
Optional Boolean. This parameter specifies whetherthe response will report the time edits wereapplied. If true, the server will return the timeedits were applied in the response’s edit momentkey. This parameter applies only if theisDataBranchVersioned property of the layer istrue.
future
Optional boolean. If True, a future object will bereturned and the processwill not wait for the task to complete. The default isFalse, which means wait for results.
This applies to 10.8+ only
- Returns:
- A dictionary with the following format:
{‘updatedFeatureCount’: 1,‘success’: True}
If
future=True
, then the result is aFuture
object. Callresult()
to get the response.
# Usage Example 1:print(fl.calculate(where="OBJECTID < 2",calc_expression={"field":"ZONE","value":"R1"}))
# Usage Example 2:print(fl.calculate(where="OBJECTID < 2001",calc_expression={"field":"A","sqlExpression":"B*3"}))
- propertycontainer
Get/Set the
FeatureLayerCollection
to which thislayer belongs.Parameter
Description
value
Required
FeatureLayerCollection
.- Returns:
The Feature Layer Collection where the layer is stored
- propertycontingent_values:dict[str,Any]
Returns the define contingent values for the given layer.:returns: Dict[str,Any]
- delete_features(deletes:str|None=None,where:str|None=None,geometry_filter:GeometryFilter|None=None,gdb_version:str|None=None,rollback_on_failure:bool=True,return_delete_results:bool=True,future:bool=False)
Deletes features in a
FeatureLayer
orTable
Parameter
Description
deletes
Optional string. A comma separated string of OIDs to remove from theservice.
where
Optional string. A where clause for the query filter. Any legal SQLwhere clause operating on the fields in the layer is allowed.Features conforming to the specified where clause will be deleted.
geometry_filter
Optional
SpatialFilter
. A spatial filter fromarcgis.geometry.filters module to filter results by a spatialrelationship with another geometry.gdb_version
Optional string. The geodatabase version. This parameter applies onlyif theisDataVersioned property of the layer is true.
rollback_on_failure
Optional boolean. Optional parameter to specify if the edits shouldbe applied only if all submitted edits succeed. If false, the serverwill apply the edits that succeed even if some of the submittededits fail. If true, the server will apply the edits only if alledits succeed. The default value is true.
return_delete_results
Optional Boolean. Optional parameter that indicates whether a resultis returned per deleted row when the deleteFeatures operation is run.The default is true.
future
Optional boolean. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.
- Returns:
A dictionary if future=False (default), else If
future=True
,then the result is aFuture
object. Callresult()
to get the response.
# Usage Example with only a "where" sql statement>>>fromarcgis.featuresimportFeatureLayer>>>gis=GIS("pro")>>>buck=gis.content.search("owner:"+gis.users.me.username)>>>buck_1=buck[1]>>>lay=buck_1.layers[0]>>>la_df=lay.delete_features(where="OBJECTID > 15")>>>la_df{'deleteResults':[{'objectId':1,'uniqueId':5,'globalId':None,'success':True},{'objectId':2,'uniqueId':5,'globalId':None,'success':True},{'objectId':3,'uniqueId':5,'globalId':None,'success':True},{'objectId':4,'uniqueId':5,'globalId':None,'success':True},{'objectId':5,'uniqueId':5,'globalId':None,'success':True},{'objectId':6,'uniqueId':6,'globalId':None,'success':True},{'objectId':7,'uniqueId':7,'globalId':None,'success':True},{'objectId':8,'uniqueId':8,'globalId':None,'success':True},{'objectId':9,'uniqueId':9,'globalId':None,'success':True},{'objectId':10,'uniqueId':10,'globalId':None,'success':True},{'objectId':11,'uniqueId':11,'globalId':None,'success':True},{'objectId':12,'uniqueId':12,'globalId':None,'success':True},{'objectId':13,'uniqueId':13,'globalId':None,'success':True},{'objectId':14,'uniqueId':14,'globalId':None,'success':True},{'objectId':15,'uniqueId':15,'globalId':None,'success':True}]}
- edit_features(adds:FeatureSet|list[dict]|None=None,updates:FeatureSet|list[dict]|None=None,deletes:FeatureSet|list[dict]|None=None,gdb_version:str|None=None,use_global_ids:bool=False,rollback_on_failure:bool=True,return_edit_moment:bool=False,attachments:dict[str,list[Any]]|None=None,true_curve_client:bool=False,session_id:str|None=None,use_previous_moment:bool=False,datum_transformation:int|dict[str,Any]|None=None,future:bool=False)
Adds, updates, and deletes features to theassociated
FeatureLayer
orTable
in a single call.Note
When making large number (250+ records at once) of edits,
append
should be used overedit_features
to improveperformance and ensure service stability.Inputs
Description
adds
Optional
FeatureSet
/List. The array of features to be added.updates
Optional
FeatureSet
/List. The array of features to be updated.deletes
Optional
FeatureSet
/List. string of OIDs to remove from serviceuse_global_ids
Optional boolean. Instead of referencing the default Object ID field, the servicewill look at a GUID field to track changes. This means the GUIDs will be passedinstead of OIDs for delete, update or add features.
gdb_version
Optional string. The geodatabase version to apply edits. This parameterapplies only if theisDataVersioned property of the layer is true.
rollback_on_failure
Optional boolean. Optional parameter to specify if the edits should be applied onlyif all submitted edits succeed. If false, the server will apply the edits that succeedeven if some of the submitted edits fail. If true, the server will apply the editsonly if all edits succeed. The default value is true.
return_edit_moment
Optional boolean. Introduced at 10.5, only applicable with ArcGIS Server servicesonly. Specifies whether the response will report the time edits were applied. If setto true, the server will return the time in the response’s editMoment key. The defaultvalue is false.
attachments
Optional Dict. This parameter adds, updates, or deletes attachments. It applies onlywhen theuse_global_ids parameter is set to true. For adds, the globalIds of theattachments provided by the client are preserved. When useGlobalIds is true, updatesand deletes are identified by each feature or attachment globalId, rather than theirobjectId or attachmentId. This parameter requires the layer’ssupportsApplyEditsWithGlobalIds property to be true.
Attachments to be added or updated can use either pre-uploaded data or base 64encoded data.
Inputs
Inputs
Description
adds
List of attachments to add.
updates
List of attachments to update
deletes
List of attachments to delete
See theApply Edits to a Feature Service layerin the ArcGIS REST API for more information.
true_curve_client
Optional boolean. Introduced at 10.5. Indicates to the server whether the client istrue curve capable. When set to true, this indicates to the server that true curvegeometries should be downloaded and that geometries containing true curves should beconsumed by the map service without densifying it. When set to false, this indicatesto the server that the client is not true curves capable. The default value is false.
session_id
Optional String. Introduced at 10.6. Thesession_id is a GUID value that clientsestablish at the beginning and use throughout the edit session. The sessionID ensuresisolation during the edit session. Thesession_id parameter is set by a clientduring long transaction editing on a branch version.
use_previous_moment
Optional Boolean. Introduced at 10.6. Theuse_previous_moment parameter is used toapply the edits with the same edit moment as the previous set of edits. This allows aneditor to apply single block of edits partially, complete another task and thencomplete the block of edits. This parameter is set by a client during long transactionediting on a branch version.
When set to true, the edits are applied with the same edit moment as the previous setof edits. When set to false or not set (default) the edits are applied with a newedit moment.
datum_transformation
Optional Integer/Dictionary. This parameter applies a datum transformation whileprojecting geometries in the results when out_sr is different than the layer’s spatialreference. When specifying transformations, you need to think about which datumtransformation best projects the layer (not the feature service) to theoutSR andsourceSpatialReference property in the layer properties. For a list of valid datumtransformation ID values ad well-known text strings, seeUsing spatial references.For more information on datum transformations please see the transformationparameter in theProject operation documentation.
Examples
Inputs
Description
WKID
Integer. Ex: datum_transformation=4326
WKT
Dict. Ex: datum_transformation={“wkt”: “<WKT>”}
Composite
Dict. Ex: datum_transformation=```{‘geoTransforms’:[{‘wkid’:<id>,’forward’:<true|false>},{‘wkt’:’<WKT>’,’forward’:<True|False>}]}```
future
Optional Boolean. If theFeatureLayer hassupportsAsyncApplyEdits settoTrue, then edits can be applied asynchronously. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.
- Returns:
A dictionary by default, or If
future=True
, then the result is aFuture
object. Callresult()
to get the response.The dictionary will contain keys “addResults”, “updateResults”, “deleteResults”, and “attachments” with the results of the operation.
# Usage Example 1:feature=[{'attributes':{'ObjectId':1,'UpdateDate':datetime.datetime.now(),}}]lyr.edit_features(updates=feature)>>>{'addResults':[],'updateResults':[{'objectId':1,'success':True}]},'deleteResults':[],}
# Usage Example 2:adds={"geometry":{"x":500,"y":500,"spatialReference":{"wkid":102100,"latestWkid":3857}},"attributes":{"ADMIN_NAME":"Fake Location"}}lyr.edit_features(adds=[adds])>>>{'addResults':[{'objectId':2542,'success':True}],'updateResults':[],'deleteResults':[],}
# Usage Example 3:lyr.edit_features(deletes=[2542])>>>{'addResults':[],'updateResults':[],'deleteResults':[{'objectId':2542,'success':True}],}
- propertyestimates:dict[str,Any]
Returns up-to-date approximations of layer information, such as row countand extent. Layers that support this property will includeinfoInEstimates information in the layer’s
properties
.Currently available with ArcGIS Online and Enterprise 10.9.1+
- Returns:
Dict[str, Any]
- export_attachments(output_folder:str,label_field:str|None=None)
Exports attachments from the
FeatureLayer
in Imagenetformat using theoutput_label_field
.Parameter
Description
output_folder
Required string. Output folder where the attachments will be stored.If None, a default folder is created
label_field
Optional string. Field which contains the label/category of each feature.
- Returns:
Nothing is returned from this method
- propertyfield_groups:dict[str,Any]
Returns the defined list of field groups for a given layer.
- Returns:
dict[str,Any]
- classmethodfromitem(item:Item,index:int=0)→OrientedImageryLayer
The
fromitem
method returns the layer at the specified index from a layerItem
object.Parameter
Description
item
Required Item. An item containing layers.
index
Optional int. The index of the layer amongst the item’s layers
- Returns:
The layer at the specified index.
# Usage Example>>>layer.fromitem(item="9311d21a9a2047d19c0faaebd6f2cca6",index=3)
- generate_renderer(definition:dict,where:str|None=None)
Groups data using the supplied definition (classification definition) and an optional where clause. Theresult is a renderer object.
Note
Use baseSymbol and colorRamp to definethe symbols assigned to each class. If the operation is performedon a table, the result is a renderer object containing the dataclasses and no symbols.
Parameter
Description
definition
Required dict. The definition using the renderer that is generated.Use either class breaks or unique value classification definitions.SeeClassification Objects for additional details.
where
Optional string. A where clause for which the data needs to beclassified. Any legal SQL where clause operating on the fields inthe dynamic layer/table is allowed.
- Returns:
A JSON Dictionary
# Example UsageFeatureLayer.generate_renderer(definition={"type":"uniqueValueDef","uniqueValueFields":["Has_Pool"],"fieldDelimiter":",","baseSymbol":{"type":"esriSFS","style":"esriSLSSolid","width":2},"colorRamp":{"type":"algorithmic","fromColor":[115,76,0,255],"toColor":[255,25,86,255],"algorithm":"esriHSVAlgorithm"}},where="POP2000 > 350000")
- get_html_popup(oid:str|None)
The
get_html_popup
method provides details about the HTML pop-upauthored by theUser
using ArcGIS Pro or ArcGIS Desktop.Parameter
Description
oid
Optional string. Object id of the feature to get the HTML popup.
- Returns:
A string
- get_unique_values(attribute:str,query_string:str='1=1')
Retrieves a list of unique values for a given attribute in the
FeatureLayer
.Parameter
Description
attribute
Required string. The feature layer attribute to query.
query_string
Optional string. SQL Query that will be used to filter attributesbefore unique values are returned.ex. “name_2 like ‘%K%’”
- Returns:
A list of unique values
# Usage Example with only a "where" sql statement>>>fromarcgis.featuresimportFeatureLayer>>>gis=GIS("pro")>>>buck=gis.content.search("owner:"+gis.users.me.username)>>>buck_1=buck[1]>>>lay=buck_1.layers[0]>>>layer=lay.get_unique_values(attribute="COUNTY")>>>layer['PITKIN','PLATTE','TWIN FALLS']
- propertymanager
The
manager
property is a helper object to manage theFeatureLayer
, such asupdating its definition.- Returns:
# Usage Example>>>manager=FeatureLayer.manager
- propertymetadata
Get the Feature Layer’s metadata.
Note
If metadata is disabled on the GIS or thelayer does not support metadata,
None
will be returned.- Returns:
String of the metadata, if any
- query(where:str='1=1',out_fields:str|list[str]='*',time_filter:list[datetime]|None=None,geometry_filter:GeometryFilter|None=None,return_geometry:bool=True,return_count_only:bool=False,return_ids_only:bool=False,return_distinct_values:bool=False,return_extent_only:bool=False,group_by_fields_for_statistics:str|None=None,statistic_filter:StatisticFilter|None=None,result_offset:int|None=None,result_record_count:int|None=None,object_ids:list[str]|None=None,distance:int|None=None,units:str|None=None,max_allowable_offset:int|None=None,out_sr:dict[str,int]|str|None=None,geometry_precision:int|None=None,gdb_version:str|None=None,order_by_fields:str|None=None,out_statistics:list[dict[str,Any]]|None=None,return_z:bool=False,return_m:bool=False,multipatch_option:tuple=None,quantization_parameters:dict[str,Any]|None=None,return_centroid:bool=False,return_all_records:bool=True,result_type:str|None=None,historic_moment:int|datetime|None=None,sql_format:str|None=None,return_true_curves:bool=False,return_exceeded_limit_features:bool|None=None,as_df:bool=False,datum_transformation:int|dict[str,Any]|None=None,time_reference_unknown_client:bool|None=None,**kwargs)
The
query
method queries aFeatureLayer
based on asql
statement.Parameter
Description
where
Optional string. SQL-92 WHERE clause syntax on the fields in the layeris supported for most data sources. Some data sources have restrictionson what is supported. Hosted feature services in ArcGIS Enterprise runningon a spatiotemporal data source only support a subset of SQL-92.Below is a list of supported SQL-92 with spatiotemporal-based feature services:
( ‘<=’ | ‘>=’ | ‘<’ | ‘>’ | ‘=’ | ‘!=’ | ‘<>’ | LIKE )(AND | OR)(IS | IS_NOT)(IN | NOT_IN) ( ‘(’ ( expr ( ‘,’ expr )* )? ‘)’ )COLUMN_NAME BETWEEN LITERAL_VALUE AND LITERAL_VALUE
out_fields
Optional list of fields to be included in the returned result set.This list is a comma-delimited list of field names. You can also specifythe wildcard “*” as the value of this parameter. In this case, the queryresults include all the field values.
Note
If specifyingreturn_count_only,return_id_only, orreturn_extent_onlyas True, do not specify this parameter in order to avoid errors.
object_ids
Optional string. The object IDs of this layer or table to be queried.The object ID values should be a comma-separated string.
Note
There might be a drop in performance if the layer/table datasource resides in an enterprise geodatabase and more than1,000 object_ids are specified.
distance
Optional integer. The buffer distance for the input geometries.The distance unit is specified by units. For example, if thedistance is 100, the query geometry is a point, units is set tometers, and all points within 100 meters of the point are returned.
units
Optional string. The unit for calculating the buffer distance. Ifunit is not specified, the unit is derived from the geometry spatialreference. If the geometry spatial reference is not specified, theunit is derived from the feature service data spatial reference.This parameter only applies ifsupportsQueryWithDistance is true.
- Values:`esriSRUnit_Meter | esriSRUnit_StatuteMile |
esriSRUnit_Foot | esriSRUnit_Kilometer |esriSRUnit_NauticalMile | esriSRUnit_USNauticalMile`
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp inmilliseconds
geometry_filter
Optional from
filters
. Allows for the information tobe filtered on spatial relationship with another geometry.max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation.The max_allowable_offset is in the units of out_sr. If out_sr is notspecified, max_allowable_offset is assumed to be in the unit of thespatial reference of the layer.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
geometry_precision
Optional Integer. This option can be used to specify the number ofdecimal places in the response geometries returned by the queryoperation.This applies to X and Y values only (not m or z-values).
gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer is true.If this is not specified, the query will apply to the publishedmap’s version.
return_geometry
Optional boolean. If true, geometry is returned with the query.Default is true.
return_distinct_values
Optional boolean. If true, it returns distinct values based on thefields specified in out_fields. This parameter applies only if thesupportsAdvancedQueries property of the layer is true. This parametercan be used with return_count_only to return the count of distinctvalues of subfields.
Note
Make sure to set return_geometry to False if this is set to True.Otherwise, reliable results will not be returned.
return_ids_only
Optional boolean. Default is False. If true, the response onlyincludes an array of object IDs. Otherwise, the response is afeature set. When object_ids are specified, setting this parameter totrue is invalid.
return_count_only
Optional boolean. If true, the response only includes the count(number of features/records) that would be returned by a query.Otherwise, the response is a feature set. The default is false. Thisoption supersedes the returnIdsOnly parameter. IfreturnCountOnly = true, the response will return both the count andthe extent.
return_extent_only
Optional boolean. If true, the response only includes the extent ofthe features that would be returned by the query. IfreturnCountOnly=true, the response will return both the count andthe extent.The default is false. This parameter applies only if thesupportsReturningQueryExtent property of the layer is true.
order_by_fields
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
Note
If specifyingreturn_count_only,return_id_only, orreturn_extent_onlyas True, do not specify this parameter in order to avoid errors.
group_by_fields_for_statistics
Optional string. One or more field names on which the values need tobe grouped for calculating the statistics.example: STATE_NAME, GENDER
out_statistics
Optional list of dictionaries. The definitions for one or more field-basedstatistics to be calculated.
Syntax:
- [
- {
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field1”,“outStatisticFieldName”: “Out_Field_Name1”
},{
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field2”,“outStatisticFieldName”: “Out_Field_Name2”
}
]
statistic_filter
Optional
StatisticFilter
instance. The definitions for one or more field-basedstatistics can be added, e.g. statisticType, onStatisticField, oroutStatisticFieldName.Syntax:
sf = StatisticFilter()sf.add(statisticType=”count”, onStatisticField=”1”, outStatisticFieldName=”total”)sf.filter
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is False.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
multipatch_option
Optional x/y footprint. This option dictates how the geometry ofa multipatch feature will be returned.
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th). This option is ignoredif return_all_records is True (i.e. by default).This parameter cannot be specified if the service does not support pagination.
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property. This option is ignored ifreturn_all_records is True (i.e. by default).
quantization_parameters
Optional dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
return_centroid
Optional boolean. Used to return the geometry centroid associatedwith each feature returned. If true, the result includes the geometrycentroid. The default is false. Only supported on layer withpolygon geometry type.
return_all_records
Optional boolean. When True, the query operation will call theservice until all records that satisfy the where_clause arereturned. Note: result_offset and result_record_count will beignored if return_all_records is True. Also, if return_count_only,return_ids_only, or return_extent_only are True, this parameterwill be ignored. If this parameter is set to False but no other limit isspecified, the default is True.
result_type
Optional string. The result_type parameter can be used to controlthe number of features returned by the query operation.Values: None | standard | tile
historic_moment
Optional integer. The historic moment to query. This parameterapplies only if the layer is archiving enabled and thesupportsQueryWithHistoricMoment property is set to true. Thisproperty is provided in the layer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values: none | standard | native
return_true_curves
Optional boolean. When set to true, returns true curves in outputgeometries. When set to false, curves are converted to densifiedpolylines or polygons.
return_exceeded_limit_features
Optional boolean. Optional parameter which is true by default. Whenset to true, features are returned even when the results include‘exceededTransferLimit’: True.
When set to false and querying with resultType = tile features arenot returned when the results include ‘exceededTransferLimit’: True.This allows a client to find the resolution in which the transferlimit is no longer exceeded without making multiple calls.
as_df
Optional boolean. If True, the results are returned as a DataFrameinstead of a FeatureSet.
datum_transformation
Optional Integer/Dictionary. This parameter applies a datum transformation whileprojecting geometries in the results when out_sr is different than the layer’s spatialreference. When specifying transformations, you need to think about which datumtransformation best projects the layer (not the feature service) to theoutSR andsourceSpatialReference property in the layer properties. For a list of valid datumtransformation ID values ad well-known text strings, seeCoordinate systems andtransformations.For more information on datum transformations, please see the transformationparameter in theProject operation.
Examples
Inputs
Description
WKID
Integer. Ex: datum_transformation=4326
WKT
Dict. Ex: datum_transformation={“wkt”: “<WKT>”}
Composite
Dict. Ex: datum_transformation=```{‘geoTransforms’:[{‘wkid’:<id>,’forward’:<true|false>},{‘wkt’:’<WKT>’,’forward’:<True|False>}]}```
kwargs
Optional dict. Optional parameters that can be passed to the Queryfunction. This will allow users to pass additional parameters notexplicitly implemented on the function. A complete list of functionsavailable is documented on the Query REST API.
- Returns:
A
FeatureSet
containing the features matching the query unless another return typeis specified, such asreturn_count_only
,return_extent_only
, orreturn_ids_only
.
# Usage Example with only a "where" sql statement>>>feat_set=feature_layer.query(where="OBJECTID= 1")>>>type(feat_set)<arcgis.Features.FeatureSet>>>>feat_set[0]<Feature1>
# Usage Example of an advanced query returning the object IDs instead of Features>>>id_set=feature_layer.query(where="OBJECTID1",out_fields=["FieldName1, FieldName2"],distance=100,units='esriSRUnit_Meter',return_ids_only=True)>>>type(id_set)<Array>>>>id_set[0]<"Item_id1">
# Usage Example of an advanced query returning the number of features in the query>>>search_count=feature_layer.query(where="OBJECTID1",out_fields=["FieldName1, FieldName2"],distance=100,units='esriSRUnit_Meter',return_count_only=True)>>>type(search_count)<Integer>>>>search_count<149>
# Usage Example with "out_statistics" parameter>>>stats=[{'onStatisticField':"1",'outStatisticFieldName':"total",'statisticType':"count"}]>>>feature_layer.query(out_statistics=stats,as_df=True)# returns a DataFrame containing total count
# Usage Example with "StatisticFilter" parameter>>>fromarcgis._impl.common._filtersimportStatisticFilter>>>sf1=StatisticFilter()>>>sf1.add(statisticType="count",onStatisticField="1",outStatisticFieldName="total")>>>sf1.filter# This is to print the filter content>>>feature_layer.query(statistic_filter=sf1,as_df=True)# returns a DataFrame containing total count
- query_3d(where:str|None=None,out_fields:str|None=None,object_ids:str|None=None,distance:int|None=None,units:str|None=None,time_filter:str|int|None=None,geometry_filter:Geometry|dict|None=None,gdb_version:str|None=None,return_distinct_values:bool|None=None,order_by_fields:str|None=None,group_by_fields_for_statistics:str|None=None,out_statistics:list[dict]|None=None,result_offset:int|None=None,result_record_count:int|None=None,historic_moment:int|None=None,sql_format:str|None=None,format_3d_objects:str|None=None,time_reference_unknown_client:bool|None=None)
The query3D operation allows clients to query 3D object features and isbased on the feature service layer query operation. The 3D object featurelayer still supports layer and service level feature service query operations.
Parameter
Description
where
Optional string. SQL-92 WHERE clause syntax on the fields in the layeris supported for most data sources. Some data sources have restrictionson what is supported. Hosted feature services in ArcGIS Enterprise runningon a spatiotemporal data source only support a subset of SQL-92.Below is a list of supported SQL-92 with spatiotemporal-based feature services:
( ‘<=’ | ‘>=’ | ‘<’ | ‘>’ | ‘=’ | ‘!=’ | ‘<>’ | LIKE )(AND | OR)(IS | IS_NOT)(IN | NOT_IN) ( ‘(’ ( expr ( ‘,’ expr )* )? ‘)’ )COLUMN_NAME BETWEEN LITERAL_VALUE AND LITERAL_VALUE
out_fields
Optional list of fields to be included in the returned result set.This list is a comma-delimited list of field names. You can also specifythe wildcard “*” as the value of this parameter to return allfields in the result.
object_ids
Optional string. The object IDs of this layer or table to be queried.The object ID values should be a comma-separated string.
Note
There might be a drop in performance if the layer/table datasource resides in an enterprise geodatabase and more than1,000 object_ids are specified.
distance
Optional integer. The buffer distance for the input geometries.The distance unit is specified by units. For example, if thedistance is 100, the query geometry is a point, units is set tometers, and all points within 100 meters of the point are returned.
units
Optional string. The unit for calculating the buffer distance. Ifunit is not specified, the unit is derived from the geometry spatialreference. If the geometry spatial reference is not specified, theunit is derived from the feature service data spatial reference.This parameter only applies ifsupportsQueryWithDistance is true.
- Values:`esriSRUnit_Meter | esriSRUnit_StatuteMile |
esriSRUnit_Foot | esriSRUnit_Kilometer |esriSRUnit_NauticalMile | esriSRUnit_USNauticalMile`
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp inmilliseconds
geometry_filter
Optional from
filters
. Allows for the information tobe filtered on spatial relationship with another geometry.gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer is true.If this is not specified, the query will apply to the publishedmap’s version.
return_distinct_values
Optional boolean. If true, it returns distinct values based on thefields specified in out_fields. This parameter applies only if thesupportsAdvancedQueries property of the layer is true. This parametercan be used with return_count_only to return the count of distinctvalues of subfields.
Note
Make sure to set return_geometry to False if this is set to True.Otherwise, reliable results will not be returned.
order_by_fields
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
Note
If specifyingreturn_count_only,return_id_only, orreturn_extent_onlyas True, do not specify this parameter in order to avoid errors.
group_by_fields_for_statistics
Optional string. One or more field names on which the values need tobe grouped for calculating the statistics.example: STATE_NAME, GENDER
out_statistics
Optional list of dictionaries. The definitions for one or more field-basedstatistics to be calculated.
Syntax:
- [
- {
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field1”,“outStatisticFieldName”: “Out_Field_Name1”
},{
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field2”,“outStatisticFieldName”: “Out_Field_Name2”
}
]
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th). This option is ignoredif return_all_records is True (i.e. by default).
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property. This option is ignored ifreturn_all_records is True (i.e. by default).
historic_moment
Optional integer. The historic moment to query. This parameterapplies only if the layer is archiving enabled and thesupportsQueryWithHistoricMoment property is set to true. Thisproperty is provided in the layer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values: none | standard | native
format_3d_objects
Optional string. Specifies the 3D format that will be used to requesta feature. If set to a valid format ID (see layer resource), the geometryof the feature response will be a 3D envelope of the 3D object and willinclude asset maps for the 3D object. Since formats are created asynchronously,review the flags field in the asset map to determine if the format is available(conversionStatus is COMPLETED). If conversionStatus is INPROGRESS, the formatis not ready. Request the feature again later.
If a feature does not have the specified format, the feature will still be returnedaccording to the query parameters (such as the where clause), but theasset mapping will be missing.
Values: “3D_dae” | “3D_dwg” | “3D_fbx” | “3D_glb” | “3D_gltf” | “3D_ifc”| “3D_obj” | “3D_shapebuffer” | “3D_shapebufferg” | “3D_usdc” | “3D_usdz”
time_reference_unknown_client
Optional boolean. Settingtime_reference_unknown_client as Trueindicates that the client is capable of working with data values thatare not in UTC. If its not set to true, and the service layer’sdatesInUnknownTimeZone property is true, then an error is returned.The default is False
Its possible to define a service’s time zone of date fields as unknown.Setting the time zone as unknown means that date values will be returnedas-is from the database, rather than as date values in UTC. Non-hostedfeature services can be set to use an unknown time zone usingArcGIS Server Manager. Setting the time zones to unknown alsosets the datesInUnknownTimeZone layer property as true. Currently,hosted feature services do not support this setting. This setting doesnot apply to editor tracking date fields which are stored and returnedin UTC even when the time zone is set to unknown.
Most clients released prior to ArcGIS Enterprise 10.9 will not be ableto work with feature services that have an unknown time setting.
- Returns:
A dictionary containing the feature, asset map, and asset information for the layer.
USAGEEXAMPLE:Query3Dobjects# Import the required modulesfromarcgis.gisimportGISfromarcgis.featuresimportFeatureLayer# Connect to your GISgis=GIS(profile="your_enterprise_profile")# Search for the feature layersearch_result=gis.content.search("3D Object Feature Layer","Feature Layer")feature_layer=search_result[0]# Create a FeatureLayer objectlayer=FeatureLayer(feature_layer.url,gis)# Query the 3D objectsresult=layer.query_3d(where="OBJECTID < 10",out_fields="*",format_3d_objects="3D_dae")print(result)
- query_analytics(out_analytics:list[dict],where:str='1=1',out_fields:str|list[str]='*',analytic_where:str|None=None,geometry_filter:GeometryFilter|None=None,out_sr:dict[str,int]|str|None=None,return_geometry:bool=True,order_by:str|None=None,result_type:str|None=None,cache_hint:str|None=None,result_offset:int|None=None,result_record_count:int|None=None,quantization_param:dict[str,Any]|None=None,sql_format:str|None=None,future:bool=True,**kwargs)
The
query_analytics
exposes the standardSQL
windows functions that computeaggregate and ranking values based on a group of rows called windowpartition. The window function is applied to the rows after thepartitioning and ordering of the rows.query_analytics
defines awindow or user-specified set of rows within a query result set.query_analytics
can be used to compute aggregated values such as movingaverages, cumulative aggregates, or running totals.Note
See the
query
method for a similar function.SQL Windows Function
A window function performs a calculation across a set of rows (SQL partitionor window) that are related to the current row. Unlike regular aggregatefunctions, use of a window function does not return single output row. Therows retain their separate identities with each calculation appended to therows as a new field value. The window function can access more than justthe current row of the query result.
query_analytics
currently supports the following windows functions:Aggregate functions
Analytic functions
Ranking functions
Aggregate Functions
Aggregate functions are deterministic function that perform a calculation ona set of values and return a single value. They are used in the select listwith optional HAVING clause. GROUP BY clause can also be used to calculatethe aggregation on categories of rows.
query_analytics
can be used tocalculate the aggregation on a specific range of value. Supported aggregatefunctions are:Min
Max
Sum
Count
AVG
STDDEV
VAR
Analytic Functions
Several analytic functions available now in all SQL vendors to compute anaggregate value based on a group of rows or windows partition. Unlikeaggregation functions, analytic functions can return single or multiple rowsfor each group.
CUM_DIST
FIRST_VALUE
LAST_VALUE
LEAD
LAG
PERCENTILE_DISC
PERCENTILE_CONT
PERCENT_RANK
Ranking Functions
Ranking functions return a ranking value for each row in a partition. Dependingon the function that is used, some rows might receive the same value as other rows.
RANK
NTILE
DENSE_RANK
ROW_NUMBER
Partitioning
Partitions are extremely useful when you need to calculate the same metric overdifferent group of rows. It is very powerful and has many potential usages. Forexample, you can add partition by to your window specification to look atdifferent groups of rows individually.
partitionBy
clause divides the query result set into partitions and the sqlwindow function is applied to each partition.The ‘partitionBy’ clause normally refers to the column by which the result ispartitioned. ‘partitionBy’ can also be a value expression (column expression orfunction) that references any of the selected columns (not aliases).Parameter
Description
out_analytics
Required List. A set of analytics to calculate on the Feature Layer.
The definitions for one or more field-based or expression analyticsto be computed. This parameter is supported only on layers/tables thatreturntrue forsupportsAnalytics property.
Note
IfoutAnalyticFieldName is empty or missing, the server assignsa field name to the returned analytic field.
The argument should be a list of dictionaries that define analystics.An analytic definition specifies:
the type of analytic - key:analyticType
the field or expression on which it is to be computed - key:onAnalyticField
the resulting output field name -key:outAnalyticFieldName
the analytic specifications -analysticParameters
SeeOverviewfor details.
# Dictionary structure and options for this parameter[{"analyticType":"<COUNT | SUM | MIN | MAX | AVG | STDDEV | VAR | FIRST_VALUE, LAST_VALUE, LAG, LEAD, PERCENTILE_CONT, PERCENTILE_DISC, PERCENT_RANK, RANK, NTILE, DENSE_RANK, EXPRESSION>","onAnalyticField":"Field1","outAnalyticFieldName":"Out_Field_Name1","analyticParameters":{"orderBy":"<orderBy expression","value":<doublevalue>,//percentilevalue"partitionBy":"<field name or expression>","offset":<integer>,//usedbyLAG/LEAD"windowFrame":{"type":"ROWS"|"RANGE","extent":{"extentType":"PRECEDING"|"BOUNDARY","PRECEDING":{"type":<"UNBOUNDED"|"NUMERIC_CONSTANT"|"CURRENT_ROW">"value":<numericconstantvalue>}"BOUNDARY":{"start":"UNBOUNDED_PRECEDING","NUMERIC_PRECEDING","CURRENT_ROW","startValue":<numericconstantvalue>,"end":<"UNBOUNDED_FOLLOWING"|"NUMERIC_FOLLOWING"|"CURRENT_ROW","endValue":<numericconstantvalue>}}}}}}]
# Usage Example:>>>out_analytics=[{"analyticType":"FIRST_VALUE","onAnalyticField":"POP1990","analyticParameters":{"orderBy":"POP1990","partitionBy":"state_name"},"outAnalyticFieldName":"FirstValue"}]
where
Optional string. The default is 1=1. The selection sql statement.
out_fields
Optional List of field names to return. Field names can be specifiedeither as a List of field names or as a comma separated string.The default is “*”, which returns all the fields.
analytic_where
Optional String. A where clause for the query filter that applies tothe result set of applying the source where clause and all other params.
geometry_filter
Optional from arcgis.geometry.filter. Allows for the information tobe filtered on spatial relationship with another geometry.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
return_geometry
Optional boolean. If true, geometry is returned with the query.Default is true.
order_by
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
result_type
Optional string. The result_type parameter can be used to controlthe number of features returned by the query operation.Values: None | standard | tile
cache_hint
Optional Boolean. If you are performing the same query multiple times,a user can ask the server to cache the call to obtain the resultsquicker. The default isFalse.
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th).
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property.
quantization_parameters
Optional dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values:none | standard | native
future
Optional Boolean. This determines if aFuture object is returned(True) the method returns the results directly (False).
- Returns:
A Pandas DataFrame (pd.DataFrame)
- query_date_bins(bin_field:str|datetime,bin_specs:dict,out_statistics:list[dict[str,Any]],time_filter:TimeFilter|None=None,geometry_filter:GeometryFilter|dict|None=None,bin_order:str|None=None,where:str|None=None,return_centroid:bool|None=False,in_sr:int|dict[str,Any]|None=None,out_sr:int|dict[str,Any]|None=None,spatial_rel:str|None=None,quantization_params:dict[str,Any]|None=None,result_offset:int|None=None,result_record_count:int|None=None,return_exceeded_limit_features:bool|None=False)
The
query_date_bins
operation is performed on aFeatureLayer
.This operation returns a histogram of features divided into bins based on a date field.The response can include statistical aggregations for each bin, such as a count orsum, and may also include the aggregate geometries (in other words, centroid) forpoint layers.The parameters define the bins, the aggregate information returned, and the includedfeatures. Bins are defined using the bin parameter. The
out_statistics
andreturn_centroid
parameters define the information each bin will provide. Includedfeatures can be specified by providing atime
extent,where
condition, and aspatial filter, similar to a query operation.The contents of the
bin_specs
parameter provide flexibility for defining binboundaries. Thebin_specs
parameter’sunit
property defines the time width of eachbin, such as one year, quarter, month, day, or hour. Fixed bins can use multiple units forthese time widths. Theresult_offset
property defines an offset within that time unit.For example, if your bin unit isday
, and you want bin boundaries to go from noon tonoon on the next day, the offset would be 12 hours.Features can be manipulated with the
time_filter
,where
, andgeometry_filter
parameters. By default, the result will expand to fit the feature’s earliest and latestpoint of time. Thetime_filter
parameter defines a fixed starting point and endingpoint of the features based on the field used in binField. Thewhere
andgeometry_filter
parameters allow additional filters to be put on the data.This operation is only supported on feature services using a spatiotemporal datastore. As well, the service property
supportsQueryDateBins
must be set to true.To use pagination with aggregated queries on hosted feature services in ArcGISEnterprise, the
supportsPaginationOnAggregatedQueries
property must betrue
onthe layer. Hosted feature services using a spatiotemporal data store do not currentlysupport pagination on aggregated queries.Parameter
Description
bin_field
Required String. The date field used to determine which bin eachfeature falls into.
bin_specs
Required Dict. A dictionary that describes the characteristics ofbins, such as the size of the bin and its starting position. Thesize of each bin is determined by the number of time units denotedby the
number
andunit
properties.The starting position of the bin is the earliest moment in thespecified unit. For example, each year begins at midnight of January1. An offset inside the bin parameter can provide an offset to thestarting position of the bin. This can contain a positive ornegative integer value.
A bin can take two forms: either a calendar bin or a fixed bin. Acalendar bin is aware of calendar-specific adjustments, such asdaylight saving time and leap seconds. Fixed bins are, by contrast,always a specific unit of measurement (for example, 60 seconds in aminute, 24 hours in a day) regardless of where the date and time ofthe bin starts. For this reason, some calendar-specific units areonly supported as calendar bins.
# Calendar bin>>>bin_specs={"calendarBin":{"unit":"year","timezone":"US/Arizona","offset":{"number":5,"unit":"hour"}}}# Fixed bin>>>bin_specs={"fixedBin":{"number":12,"unit":"hour","offset":{"number":5,"unit":"hour"}}}
out_statistics
Required List of Dicts. The definitions for one or more field-basedstatistics to be calculated:
{"statisticType":"<count | sum | min | max | avg | stddev | var>","onStatisticField":"Field1","outStatisticFieldName":"Out_Field_Name1"}
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.
geometry_filter
Optional from
filters
. Allows for theinformation to be filtered on spatial relationship with anothergeometry.bin_order
Optional String. Either “ASC” or “DESC”. Determines whether resultsare returned in ascending or descending order. Default is ascending.
where
Optional String. A WHERE clause for the query filter. SQL ‘92 WHEREclause syntax on the fields in the layer is supported for most datasources.
return_centroid
Optional Boolean. Returns the geometry centroid associated with allthe features in the bin. If true, the result includes the geometrycentroid. The default is false. This parameter is only supported onpoint data.
in_sr
Optional Integer. The WKID for the spatial reference of the inputgeometry.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
spatial_rel
Optional String. The spatial relationship to be applied to the inputgeometry while performing the query. The supported spatialrelationships include intersects, contains, envelop intersects,within, and so on. The default spatial relationship is intersects(
esriSpatialRelIntersects
). Other options areesriSpatialRelContains
,esriSpatialRelCrosses
,esriSpatialRelEnvelopeIntersects
,esriSpatialRelIndexIntersects
,esriSpatialRelOverlaps
,esriSpatialRelTouches
, andesriSpatialRelWithin
.quantization_params
Optional Dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
# upperLeft origin position{"mode":"view","originPosition":"upperLeft","tolerance":1.0583354500042335,"extent":{"type":"extent","xmin":-18341377.47954369,"ymin":2979920.6113554947,"xmax":-7546517.393554582,"ymax":11203512.89298139,"spatialReference":{"wkid":102100,"latestWkid":3857}}}# lowerLeft origin position{"mode":"view","originPosition":"lowerLeft","tolerance":1.0583354500042335,"extent":{"type":"extent","xmin":-18341377.47954369,"ymin":2979920.6113554947,"xmax":-7546517.393554582,"ymax":11203512.89298139,"spatialReference":{"wkid":102100,"latestWkid":3857}}}
SeeQuantization parameters JSON propertiesfor details on format of this parameter.
Note
This parameter only applies if the layer’s
supportsCoordinateQuantization
property istrue
.result_offset
Optional Int. This parameter fetches query results by skipping thespecified number of records and starting from the next record. Thedefault is 0.
- Note:
This parameter only applies if the layer’s
supportsPagination
property istrue
.
result_record_count
Optional Int. This parameter fetches query results up to the valuespecified. When
result_offset
is specified, but this parameteris not, the map service defaults to the layer’smaxRecordCount
property. The maximum value for this parameter is the value of themaxRecordCount
property. The minimum value entered for thisparameter cannot be below 1.- Note:
This parameter only applies if the layer’s
supportsPagination
property istrue
.
return_exceeded_limit_features
Optional Boolean. When set to
True
, features are returned evenwhen the results include"exceededTransferLimit":true
. Thisallows a client to find the resolution in which the transfer limitis no longer exceeded without making multiple calls. The defaultvalue isFalse
.- Returns:
A Dict containing the resulting features and fields.
# Usage Example>>>flyr_item=gis.content.search("*","Feature Layer")[0]>>>flyr=flyr_item.layers[0]>>>qy_result=flyr.query_date_bins(bin_field="boundary",bin_specs={"calendarBin":{"unit":"day","timezone":"America/Los_Angeles","offset":{"number":8,"unit":"hour"}}},out_statistics=[{"statisticType":"count","onStatisticField":"objectid","outStatisticFieldName":"item_sold_count"},{"statisticType":"avg","onStatisticField":"price","outStatisticFieldName":"avg_daily_revenue "}],time=[1609516800000,1612195199999])>>>qy_result{"features":[{"attributes":{"boundary":1609516800000,"avg_daily_revenue":300.40,"item_sold_count":79}},{"attributes":{"boundary":1612108800000,"avg_daily_revenue":null,"item_sold_count":0}}],"fields":[{"name":"boundary","type":"esriFieldTypeDate"},{"name":"item_sold_count","alias":"item_sold_count","type":"esriFieldTypeInteger"},{"name":"avg_daily_revenue","alias":"avg_daily_revenue","type":"esriFieldTypeDouble"}],"exceededTransferLimit":false}
- query_related_records(object_ids:str,relationship_id:str,out_fields:str='*',definition_expression:str|None=None,return_geometry:bool=True,max_allowable_offset:float|None=None,geometry_precision:int|None=None,out_wkid:int|None=None,gdb_version:str|None=None,return_z:bool=False,return_m:bool=False,historic_moment:int|datetime|None=None,return_true_curve:bool=False)
The
query_related_records
operation is performed on aFeatureLayer
resource. The result of this operation are feature sets groupedby source layer/table object IDs. Each feature set containsFeature objects including the values for the fields requested bythe user. For related layers, if you request geometryinformation, the geometry of each feature is also returned inthe feature set. For related tables, the feature set does notinclude geometries.Note
See the
query
method for a similar function.Parameter
Description
object_ids
Required string. The object IDs of the table/layer to be queried
relationship_id
Required string. The ID of the relationship to be queried.
out_fields
Required string. the list of fields from the related table/layerto be included in the returned feature set. This list is a commadelimited list of field names. If you specify the shape field in thelist of return fields, it is ignored. To request geometry, setreturn_geometry to true. You can also specify the wildcard “*” asthe value of this parameter. In this case, the results will includeall the field values.
definition_expression
Optional string. The definition expression to be applied to therelated table/layer. From the list of objectIds, only those recordsthat conform to this expression are queried for related records.
return_geometry
Optional boolean. If true, the feature set includes the geometryassociated with each feature. The default is true.
max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation. The max_allowable_offset is in the units ofthe outSR. If out_wkid is not specified, then max_allowable_offsetis assumed to be in the unit of the spatial reference of the map.
geometry_precision
Optional integer. This option can be used to specify the number ofdecimal places in the response geometries.
out_wkid
Optional Integer. The spatial reference of the returned geometry.
gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer queried istrue.
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is false.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
historic_moment
Optional Integer/datetime. The historic moment to query. This parameterapplies only if the supportsQueryWithHistoricMoment property of thelayers being queried is set to true. This setting is provided in thelayer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
Syntax: historic_moment=<Epoch time in milliseconds>
return_true_curves
Optional boolean. Optional parameter that is false by default. Whenset to true, returns true curves in output geometries; otherwise,curves are converted to densified
Polyline
orPolygon
objects.- Returns:
Dictionary of the query results
# Usage Example:# Query returning the related records for a feature with objectid value of 2,# returning the values in the 6 attribute fields defined in the `field_string`# variable:>>>field_string="objectid,attribute,system_name,subsystem_name,class_name,water_regime_name">>>rel_records=feat_lyr.query_related_records(object_ids="2",relationship_id=0,out_fields=field_string,return_geometry=True)>>>list(rel_records.keys())['fields','relatedRecordGroups']>>>rel_records["relatedRecordGroups"][{'objectId':2,'relatedRecords':[{'attributes':{'objectid':686,'attribute':'L1UBHh','system_name':'Lacustrine','subsystem_name':'Limnetic','class_name':'Unconsolidated Bottom','water_regime_name':'Permanently Flooded'}}]}]
- query_top_features(top_filter:dict[str,str]|None=None,where:str|None=None,objectids:list[str]|None=None,start_time:datetime|None=None,end_time:datetime|None=None,geometry_filter:GeometryFilter|None=None,out_fields:str='*',return_geometry:bool=True,return_centroid:bool=False,max_allowable_offset:float|None=None,out_sr:dict[str,int]|str|None=None,geometry_precision:int|None=None,return_ids_only:bool=False,return_extents_only:bool=False,order_by_field:str|None=None,return_z:bool=False,return_m:bool=False,result_type:str|None=None,as_df:bool=True)
The
query_top_features
is performed on aFeatureLayer
. This operation returns afeature set or spatially enabled dataframe based on the top features by order within a group. For example, whenquerying counties in the United States, you want to return the top five counties by population ineach state. To do this, you can usequery_top_features
to group by state name, order by desc onthe population and return the first five rows from each group (state).The
top_filter
parameter is used to set the group by, order by, and count criteria used ingenerating the result. The operation also has many of the same parameters (for example, whereand geometry) as the layer query operation. However, unlike the layer query operation,query_top_features
does not support parameters such as outStatistics and its related parametersor return distinct values. Consult theadvancedQueryCapabilities
layer property for more details.If the feature layer collection supports thequery_top_features operation, it will include“supportsTopFeaturesQuery”: True, in the
advancedQueryCapabilities
layer property.Note
See the
query
method for a similar function.Parameter
Description
top_filter
Required Dict. Thetop_filter define the aggregation of the data.
groupByFields define the field or fields used to aggregate
your data.
topCount defines the number of features returned from the top
features query and is a numeric value.
orderByFields defines the order in which the top features will
be returned. orderByFields can be specified ineither ascending (asc) or descending (desc)order, ascending being the default.
- Example: {“groupByFields”: “worker”, “topCount”: 1,
“orderByFields”: “employeeNumber”}
where
Optional String. A WHERE clause for the query filter. SQL ‘92 WHEREclause syntax on the fields in the layer is supported for most datasources.
objectids
Optional List. The object IDs of the layer or table to be queried.
start_time
Optional Datetime. The starting time to query for.
end_time
Optional Datetime. The end date to query for.
geometry_filter
Optional from arcgis.geometry.filter. Allows for the information tobe filtered on spatial relationship with another geometry.
out_fields
Optional String. The list of fields to include in the return results.
return_geometry
Optional Boolean. If False, the query will not return geometries.The default is True.
return_centroid
Optional Boolean. If True, the centroid of the geometry will beadded to the output.
max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation.The max_allowable_offset is in the units of out_sr. If out_sr is notspecified, max_allowable_offset is assumed to be in the unit of thespatial reference of the layer.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
geometry_precision
Optional Integer. This option can be used to specify the number ofdecimal places in the response geometries returned by the queryoperation.This applies to X and Y values only (not m or z-values).
return_ids_only
Optional boolean. Default is False. If true, the response onlyincludes an array of object IDs. Otherwise, the response is afeature set.
return_extent_only
Optional boolean. If true, the response only includes the extent ofthe features that would be returned by the query. IfreturnCountOnly=true, the response will return both the count andthe extent.The default is false. This parameter applies only if thesupportsReturningQueryExtent property of the layer is true.
order_by_field
Optional Str. Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is False.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
result_type
Optional String. The result_type can be used to control the numberof features returned by the query operation.Values: none | standard | tile
as_df
Optional Boolean. If False, the result is returned as a FeatureSet.If True (default) the result is returned as a spatially enabled dataframe.
- Returns:
Default is a pd.DataFrame, but when
`as_df=False`
returns aFeatureSet
.If`return_count_only=True`
, the return type is Integer.If`return_ids_only=True`
, a list of value is returned.
- propertyrenderer
Get/Set the Renderer of the Feature Layer.
Parameter
Description
value
Required dict.
Note
When set, this overrides the default symbology when displaying it on a webmap.
- Returns:
`InsensitiveDict`
: A case-insensitivedict
like object used to update and alter JSONA varients of a case-less dictionary that allows for dot and bracket notation.
- propertytime_filter
The
time_filter
method is used to set a time filter instead of querying time-enabled mapservice layers or time-enabled feature service layers, a time filtercan be specified. Time can be filtered as a single instant or byseparating the two ends of a time extent with a comma.Note
The
time_filter
method is supported starting at Enterprise 10.7.1+.Input
Description
value
Required Datetime/List Datetime. This is a singleor list of start/stop date.
- Returns:
A string of datetime values as milliseconds from epoch
- update_metadata(file_path:str)
The
update_metadata
updates aFeatureLayer
metadata from an xml file.Parameter
Description
file_path
Required String. The path to the .xml file that contains the metadata.
- Returns:
A boolean indicating success (True), or failure (False)
- validate_sql(sql:str,sql_type:str='where')
The
validate_sql
operation validates anSQL-92
expression or WHEREclause.Thevalidate_sql
operation ensures that anSQL-92
expression, suchas one written by a user through a user interface, is correctbefore performing another operation that uses the expression.Note
For example,
validateSQL
can be used to validate information that issubsequently passed in as part of the where parameter of the calculate operation.validate_sql
also prevents SQL injection. In addition, all tableand field names used in the SQL expression or WHERE clause arevalidated to ensure they are valid tables and fields.Parameter
Description
sql
Required String. The SQL expression of WHERE clause to validate.Example: “Population > 300000”
sql_type
- Optional String. Three SQL types are supported in validate_sql
where(default)
- Represents the custom WHERE clause the usercan compose when querying a layer or using calculate.expression
- Represents an SQL-92 expression. Currently,expression is used as a default value expression when adding anew field or using the calculate API.statement
- Represents the full SQL-92 statement that can bepassed directly to the database. No current ArcGIS REST APIresource or operation supports using the full SQL-92 SELECTstatement directly. It has been added to the validateSQL forcompleteness.Values:where | expression | statement
- Returns:
A JSON Dictionary indicating ‘success’ or ‘error’
Table
- classarcgis.features.Table(url,gis=None,container=None,dynamic_layer=None)
Table
objects represent entity classes with uniform properties. In addition to working with“entities with location” asFeature
objects, theGIS
can also workwith non-spatial entities as rows in tables.Note
Working with tables is similar to working with :class:`~arcgis.features.FeatureLayer`objects, except that therows (Features) in a table do not have a geometry, and tables ignore any geometry related operation.
- append(item_id:str|None=None,upload_format:str='featureCollection',source_table_name:str|None=None,field_mappings:list[dict[str,str]]|None=None,edits:dict|None=None,source_info:dict|None=None,upsert:bool=False,skip_updates:bool=False,use_globalids:bool=False,update_geometry:bool=True,append_fields:list[str]|None=None,rollback:bool=False,skip_inserts:bool|None=None,upsert_matching_field:str|None=None,upload_id:str|None=None,layer_mappings:list[dict[str,int]]|None=None,*,return_messages:bool|None=None,future:bool=False)
The
append
method is used to update an existing hostedFeatureLayer
object.See theAppend (Feature Service/Layer)page in the ArcGIS REST API documentation for more information.Note
The
append
method is only available in ArcGIS Online and ArcGIS Enterprise 10.8.1+Note
Please reference specific deployment documentation for important information on criteria thatmust be met before appending data will work:
Parameter
Description
item_id
Optional string. The ID for the Portal item that contains the sourcefile.Used in conjunction with editsUploadFormat.
upload_format
Required string. The source append data format. Supported formatsvary by deployment and layer. See documentation for details:
Note
You can find whether append is supported on a Feature Layer,and the specific formats the layer supports by checking theproperties:
>>>featurelayer.properties.supportsAppendTrue>>>featureLayer.properties.supportedAppendFormats'sqlite,geoPackage,shapefile,filegdb,featureCollection''geojson,csv,excel,jsonl,featureService,pbf'
source_table_name
Required string. Required even when the source data contains onlyone table, e.g., for file geodatabase.
# Example usage:source_table_name="Building"
field_mappings
Optional list. Used to map source data to a destination layer.Syntax: field_mappings=[{“name” : <”targetName”>,
“sourceName” : < “sourceName”>}, …]
# Example usage:field_mappings=[{"name":"CountyID","sourceName":"GEOID10"}]
edits
Optional dictionary. Only feature collection json is supported. Appendsupports all format through the upload_id or item_id.
source_info
Optional dictionary. This is only needed when appending data fromexcel or csv. The appendSourceInfo can be the publishing parameterreturned from analyze the csv or excel file.
upsert
Optional boolean. Optional parameter specifying whether the editsneeds to be applied as updates if the feature already exists.Default is false.
skip_updates
Optional boolean. Parameter is used only when upsert is true.
use_globalids
Optional boolean. Specifying whether upsert needs to use GlobalIdwhen matching features.
update_geometry
Optional boolean. The parameter is used only when upsert is true.Skip updating the geometry and update only the attributes forexisting features if they match source features by objectId orglobalId.(as specified by useGlobalIds parameter).
append_fields
Optional list. The list of destination fields to append to. This issupported when upsert=true or false.
#Values:["fieldName1","fieldName2",....]
rollback
Optional boolean. Optional parameter specifying whether the upsertedits needs to be rolled back in case of failure. Default is false.
skip_inserts
Used only when upsert is true. Used to skip inserts if the value istrue. The default value is false.
upsert_matching_field
Optional string. The layer field to be used when matching featureswith upsert. ObjectId, GlobalId, and any other field that has aunique index can be used with upsert.This parameter overrides use_globalids; e.g., specifyingupsert_matching_field will be used even if you specifyuse_globalids = True.Example: upsert_matching_field=”MyfieldWithUniqueIndex”
upload_id
Optional string. The itemID field from an
upload()
response, corresponding withtheappendUploadId REST API argument. This argument should not beused along side theitem_id argument.layer_mappings
Optional list of dictionaries. This is needed if the source is afeature service. It is used to map a source layer to a destinationlayer. Only one source can be mapped to a layer.
Syntax: layerMappings=[{“id”: <layerID>, “sourceId”: <layer id>}]
return_messages
Optional Boolean. When set toTrue, the messages returned fromthe append will be returned. IfFalse, the response messages willnot be returned. This alters the output to be a tuple consisting ofa (Boolean, Dictionary).
future
Optional boolean.
IfTrue, method runs asynchronously and a future object will bereturned. The process will return control to the user.
IfFalse, method runs synchronously and process waits until theoperation completes before returning control back to user. This isthe default value.
- Returns:
Iffuture=False, A boolean indicating success (True), or failure (False). Whenreturn_messages isTrue, the response will return a tuple with a boolean indicatingsuccess or failure, and dictionary with the return messages.
If
future=True
, then the result is aFuture
object.Callresult()
to get the response.
# Usage Example>>>feature_layer.append(source_table_name="Building",field_mappings=[{"name":"CountyID","sourceName":"GEOID10"}],upsert=True,append_fields=["fieldName1","fieldName2",....,fieldname22],return_messages=False)<True>
- calculate(where:str,calc_expression:list[dict[str,Any]],sql_format:str='standard',version:str|None=None,sessionid:str|None=None,return_edit_moment:bool|None=None,future:bool=False)
The
calculate
operation is performed on aFeatureLayer
resource.calculate
updates the values of one or more fields in anexisting feature service layer based on SQL expressions or scalarvalues. Thecalculate
operation can only be used if thesupportsCalculate
property of the layer isTrue.Neither the Shape field nor system fields can be updated usingcalculate
. System fields includeObjectId
andGlobalId
.Inputs
Description
where
Required String. A where clause can be used to limitthe updated records. Any legal SQL where clauseoperating on the fields in the layer is allowed.
calc_expression
Required List. The array of field/value info objectsthat contain the field or fields to update and theirscalar values or SQL expression. Allowed types aredictionary and list. List must be a list ofdictionary objects.
Calculation Format is as follows:
{“field” : “<field name>”, “value” : “<value>”}
sql_format
Optional String. The SQL format for thecalc_expression. It can be either standard SQL92(standard) or native SQL (native). The default isstandard.
Values:standard,native
version
Optional String. The geodatabase version to applythe edits.
sessionid
Optional String. A parameter which is set by aclient during long transaction editing on a branchversion. The sessionid is a GUID value that clientsestablish at the beginning and use throughout theedit session.The sessionid ensures isolation during the editsession. This parameter applies only if theisDataBranchVersioned property of the layer istrue.
return_edit_moment
Optional Boolean. This parameter specifies whetherthe response will report the time edits wereapplied. If true, the server will return the timeedits were applied in the response’s edit momentkey. This parameter applies only if theisDataBranchVersioned property of the layer istrue.
future
Optional boolean. If True, a future object will bereturned and the processwill not wait for the task to complete. The default isFalse, which means wait for results.
This applies to 10.8+ only
- Returns:
- A dictionary with the following format:
{‘updatedFeatureCount’: 1,‘success’: True}
If
future=True
, then the result is aFuture
object. Callresult()
to get the response.
# Usage Example 1:print(fl.calculate(where="OBJECTID < 2",calc_expression={"field":"ZONE","value":"R1"}))
# Usage Example 2:print(fl.calculate(where="OBJECTID < 2001",calc_expression={"field":"A","sqlExpression":"B*3"}))
- propertycontainer
Get/Set the
FeatureLayerCollection
to which thislayer belongs.Parameter
Description
value
Required
FeatureLayerCollection
.- Returns:
The Feature Layer Collection where the layer is stored
- propertycontingent_values:dict[str,Any]
Returns the define contingent values for the given layer.:returns: Dict[str,Any]
- delete_features(deletes:str|None=None,where:str|None=None,geometry_filter:GeometryFilter|None=None,gdb_version:str|None=None,rollback_on_failure:bool=True,return_delete_results:bool=True,future:bool=False)
Deletes features in a
FeatureLayer
orTable
Parameter
Description
deletes
Optional string. A comma separated string of OIDs to remove from theservice.
where
Optional string. A where clause for the query filter. Any legal SQLwhere clause operating on the fields in the layer is allowed.Features conforming to the specified where clause will be deleted.
geometry_filter
Optional
SpatialFilter
. A spatial filter fromarcgis.geometry.filters module to filter results by a spatialrelationship with another geometry.gdb_version
Optional string. The geodatabase version. This parameter applies onlyif theisDataVersioned property of the layer is true.
rollback_on_failure
Optional boolean. Optional parameter to specify if the edits shouldbe applied only if all submitted edits succeed. If false, the serverwill apply the edits that succeed even if some of the submittededits fail. If true, the server will apply the edits only if alledits succeed. The default value is true.
return_delete_results
Optional Boolean. Optional parameter that indicates whether a resultis returned per deleted row when the deleteFeatures operation is run.The default is true.
future
Optional boolean. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.
- Returns:
A dictionary if future=False (default), else If
future=True
,then the result is aFuture
object. Callresult()
to get the response.
# Usage Example with only a "where" sql statement>>>fromarcgis.featuresimportFeatureLayer>>>gis=GIS("pro")>>>buck=gis.content.search("owner:"+gis.users.me.username)>>>buck_1=buck[1]>>>lay=buck_1.layers[0]>>>la_df=lay.delete_features(where="OBJECTID > 15")>>>la_df{'deleteResults':[{'objectId':1,'uniqueId':5,'globalId':None,'success':True},{'objectId':2,'uniqueId':5,'globalId':None,'success':True},{'objectId':3,'uniqueId':5,'globalId':None,'success':True},{'objectId':4,'uniqueId':5,'globalId':None,'success':True},{'objectId':5,'uniqueId':5,'globalId':None,'success':True},{'objectId':6,'uniqueId':6,'globalId':None,'success':True},{'objectId':7,'uniqueId':7,'globalId':None,'success':True},{'objectId':8,'uniqueId':8,'globalId':None,'success':True},{'objectId':9,'uniqueId':9,'globalId':None,'success':True},{'objectId':10,'uniqueId':10,'globalId':None,'success':True},{'objectId':11,'uniqueId':11,'globalId':None,'success':True},{'objectId':12,'uniqueId':12,'globalId':None,'success':True},{'objectId':13,'uniqueId':13,'globalId':None,'success':True},{'objectId':14,'uniqueId':14,'globalId':None,'success':True},{'objectId':15,'uniqueId':15,'globalId':None,'success':True}]}
- edit_features(adds:FeatureSet|list[dict]|None=None,updates:FeatureSet|list[dict]|None=None,deletes:FeatureSet|list[dict]|None=None,gdb_version:str|None=None,use_global_ids:bool=False,rollback_on_failure:bool=True,return_edit_moment:bool=False,attachments:dict[str,list[Any]]|None=None,true_curve_client:bool=False,session_id:str|None=None,use_previous_moment:bool=False,datum_transformation:int|dict[str,Any]|None=None,future:bool=False)
Adds, updates, and deletes features to theassociated
FeatureLayer
orTable
in a single call.Note
When making large number (250+ records at once) of edits,
append
should be used overedit_features
to improveperformance and ensure service stability.Inputs
Description
adds
Optional
FeatureSet
/List. The array of features to be added.updates
Optional
FeatureSet
/List. The array of features to be updated.deletes
Optional
FeatureSet
/List. string of OIDs to remove from serviceuse_global_ids
Optional boolean. Instead of referencing the default Object ID field, the servicewill look at a GUID field to track changes. This means the GUIDs will be passedinstead of OIDs for delete, update or add features.
gdb_version
Optional string. The geodatabase version to apply edits. This parameterapplies only if theisDataVersioned property of the layer is true.
rollback_on_failure
Optional boolean. Optional parameter to specify if the edits should be applied onlyif all submitted edits succeed. If false, the server will apply the edits that succeedeven if some of the submitted edits fail. If true, the server will apply the editsonly if all edits succeed. The default value is true.
return_edit_moment
Optional boolean. Introduced at 10.5, only applicable with ArcGIS Server servicesonly. Specifies whether the response will report the time edits were applied. If setto true, the server will return the time in the response’s editMoment key. The defaultvalue is false.
attachments
Optional Dict. This parameter adds, updates, or deletes attachments. It applies onlywhen theuse_global_ids parameter is set to true. For adds, the globalIds of theattachments provided by the client are preserved. When useGlobalIds is true, updatesand deletes are identified by each feature or attachment globalId, rather than theirobjectId or attachmentId. This parameter requires the layer’ssupportsApplyEditsWithGlobalIds property to be true.
Attachments to be added or updated can use either pre-uploaded data or base 64encoded data.
Inputs
Inputs
Description
adds
List of attachments to add.
updates
List of attachments to update
deletes
List of attachments to delete
See theApply Edits to a Feature Service layerin the ArcGIS REST API for more information.
true_curve_client
Optional boolean. Introduced at 10.5. Indicates to the server whether the client istrue curve capable. When set to true, this indicates to the server that true curvegeometries should be downloaded and that geometries containing true curves should beconsumed by the map service without densifying it. When set to false, this indicatesto the server that the client is not true curves capable. The default value is false.
session_id
Optional String. Introduced at 10.6. Thesession_id is a GUID value that clientsestablish at the beginning and use throughout the edit session. The sessionID ensuresisolation during the edit session. Thesession_id parameter is set by a clientduring long transaction editing on a branch version.
use_previous_moment
Optional Boolean. Introduced at 10.6. Theuse_previous_moment parameter is used toapply the edits with the same edit moment as the previous set of edits. This allows aneditor to apply single block of edits partially, complete another task and thencomplete the block of edits. This parameter is set by a client during long transactionediting on a branch version.
When set to true, the edits are applied with the same edit moment as the previous setof edits. When set to false or not set (default) the edits are applied with a newedit moment.
datum_transformation
Optional Integer/Dictionary. This parameter applies a datum transformation whileprojecting geometries in the results when out_sr is different than the layer’s spatialreference. When specifying transformations, you need to think about which datumtransformation best projects the layer (not the feature service) to theoutSR andsourceSpatialReference property in the layer properties. For a list of valid datumtransformation ID values ad well-known text strings, seeUsing spatial references.For more information on datum transformations please see the transformationparameter in theProject operation documentation.
Examples
Inputs
Description
WKID
Integer. Ex: datum_transformation=4326
WKT
Dict. Ex: datum_transformation={“wkt”: “<WKT>”}
Composite
Dict. Ex: datum_transformation=```{‘geoTransforms’:[{‘wkid’:<id>,’forward’:<true|false>},{‘wkt’:’<WKT>’,’forward’:<True|False>}]}```
future
Optional Boolean. If theFeatureLayer hassupportsAsyncApplyEdits settoTrue, then edits can be applied asynchronously. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.
- Returns:
A dictionary by default, or If
future=True
, then the result is aFuture
object. Callresult()
to get the response.The dictionary will contain keys “addResults”, “updateResults”, “deleteResults”, and “attachments” with the results of the operation.
# Usage Example 1:feature=[{'attributes':{'ObjectId':1,'UpdateDate':datetime.datetime.now(),}}]lyr.edit_features(updates=feature)>>>{'addResults':[],'updateResults':[{'objectId':1,'success':True}]},'deleteResults':[],}
# Usage Example 2:adds={"geometry":{"x":500,"y":500,"spatialReference":{"wkid":102100,"latestWkid":3857}},"attributes":{"ADMIN_NAME":"Fake Location"}}lyr.edit_features(adds=[adds])>>>{'addResults':[{'objectId':2542,'success':True}],'updateResults':[],'deleteResults':[],}
# Usage Example 3:lyr.edit_features(deletes=[2542])>>>{'addResults':[],'updateResults':[],'deleteResults':[{'objectId':2542,'success':True}],}
- propertyestimates:dict[str,Any]
Returns up-to-date approximations of layer information, such as row countand extent. Layers that support this property will includeinfoInEstimates information in the layer’s
properties
.Currently available with ArcGIS Online and Enterprise 10.9.1+
- Returns:
Dict[str, Any]
- export_attachments(output_folder:str,label_field:str|None=None)
Exports attachments from the
FeatureLayer
in Imagenetformat using theoutput_label_field
.Parameter
Description
output_folder
Required string. Output folder where the attachments will be stored.If None, a default folder is created
label_field
Optional string. Field which contains the label/category of each feature.
- Returns:
Nothing is returned from this method
- propertyfield_groups:dict[str,Any]
Returns the defined list of field groups for a given layer.
- Returns:
dict[str,Any]
- classmethodfromitem(item:Item,table_id:int=0)
The
fromitem
method creates aTable
from aItem
object.The table_id is the id of the table inFeatureLayerCollection
(feature service).Parameter
Description
item
Required
Item
object. The type of item should be aFeatureService
that represents aFeatureLayerCollection
table_id
Required Integer. The id of the layer in feature layer collection(feature service).The default for
table
is 0.- Returns:
A
Table
object
- generate_renderer(definition:dict,where:str|None=None)
Groups data using the supplied definition (classification definition) and an optional where clause. Theresult is a renderer object.
Note
Use baseSymbol and colorRamp to definethe symbols assigned to each class. If the operation is performedon a table, the result is a renderer object containing the dataclasses and no symbols.
Parameter
Description
definition
Required dict. The definition using the renderer that is generated.Use either class breaks or unique value classification definitions.SeeClassification Objects for additional details.
where
Optional string. A where clause for which the data needs to beclassified. Any legal SQL where clause operating on the fields inthe dynamic layer/table is allowed.
- Returns:
A JSON Dictionary
# Example UsageFeatureLayer.generate_renderer(definition={"type":"uniqueValueDef","uniqueValueFields":["Has_Pool"],"fieldDelimiter":",","baseSymbol":{"type":"esriSFS","style":"esriSLSSolid","width":2},"colorRamp":{"type":"algorithmic","fromColor":[115,76,0,255],"toColor":[255,25,86,255],"algorithm":"esriHSVAlgorithm"}},where="POP2000 > 350000")
- get_html_popup(oid:str|None)
The
get_html_popup
method provides details about the HTML pop-upauthored by theUser
using ArcGIS Pro or ArcGIS Desktop.Parameter
Description
oid
Optional string. Object id of the feature to get the HTML popup.
- Returns:
A string
- get_unique_values(attribute:str,query_string:str='1=1')
Retrieves a list of unique values for a given attribute in the
FeatureLayer
.Parameter
Description
attribute
Required string. The feature layer attribute to query.
query_string
Optional string. SQL Query that will be used to filter attributesbefore unique values are returned.ex. “name_2 like ‘%K%’”
- Returns:
A list of unique values
# Usage Example with only a "where" sql statement>>>fromarcgis.featuresimportFeatureLayer>>>gis=GIS("pro")>>>buck=gis.content.search("owner:"+gis.users.me.username)>>>buck_1=buck[1]>>>lay=buck_1.layers[0]>>>layer=lay.get_unique_values(attribute="COUNTY")>>>layer['PITKIN','PLATTE','TWIN FALLS']
- propertymanager
The
manager
property is a helper object to manage theFeatureLayer
, such asupdating its definition.- Returns:
# Usage Example>>>manager=FeatureLayer.manager
- propertymetadata
Get the Feature Layer’s metadata.
Note
If metadata is disabled on the GIS or thelayer does not support metadata,
None
will be returned.- Returns:
String of the metadata, if any
- query(where:str='1=1',out_fields:str|list[str]='*',time_filter:list[datetime]=None,return_count_only:bool=False,return_ids_only:bool=False,return_distinct_values:bool=False,group_by_fields_for_statistics:str|None=None,statistic_filter:StatisticFilter|None=None,result_offset:int|None=None,result_record_count:int|None=None,object_ids:str|None=None,gdb_version:str|None=None,order_by_fields:str|None=None,out_statistics:list[dict[str,Any]]|None=None,return_all_records:bool=True,historic_moment:int|datetime|None=None,sql_format:str|None=None,return_exceeded_limit_features:bool|None=None,as_df:bool=False,having:str|None=None,time_reference_unknown_client:bool|None=None,**kwargs)
The
query
method queries aTable
Layer based on a set of criteria.Parameter
Description
where
Optional string. The default is 1=1. The selection sql statement.
out_fields
Optional List of field names to return. Field names can be specifiedeither as a List of field names or as a comma separated string.The default is “*”, which returns all the fields.
object_ids
Optional string. The object IDs of this layer or table to be queried.The object ID values should be a comma-separated string.
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp inmilliseconds
gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer is true.If this is not specified, the query will apply to the publishedmap’s version.
return_geometry
Optional boolean. If true, geometry is returned with the query.Default is true.
return_distinct_values
Optional boolean. If true, it returns distinct values based on thefields specified in out_fields. This parameter applies only if thesupportsAdvancedQueries property of the layer is true.
return_ids_only
Optional boolean. Default is False. If true, the response onlyincludes an array of object IDs. Otherwise, the response is afeature set.
return_count_only
Optional boolean. If true, the response only includes the count(number of features/records) that would be returned by a query.Otherwise, the response is a feature set. The default is false. Thisoption supersedes the returnIdsOnly parameter. IfreturnCountOnly = true, the response will return both the count andthe extent.
order_by_fields
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
group_by_fields_for_statistics
Optional string. One or more field names on which the values need tobe grouped for calculating the statistics.example: STATE_NAME, GENDER
out_statistics
Optional string. The definitions for one or more field-basedstatistics to be calculated.
Syntax:
- [
- {
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field1”,“outStatisticFieldName”: “Out_Field_Name1”
},{
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field2”,“outStatisticFieldName”: “Out_Field_Name2”
}
]
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th). This option is ignoredif return_all_records is True (i.e. by default).
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property. This option is ignored ifreturn_all_records is True (i.e. by default).
return_all_records
Optional boolean. When True, the query operation will call theservice until all records that satisfy the where_clause arereturned. Note: result_offset and result_record_count will beignored if return_all_records is True. Also, if return_count_only,return_ids_only, or return_extent_only are True, this parameterwill be ignored.
historic_moment
Optional integer. The historic moment to query. This parameterapplies only if the layer is archiving enabled and thesupportsQueryWithHistoricMoment property is set to true. Thisproperty is provided in the layer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values: none | standard | native
return_exceeded_limit_features
Optional boolean. Optional parameter which is true by default. Whenset to true, features are returned even when the results include‘exceededTransferLimit’: True.
When set to false and querying with resultType = tile features arenot returned when the results include ‘exceededTransferLimit’: True.This allows a client to find the resolution in which the transferlimit is no longer exceeded without making multiple calls.
as_df
Optional boolean. If True, the results are returned as a DataFrameinstead of a FeatureSet.
kwargs
Optional dict. Optional parameters that can be passed to the Queryfunction. This will allow users to pass additional parameters notexplicitly implemented on the function. A complete list of functionsavailable is documented on the Query REST API.
- Returns:
A
FeatureSet
object or, if`as_df=True`
, a Panda’s DataFramecontaining the features matching the query unless another return typeis specified, such asreturn_count_only
# Usage Example with only a "where" sql statement>>>feat_set=feature_layer.query(where="OBJECTID1")>>>type(feat_set)<arcgis.Features.FeatureSet>>>>feat_set[0]<Feature1>
# Usage Example of an advanced query returning the object IDs instead of Features>>>id_set=feature_layer.query(where="OBJECTID1",out_fields=["FieldName1, FieldName2"],distance=100,units='esriSRUnit_Meter',return_ids_only=True)>>>type(id_set)<Array>>>>id_set[0]<"Item_id1">
# Usage Example of an advanced query returning the number of features in the query>>>search_count=feature_layer.query(where="OBJECTID1",out_fields=["FieldName1, FieldName2"],distance=100,units='esriSRUnit_Meter',return_count_only=True)>>>type(search_count)<Integer>>>>search_count<149>
- query_3d(where:str|None=None,out_fields:str|None=None,object_ids:str|None=None,distance:int|None=None,units:str|None=None,time_filter:str|int|None=None,geometry_filter:Geometry|dict|None=None,gdb_version:str|None=None,return_distinct_values:bool|None=None,order_by_fields:str|None=None,group_by_fields_for_statistics:str|None=None,out_statistics:list[dict]|None=None,result_offset:int|None=None,result_record_count:int|None=None,historic_moment:int|None=None,sql_format:str|None=None,format_3d_objects:str|None=None,time_reference_unknown_client:bool|None=None)
The query3D operation allows clients to query 3D object features and isbased on the feature service layer query operation. The 3D object featurelayer still supports layer and service level feature service query operations.
Parameter
Description
where
Optional string. SQL-92 WHERE clause syntax on the fields in the layeris supported for most data sources. Some data sources have restrictionson what is supported. Hosted feature services in ArcGIS Enterprise runningon a spatiotemporal data source only support a subset of SQL-92.Below is a list of supported SQL-92 with spatiotemporal-based feature services:
( ‘<=’ | ‘>=’ | ‘<’ | ‘>’ | ‘=’ | ‘!=’ | ‘<>’ | LIKE )(AND | OR)(IS | IS_NOT)(IN | NOT_IN) ( ‘(’ ( expr ( ‘,’ expr )* )? ‘)’ )COLUMN_NAME BETWEEN LITERAL_VALUE AND LITERAL_VALUE
out_fields
Optional list of fields to be included in the returned result set.This list is a comma-delimited list of field names. You can also specifythe wildcard “*” as the value of this parameter to return allfields in the result.
object_ids
Optional string. The object IDs of this layer or table to be queried.The object ID values should be a comma-separated string.
Note
There might be a drop in performance if the layer/table datasource resides in an enterprise geodatabase and more than1,000 object_ids are specified.
distance
Optional integer. The buffer distance for the input geometries.The distance unit is specified by units. For example, if thedistance is 100, the query geometry is a point, units is set tometers, and all points within 100 meters of the point are returned.
units
Optional string. The unit for calculating the buffer distance. Ifunit is not specified, the unit is derived from the geometry spatialreference. If the geometry spatial reference is not specified, theunit is derived from the feature service data spatial reference.This parameter only applies ifsupportsQueryWithDistance is true.
- Values:`esriSRUnit_Meter | esriSRUnit_StatuteMile |
esriSRUnit_Foot | esriSRUnit_Kilometer |esriSRUnit_NauticalMile | esriSRUnit_USNauticalMile`
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp inmilliseconds
geometry_filter
Optional from
filters
. Allows for the information tobe filtered on spatial relationship with another geometry.gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer is true.If this is not specified, the query will apply to the publishedmap’s version.
return_distinct_values
Optional boolean. If true, it returns distinct values based on thefields specified in out_fields. This parameter applies only if thesupportsAdvancedQueries property of the layer is true. This parametercan be used with return_count_only to return the count of distinctvalues of subfields.
Note
Make sure to set return_geometry to False if this is set to True.Otherwise, reliable results will not be returned.
order_by_fields
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
Note
If specifyingreturn_count_only,return_id_only, orreturn_extent_onlyas True, do not specify this parameter in order to avoid errors.
group_by_fields_for_statistics
Optional string. One or more field names on which the values need tobe grouped for calculating the statistics.example: STATE_NAME, GENDER
out_statistics
Optional list of dictionaries. The definitions for one or more field-basedstatistics to be calculated.
Syntax:
- [
- {
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field1”,“outStatisticFieldName”: “Out_Field_Name1”
},{
“statisticType”: “<count | sum | min | max | avg | stddev | var>”,“onStatisticField”: “Field2”,“outStatisticFieldName”: “Out_Field_Name2”
}
]
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th). This option is ignoredif return_all_records is True (i.e. by default).
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property. This option is ignored ifreturn_all_records is True (i.e. by default).
historic_moment
Optional integer. The historic moment to query. This parameterapplies only if the layer is archiving enabled and thesupportsQueryWithHistoricMoment property is set to true. Thisproperty is provided in the layer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values: none | standard | native
format_3d_objects
Optional string. Specifies the 3D format that will be used to requesta feature. If set to a valid format ID (see layer resource), the geometryof the feature response will be a 3D envelope of the 3D object and willinclude asset maps for the 3D object. Since formats are created asynchronously,review the flags field in the asset map to determine if the format is available(conversionStatus is COMPLETED). If conversionStatus is INPROGRESS, the formatis not ready. Request the feature again later.
If a feature does not have the specified format, the feature will still be returnedaccording to the query parameters (such as the where clause), but theasset mapping will be missing.
Values: “3D_dae” | “3D_dwg” | “3D_fbx” | “3D_glb” | “3D_gltf” | “3D_ifc”| “3D_obj” | “3D_shapebuffer” | “3D_shapebufferg” | “3D_usdc” | “3D_usdz”
time_reference_unknown_client
Optional boolean. Settingtime_reference_unknown_client as Trueindicates that the client is capable of working with data values thatare not in UTC. If its not set to true, and the service layer’sdatesInUnknownTimeZone property is true, then an error is returned.The default is False
Its possible to define a service’s time zone of date fields as unknown.Setting the time zone as unknown means that date values will be returnedas-is from the database, rather than as date values in UTC. Non-hostedfeature services can be set to use an unknown time zone usingArcGIS Server Manager. Setting the time zones to unknown alsosets the datesInUnknownTimeZone layer property as true. Currently,hosted feature services do not support this setting. This setting doesnot apply to editor tracking date fields which are stored and returnedin UTC even when the time zone is set to unknown.
Most clients released prior to ArcGIS Enterprise 10.9 will not be ableto work with feature services that have an unknown time setting.
- Returns:
A dictionary containing the feature, asset map, and asset information for the layer.
USAGEEXAMPLE:Query3Dobjects# Import the required modulesfromarcgis.gisimportGISfromarcgis.featuresimportFeatureLayer# Connect to your GISgis=GIS(profile="your_enterprise_profile")# Search for the feature layersearch_result=gis.content.search("3D Object Feature Layer","Feature Layer")feature_layer=search_result[0]# Create a FeatureLayer objectlayer=FeatureLayer(feature_layer.url,gis)# Query the 3D objectsresult=layer.query_3d(where="OBJECTID < 10",out_fields="*",format_3d_objects="3D_dae")print(result)
- query_analytics(out_analytics:list[dict],where:str='1=1',out_fields:str|list[str]='*',analytic_where:str|None=None,geometry_filter:GeometryFilter|None=None,out_sr:dict[str,int]|str|None=None,return_geometry:bool=True,order_by:str|None=None,result_type:str|None=None,cache_hint:str|None=None,result_offset:int|None=None,result_record_count:int|None=None,quantization_param:dict[str,Any]|None=None,sql_format:str|None=None,future:bool=True,**kwargs)
The
query_analytics
exposes the standardSQL
windows functions that computeaggregate and ranking values based on a group of rows called windowpartition. The window function is applied to the rows after thepartitioning and ordering of the rows.query_analytics
defines awindow or user-specified set of rows within a query result set.query_analytics
can be used to compute aggregated values such as movingaverages, cumulative aggregates, or running totals.Note
See the
query
method for a similar function.SQL Windows Function
A window function performs a calculation across a set of rows (SQL partitionor window) that are related to the current row. Unlike regular aggregatefunctions, use of a window function does not return single output row. Therows retain their separate identities with each calculation appended to therows as a new field value. The window function can access more than justthe current row of the query result.
query_analytics
currently supports the following windows functions:Aggregate functions
Analytic functions
Ranking functions
Aggregate Functions
Aggregate functions are deterministic function that perform a calculation ona set of values and return a single value. They are used in the select listwith optional HAVING clause. GROUP BY clause can also be used to calculatethe aggregation on categories of rows.
query_analytics
can be used tocalculate the aggregation on a specific range of value. Supported aggregatefunctions are:Min
Max
Sum
Count
AVG
STDDEV
VAR
Analytic Functions
Several analytic functions available now in all SQL vendors to compute anaggregate value based on a group of rows or windows partition. Unlikeaggregation functions, analytic functions can return single or multiple rowsfor each group.
CUM_DIST
FIRST_VALUE
LAST_VALUE
LEAD
LAG
PERCENTILE_DISC
PERCENTILE_CONT
PERCENT_RANK
Ranking Functions
Ranking functions return a ranking value for each row in a partition. Dependingon the function that is used, some rows might receive the same value as other rows.
RANK
NTILE
DENSE_RANK
ROW_NUMBER
Partitioning
Partitions are extremely useful when you need to calculate the same metric overdifferent group of rows. It is very powerful and has many potential usages. Forexample, you can add partition by to your window specification to look atdifferent groups of rows individually.
partitionBy
clause divides the query result set into partitions and the sqlwindow function is applied to each partition.The ‘partitionBy’ clause normally refers to the column by which the result ispartitioned. ‘partitionBy’ can also be a value expression (column expression orfunction) that references any of the selected columns (not aliases).Parameter
Description
out_analytics
Required List. A set of analytics to calculate on the Feature Layer.
The definitions for one or more field-based or expression analyticsto be computed. This parameter is supported only on layers/tables thatreturntrue forsupportsAnalytics property.
Note
IfoutAnalyticFieldName is empty or missing, the server assignsa field name to the returned analytic field.
The argument should be a list of dictionaries that define analystics.An analytic definition specifies:
the type of analytic - key:analyticType
the field or expression on which it is to be computed - key:onAnalyticField
the resulting output field name -key:outAnalyticFieldName
the analytic specifications -analysticParameters
SeeOverviewfor details.
# Dictionary structure and options for this parameter[{"analyticType":"<COUNT | SUM | MIN | MAX | AVG | STDDEV | VAR | FIRST_VALUE, LAST_VALUE, LAG, LEAD, PERCENTILE_CONT, PERCENTILE_DISC, PERCENT_RANK, RANK, NTILE, DENSE_RANK, EXPRESSION>","onAnalyticField":"Field1","outAnalyticFieldName":"Out_Field_Name1","analyticParameters":{"orderBy":"<orderBy expression","value":<doublevalue>,//percentilevalue"partitionBy":"<field name or expression>","offset":<integer>,//usedbyLAG/LEAD"windowFrame":{"type":"ROWS"|"RANGE","extent":{"extentType":"PRECEDING"|"BOUNDARY","PRECEDING":{"type":<"UNBOUNDED"|"NUMERIC_CONSTANT"|"CURRENT_ROW">"value":<numericconstantvalue>}"BOUNDARY":{"start":"UNBOUNDED_PRECEDING","NUMERIC_PRECEDING","CURRENT_ROW","startValue":<numericconstantvalue>,"end":<"UNBOUNDED_FOLLOWING"|"NUMERIC_FOLLOWING"|"CURRENT_ROW","endValue":<numericconstantvalue>}}}}}}]
# Usage Example:>>>out_analytics=[{"analyticType":"FIRST_VALUE","onAnalyticField":"POP1990","analyticParameters":{"orderBy":"POP1990","partitionBy":"state_name"},"outAnalyticFieldName":"FirstValue"}]
where
Optional string. The default is 1=1. The selection sql statement.
out_fields
Optional List of field names to return. Field names can be specifiedeither as a List of field names or as a comma separated string.The default is “*”, which returns all the fields.
analytic_where
Optional String. A where clause for the query filter that applies tothe result set of applying the source where clause and all other params.
geometry_filter
Optional from arcgis.geometry.filter. Allows for the information tobe filtered on spatial relationship with another geometry.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
return_geometry
Optional boolean. If true, geometry is returned with the query.Default is true.
order_by
Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
result_type
Optional string. The result_type parameter can be used to controlthe number of features returned by the query operation.Values: None | standard | tile
cache_hint
Optional Boolean. If you are performing the same query multiple times,a user can ask the server to cache the call to obtain the resultsquicker. The default isFalse.
result_offset
Optional integer. This option can be used for fetching query resultsby skipping the specified number of records and starting from thenext record (that is, resultOffset + 1th).
result_record_count
Optional integer. This option can be used for fetching query resultsup to the result_record_count specified. When result_offset isspecified but this parameter is not, the map service defaults it tomax_record_count. The maximum value for this parameter is the valueof the layer’s max_record_count property.
quantization_parameters
Optional dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
sql_format
Optional string. The sql_format parameter can be either standardSQL92 standard or it can use the native SQL of the underlyingdatastore native. The default is none which means the sql_formatdepends on useStandardizedQuery parameter.Values:none | standard | native
future
Optional Boolean. This determines if aFuture object is returned(True) the method returns the results directly (False).
- Returns:
A Pandas DataFrame (pd.DataFrame)
- query_date_bins(bin_field:str|datetime,bin_specs:dict,out_statistics:list[dict[str,Any]],time_filter:TimeFilter|None=None,geometry_filter:GeometryFilter|dict|None=None,bin_order:str|None=None,where:str|None=None,return_centroid:bool|None=False,in_sr:int|dict[str,Any]|None=None,out_sr:int|dict[str,Any]|None=None,spatial_rel:str|None=None,quantization_params:dict[str,Any]|None=None,result_offset:int|None=None,result_record_count:int|None=None,return_exceeded_limit_features:bool|None=False)
The
query_date_bins
operation is performed on aFeatureLayer
.This operation returns a histogram of features divided into bins based on a date field.The response can include statistical aggregations for each bin, such as a count orsum, and may also include the aggregate geometries (in other words, centroid) forpoint layers.The parameters define the bins, the aggregate information returned, and the includedfeatures. Bins are defined using the bin parameter. The
out_statistics
andreturn_centroid
parameters define the information each bin will provide. Includedfeatures can be specified by providing atime
extent,where
condition, and aspatial filter, similar to a query operation.The contents of the
bin_specs
parameter provide flexibility for defining binboundaries. Thebin_specs
parameter’sunit
property defines the time width of eachbin, such as one year, quarter, month, day, or hour. Fixed bins can use multiple units forthese time widths. Theresult_offset
property defines an offset within that time unit.For example, if your bin unit isday
, and you want bin boundaries to go from noon tonoon on the next day, the offset would be 12 hours.Features can be manipulated with the
time_filter
,where
, andgeometry_filter
parameters. By default, the result will expand to fit the feature’s earliest and latestpoint of time. Thetime_filter
parameter defines a fixed starting point and endingpoint of the features based on the field used in binField. Thewhere
andgeometry_filter
parameters allow additional filters to be put on the data.This operation is only supported on feature services using a spatiotemporal datastore. As well, the service property
supportsQueryDateBins
must be set to true.To use pagination with aggregated queries on hosted feature services in ArcGISEnterprise, the
supportsPaginationOnAggregatedQueries
property must betrue
onthe layer. Hosted feature services using a spatiotemporal data store do not currentlysupport pagination on aggregated queries.Parameter
Description
bin_field
Required String. The date field used to determine which bin eachfeature falls into.
bin_specs
Required Dict. A dictionary that describes the characteristics ofbins, such as the size of the bin and its starting position. Thesize of each bin is determined by the number of time units denotedby the
number
andunit
properties.The starting position of the bin is the earliest moment in thespecified unit. For example, each year begins at midnight of January1. An offset inside the bin parameter can provide an offset to thestarting position of the bin. This can contain a positive ornegative integer value.
A bin can take two forms: either a calendar bin or a fixed bin. Acalendar bin is aware of calendar-specific adjustments, such asdaylight saving time and leap seconds. Fixed bins are, by contrast,always a specific unit of measurement (for example, 60 seconds in aminute, 24 hours in a day) regardless of where the date and time ofthe bin starts. For this reason, some calendar-specific units areonly supported as calendar bins.
# Calendar bin>>>bin_specs={"calendarBin":{"unit":"year","timezone":"US/Arizona","offset":{"number":5,"unit":"hour"}}}# Fixed bin>>>bin_specs={"fixedBin":{"number":12,"unit":"hour","offset":{"number":5,"unit":"hour"}}}
out_statistics
Required List of Dicts. The definitions for one or more field-basedstatistics to be calculated:
{"statisticType":"<count | sum | min | max | avg | stddev | var>","onStatisticField":"Field1","outStatisticFieldName":"Out_Field_Name1"}
time_filter
Optional list. The format is of [<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.
geometry_filter
Optional from
filters
. Allows for theinformation to be filtered on spatial relationship with anothergeometry.bin_order
Optional String. Either “ASC” or “DESC”. Determines whether resultsare returned in ascending or descending order. Default is ascending.
where
Optional String. A WHERE clause for the query filter. SQL ‘92 WHEREclause syntax on the fields in the layer is supported for most datasources.
return_centroid
Optional Boolean. Returns the geometry centroid associated with allthe features in the bin. If true, the result includes the geometrycentroid. The default is false. This parameter is only supported onpoint data.
in_sr
Optional Integer. The WKID for the spatial reference of the inputgeometry.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
spatial_rel
Optional String. The spatial relationship to be applied to the inputgeometry while performing the query. The supported spatialrelationships include intersects, contains, envelop intersects,within, and so on. The default spatial relationship is intersects(
esriSpatialRelIntersects
). Other options areesriSpatialRelContains
,esriSpatialRelCrosses
,esriSpatialRelEnvelopeIntersects
,esriSpatialRelIndexIntersects
,esriSpatialRelOverlaps
,esriSpatialRelTouches
, andesriSpatialRelWithin
.quantization_params
Optional Dict. Used to project the geometry onto a virtual grid,likely representing pixels on the screen.
# upperLeft origin position{"mode":"view","originPosition":"upperLeft","tolerance":1.0583354500042335,"extent":{"type":"extent","xmin":-18341377.47954369,"ymin":2979920.6113554947,"xmax":-7546517.393554582,"ymax":11203512.89298139,"spatialReference":{"wkid":102100,"latestWkid":3857}}}# lowerLeft origin position{"mode":"view","originPosition":"lowerLeft","tolerance":1.0583354500042335,"extent":{"type":"extent","xmin":-18341377.47954369,"ymin":2979920.6113554947,"xmax":-7546517.393554582,"ymax":11203512.89298139,"spatialReference":{"wkid":102100,"latestWkid":3857}}}
SeeQuantization parameters JSON propertiesfor details on format of this parameter.
Note
This parameter only applies if the layer’s
supportsCoordinateQuantization
property istrue
.result_offset
Optional Int. This parameter fetches query results by skipping thespecified number of records and starting from the next record. Thedefault is 0.
- Note:
This parameter only applies if the layer’s
supportsPagination
property istrue
.
result_record_count
Optional Int. This parameter fetches query results up to the valuespecified. When
result_offset
is specified, but this parameteris not, the map service defaults to the layer’smaxRecordCount
property. The maximum value for this parameter is the value of themaxRecordCount
property. The minimum value entered for thisparameter cannot be below 1.- Note:
This parameter only applies if the layer’s
supportsPagination
property istrue
.
return_exceeded_limit_features
Optional Boolean. When set to
True
, features are returned evenwhen the results include"exceededTransferLimit":true
. Thisallows a client to find the resolution in which the transfer limitis no longer exceeded without making multiple calls. The defaultvalue isFalse
.- Returns:
A Dict containing the resulting features and fields.
# Usage Example>>>flyr_item=gis.content.search("*","Feature Layer")[0]>>>flyr=flyr_item.layers[0]>>>qy_result=flyr.query_date_bins(bin_field="boundary",bin_specs={"calendarBin":{"unit":"day","timezone":"America/Los_Angeles","offset":{"number":8,"unit":"hour"}}},out_statistics=[{"statisticType":"count","onStatisticField":"objectid","outStatisticFieldName":"item_sold_count"},{"statisticType":"avg","onStatisticField":"price","outStatisticFieldName":"avg_daily_revenue "}],time=[1609516800000,1612195199999])>>>qy_result{"features":[{"attributes":{"boundary":1609516800000,"avg_daily_revenue":300.40,"item_sold_count":79}},{"attributes":{"boundary":1612108800000,"avg_daily_revenue":null,"item_sold_count":0}}],"fields":[{"name":"boundary","type":"esriFieldTypeDate"},{"name":"item_sold_count","alias":"item_sold_count","type":"esriFieldTypeInteger"},{"name":"avg_daily_revenue","alias":"avg_daily_revenue","type":"esriFieldTypeDouble"}],"exceededTransferLimit":false}
- query_related_records(object_ids:str,relationship_id:str,out_fields:str='*',definition_expression:str|None=None,return_geometry:bool=True,max_allowable_offset:float|None=None,geometry_precision:int|None=None,out_wkid:int|None=None,gdb_version:str|None=None,return_z:bool=False,return_m:bool=False,historic_moment:int|datetime|None=None,return_true_curve:bool=False)
The
query_related_records
operation is performed on aFeatureLayer
resource. The result of this operation are feature sets groupedby source layer/table object IDs. Each feature set containsFeature objects including the values for the fields requested bythe user. For related layers, if you request geometryinformation, the geometry of each feature is also returned inthe feature set. For related tables, the feature set does notinclude geometries.Note
See the
query
method for a similar function.Parameter
Description
object_ids
Required string. The object IDs of the table/layer to be queried
relationship_id
Required string. The ID of the relationship to be queried.
out_fields
Required string. the list of fields from the related table/layerto be included in the returned feature set. This list is a commadelimited list of field names. If you specify the shape field in thelist of return fields, it is ignored. To request geometry, setreturn_geometry to true. You can also specify the wildcard “*” asthe value of this parameter. In this case, the results will includeall the field values.
definition_expression
Optional string. The definition expression to be applied to therelated table/layer. From the list of objectIds, only those recordsthat conform to this expression are queried for related records.
return_geometry
Optional boolean. If true, the feature set includes the geometryassociated with each feature. The default is true.
max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation. The max_allowable_offset is in the units ofthe outSR. If out_wkid is not specified, then max_allowable_offsetis assumed to be in the unit of the spatial reference of the map.
geometry_precision
Optional integer. This option can be used to specify the number ofdecimal places in the response geometries.
out_wkid
Optional Integer. The spatial reference of the returned geometry.
gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer queried istrue.
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is false.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
historic_moment
Optional Integer/datetime. The historic moment to query. This parameterapplies only if the supportsQueryWithHistoricMoment property of thelayers being queried is set to true. This setting is provided in thelayer resource.
If historic_moment is not specified, the query will apply to thecurrent features.
Syntax: historic_moment=<Epoch time in milliseconds>
return_true_curves
Optional boolean. Optional parameter that is false by default. Whenset to true, returns true curves in output geometries; otherwise,curves are converted to densified
Polyline
orPolygon
objects.- Returns:
Dictionary of the query results
# Usage Example:# Query returning the related records for a feature with objectid value of 2,# returning the values in the 6 attribute fields defined in the `field_string`# variable:>>>field_string="objectid,attribute,system_name,subsystem_name,class_name,water_regime_name">>>rel_records=feat_lyr.query_related_records(object_ids="2",relationship_id=0,out_fields=field_string,return_geometry=True)>>>list(rel_records.keys())['fields','relatedRecordGroups']>>>rel_records["relatedRecordGroups"][{'objectId':2,'relatedRecords':[{'attributes':{'objectid':686,'attribute':'L1UBHh','system_name':'Lacustrine','subsystem_name':'Limnetic','class_name':'Unconsolidated Bottom','water_regime_name':'Permanently Flooded'}}]}]
- query_top_features(top_filter:dict[str,str]|None=None,where:str|None=None,objectids:list[str]|None=None,start_time:datetime|None=None,end_time:datetime|None=None,geometry_filter:GeometryFilter|None=None,out_fields:str='*',return_geometry:bool=True,return_centroid:bool=False,max_allowable_offset:float|None=None,out_sr:dict[str,int]|str|None=None,geometry_precision:int|None=None,return_ids_only:bool=False,return_extents_only:bool=False,order_by_field:str|None=None,return_z:bool=False,return_m:bool=False,result_type:str|None=None,as_df:bool=True)
The
query_top_features
is performed on aFeatureLayer
. This operation returns afeature set or spatially enabled dataframe based on the top features by order within a group. For example, whenquerying counties in the United States, you want to return the top five counties by population ineach state. To do this, you can usequery_top_features
to group by state name, order by desc onthe population and return the first five rows from each group (state).The
top_filter
parameter is used to set the group by, order by, and count criteria used ingenerating the result. The operation also has many of the same parameters (for example, whereand geometry) as the layer query operation. However, unlike the layer query operation,query_top_features
does not support parameters such as outStatistics and its related parametersor return distinct values. Consult theadvancedQueryCapabilities
layer property for more details.If the feature layer collection supports thequery_top_features operation, it will include“supportsTopFeaturesQuery”: True, in the
advancedQueryCapabilities
layer property.Note
See the
query
method for a similar function.Parameter
Description
top_filter
Required Dict. Thetop_filter define the aggregation of the data.
groupByFields define the field or fields used to aggregate
your data.
topCount defines the number of features returned from the top
features query and is a numeric value.
orderByFields defines the order in which the top features will
be returned. orderByFields can be specified ineither ascending (asc) or descending (desc)order, ascending being the default.
- Example: {“groupByFields”: “worker”, “topCount”: 1,
“orderByFields”: “employeeNumber”}
where
Optional String. A WHERE clause for the query filter. SQL ‘92 WHEREclause syntax on the fields in the layer is supported for most datasources.
objectids
Optional List. The object IDs of the layer or table to be queried.
start_time
Optional Datetime. The starting time to query for.
end_time
Optional Datetime. The end date to query for.
geometry_filter
Optional from arcgis.geometry.filter. Allows for the information tobe filtered on spatial relationship with another geometry.
out_fields
Optional String. The list of fields to include in the return results.
return_geometry
Optional Boolean. If False, the query will not return geometries.The default is True.
return_centroid
Optional Boolean. If True, the centroid of the geometry will beadded to the output.
max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation.The max_allowable_offset is in the units of out_sr. If out_sr is notspecified, max_allowable_offset is assumed to be in the unit of thespatial reference of the layer.
out_sr
Optional Integer. The WKID for the spatial reference of the returnedgeometry.
geometry_precision
Optional Integer. This option can be used to specify the number ofdecimal places in the response geometries returned by the queryoperation.This applies to X and Y values only (not m or z-values).
return_ids_only
Optional boolean. Default is False. If true, the response onlyincludes an array of object IDs. Otherwise, the response is afeature set.
return_extent_only
Optional boolean. If true, the response only includes the extent ofthe features that would be returned by the query. IfreturnCountOnly=true, the response will return both the count andthe extent.The default is false. This parameter applies only if thesupportsReturningQueryExtent property of the layer is true.
order_by_field
Optional Str. Optional string. One or more field names on which thefeatures/records need to be ordered. Use ASC or DESC for ascendingor descending, respectively, following every field to control theordering.example: STATE_NAME ASC, RACE DESC, GENDER
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is False.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
result_type
Optional String. The result_type can be used to control the numberof features returned by the query operation.Values: none | standard | tile
as_df
Optional Boolean. If False, the result is returned as a FeatureSet.If True (default) the result is returned as a spatially enabled dataframe.
- Returns:
Default is a pd.DataFrame, but when
`as_df=False`
returns aFeatureSet
.If`return_count_only=True`
, the return type is Integer.If`return_ids_only=True`
, a list of value is returned.
- propertyrenderer
Get/Set the Renderer of the Feature Layer.
Parameter
Description
value
Required dict.
Note
When set, this overrides the default symbology when displaying it on a webmap.
- Returns:
`InsensitiveDict`
: A case-insensitivedict
like object used to update and alter JSONA varients of a case-less dictionary that allows for dot and bracket notation.
- propertytime_filter
The
time_filter
method is used to set a time filter instead of querying time-enabled mapservice layers or time-enabled feature service layers, a time filtercan be specified. Time can be filtered as a single instant or byseparating the two ends of a time extent with a comma.Note
The
time_filter
method is supported starting at Enterprise 10.7.1+.Input
Description
value
Required Datetime/List Datetime. This is a singleor list of start/stop date.
- Returns:
A string of datetime values as milliseconds from epoch
- update_metadata(file_path:str)
The
update_metadata
updates aFeatureLayer
metadata from an xml file.Parameter
Description
file_path
Required String. The path to the .xml file that contains the metadata.
- Returns:
A boolean indicating success (True), or failure (False)
- validate_sql(sql:str,sql_type:str='where')
The
validate_sql
operation validates anSQL-92
expression or WHEREclause.Thevalidate_sql
operation ensures that anSQL-92
expression, suchas one written by a user through a user interface, is correctbefore performing another operation that uses the expression.Note
For example,
validateSQL
can be used to validate information that issubsequently passed in as part of the where parameter of the calculate operation.validate_sql
also prevents SQL injection. In addition, all tableand field names used in the SQL expression or WHERE clause arevalidated to ensure they are valid tables and fields.Parameter
Description
sql
Required String. The SQL expression of WHERE clause to validate.Example: “Population > 300000”
sql_type
- Optional String. Three SQL types are supported in validate_sql
where(default)
- Represents the custom WHERE clause the usercan compose when querying a layer or using calculate.expression
- Represents an SQL-92 expression. Currently,expression is used as a default value expression when adding anew field or using the calculate API.statement
- Represents the full SQL-92 statement that can bepassed directly to the database. No current ArcGIS REST APIresource or operation supports using the full SQL-92 SELECTstatement directly. It has been added to the validateSQL forcompleteness.Values:where | expression | statement
- Returns:
A JSON Dictionary indicating ‘success’ or ‘error’
FeatureLayerCollection
- classarcgis.features.FeatureLayerCollection(url,gis=None)
A
FeatureLayerCollection
is the Python API representation of aFeature Service.Namely it is a collection offeaturelayers
andtables
with the associated relationships among the records.Instances of a
FeatureLayerCollection
can be obtainedusing the
fromitem()
methodby initializing an object using the feature service url
# Using the container property>>>fromarcgis.gisimportGIS>>>gis=GIS(profile="your_organization_profile")>>>flyr_item=gis.content.search("storm damage","Feature Layer")[0]>>>flc=flyr_item.layers[0].container>>>flc<FeatureLayerCollectionurl:"https://services8.arcgis.com/<org_id>/arcgis/rest/services/<service_name>/FeatureServer"># Using the fromitem method>>>fromarcgis.featuresimportFeatureLayerCollection>>>flyr_item=gis.content.search("storm damage","Feature Layer)[0]>>>flc=FeatureLayerCollection.fromitem(flyr_item)<FeatureLayerCollectionurl:"https://services8.arcgis.com/<org_id>/arcgis/rest/services/<service_name>/FeatureServer"># Initializing from a service url>>>fromarcgis.gisimportGIS>>>fromarcgis.featuresimportFeatureLayerCollection>>>gis=GIS(profile="your_organization_profile")>>>fs_url="https://services7.arcgis.com/<org_id>/arcgis/rest/services/<service_name>/FeatureServer">>>flc=FeatureLayerCollection(fs_url,gis)<FeatureLayerCollectionhttps://services7.arcgis.com/<org_id>/arcgis/rest/services/<service_name>/FeatureServer>
The
manager
property accesses theFeatureLayerCollectionManager
object whichcan be used to configure and manage the service.If the feature service isconfigured for synchronization,thereplicas property will be available to return a
SyncManager
object to manage thatfunctionality.Note
You can use the
layers
andtables
property to get to the individual layers and tables in thisfeature layer collection.- extract_changes(layers:list[int],servergen:list[int]=None,layer_servergen:list[dict[str,Any]]=None,queries:dict[str,Any]|None=None,geometry:Geometry|dict[str,int]|None=None,geometry_type:str|None=None,in_sr:int|dict[str,Any]|None=None,version:str|None=None,return_inserts:bool=False,return_updates:bool=False,return_deletes:bool=False,return_ids_only:bool=False,return_extent_only:bool=False,return_attachments:bool=False,attachments_by_url:bool=False,data_format:str='json',change_extent_grid_cell:str|None=None,return_geometry_updates:bool|None=None,fields_to_compare:list|None=None,out_sr:int|None=None)
A method to query for changes that have been made to the layers andtables in a feature service.
To verify whether a feature service is configured to send responses aboutthe features that have changed within its layers, query the service fortheChangeTracking capability:
# Get the capabilities a feature service is configured with>>>fromarcgis.gisimportGIS>>>gis=GIS(profile="your_organization_profile")>>>flyr_item=gis.content.search("my_feature_layer","Feature Layer")[0]# Initialize a FeatureLayerCollection object from a layer>>>flc=flyr_item.layers[0].container>>>flc.properties.capabilities'Create,Delete,Query,Update,Editing,Extract,ChangeTracking'
Change tracking can be enabled for ArcGIS Online hosted feature servicesas well as enterprise-geodatabase based ArcGIS Enterprise services.
Note
For Enterprise geodatabase based feature services publishedfrom ArcGIS Pro 2.2 or higher, the
ChangeTracking
capabilityrequires all layers and tables to be either archive enabled orbranch versioned and have globalid columns.Parameter
Description
layers
Required List. The list of layers (by index value) and tables toinclude in the output.
# Get layer index values>>>fromarcgis.gisimportFeatureLayerCollection>>>flyr_item=gis.content.get("<>flyr_item_id>")>>>flc=FeatureLayerCollection(flyr_item,gis)>>>forflyr_objinflc.layers:>>>print(f"{flyr_obj.properties.id<3}{lfyr_obj.properties.name}")0Airports1Roads2Railroads
servergen
Required integer (whenlayer_servergen argument not present).Introduced at 11.0, this argument provides the server generationnumbers to apply to all layers included in the layers parameter fromwhich to return changes.
Either a single generation value, or a pair of generation values canbe provided.
If a single value is provided, all changes that have happenedsince that generation are returned.
If a pair of values are provided, the changes that havehappened between the first generation (the minimum value) and up toand including the second generation (the maximum value) value arereturned. The first value in the pair is expected to be the smallervalue.
Query the
FeatureLayerCollection
properties to verify whether the feature service supportsthis capability. If thesupportServerGens property in theextractChangesCapabilities property group is set totrue, thecapability is present.# Determine whether parameter is supported>>>fromarcgis.gisimportGIS>>>gis=GIS(profile="your_organizaation_profile")>>>flyr_item=gis.content.get("<item_id>")>>>flc_object=flyr_item.layers[0].container>>>flc_object.properties.get("extractChangesCapabilities","no support"){...'supportsServerGens':True,...}
Note
Either theservergen orlayer_servergen argument must beprovided with this method.
You can get the latest generation numbers from thechangeTrackingInfoproperty of the feature service:
>>>flc_obj.properties.changeTrackingInfo{ "lastSyncDate": 1706901271525, "layerServerGens": [ { "id": 0, "minServerGen": 594109, "serverGen": 594109 }, { "id": 1, "minServerGen": 594109, "serverGen": 594109 } ]}
layer_servergen
Required list (ifservergen argument not provided) of generationnumbers for each layer to return changes. Use thechangeTrackingInfoinformation to get values:
# Get change tracking info>>>flc_obj.properties.changeTrackingInfo{"lastSyncDate":1706901271525,"layerServerGens":[{"id":0,"minServerGen":594109,"serverGen":594109},{"id":1,"minServerGen":594109,"serverGen":594109}]}
minServerGen - It is the minimum generation number of the serverdata changes.
serverGen - It is the current server generation number of thechanges. Every changed feature has a version or a generation numberthat is changed every time the feature is updated.
Note
These values may be identical.
The argument format should be a list of dictionaries whose keys are:
id - values is the index position of the layer within the feature
serverGen - value is the generation number after which to get the changes
# Usage Example:>>>flc.extract_changes(...layer_servergen=[{"id":0,"serverGen":594109},{"id":1,"serverGen":594109}],...)
queries
Optional Dictionary. In addition to thelayers andgeometryparameters, thequeries parameter can be used to further definewhat changes to return. This parameter allows you to set queryproperties on a per-layer or per-table basis. If a layer’s ID ispresent in thelayers argument and missing fromqueries,the layer’s changed features that intersect with thegeometryargument are returned.
The key-value options for the dictinary are:
where
- Defines an attribute query for a layer or table. Thedefault is no where clause.useGeometry
- Determines whether or not to apply thegeometryfor the layer. The default isTrue. If set toFalse, featuresfrom the layer that intersect the geometry are not added.includeRelated
- Determines whether or not to add relatedrows. The default isTrue and honored only whenqueryOption=None.This is only applicable if your data has relationship classes.Relationships are only processed in a forward direction from originto destination.queryOption
- Defines whether or how filters will be appliedto a layer. The queryOption was added in 10.2. See theCompatibility notes topicfor more information.Valid values are:
None
useFilter
all
. See also thelayerQueries column in the Request Parametersin theExtract Changes (Feature Service) helpfor details and code samples.
Note
Info on
queryOption
key values:If the value isNone and the layer participates in a relationship:
If
includeRelated
isFalse, no related features are returned.If
includeRelated
isTrue, features in this layer (that are related tothe features in other layers) are returned.
If value is
useFilter
, features that satisfy filtering based ongeometry andwhere
are returned.includeRelated
is ignored.
# Usage Example:>>>flc_obj.extract_changes(...queries={"0":{"where":"FID_1 > 300","useGeometry":"true","includeRelated":"false","queryOption":"useFilter"},"1":{"where":"SURFACE='mixed concrete'","useGeometry":"true"}},...)
geometry
Optional
Geometry
orEnvelope
object to apply as the spatial filter for the changes. All the changedfeatures intersecting this geometry will be returned.Note
Forenvelope andpoint geometries, you can specify the geometrywith a simple comma-separated syntax instead of a json object.
geometry_type
Optional String. The type of geometry specified by the geometryparameter. The geometry type can be an envelope, point, line orpolygon. The default geometry type is an envelope.
Values:
esriGeometryPoint
esriGeometryMultipoint
esriGeometryPolyline
esriGeometryPolygon
esriGeometryEnvelope
in_sr
Optional Integer. Thewkid value of the input geometry spatialreference. SeeCoordinate systems PDFsfor complete list of available values.
out_sr
Optional Integer. Thewkid for the the spatial reference of thegeometries in the returned changes. SeeCoordinate systems PDFsfor complete list of available values.
version
Optional String. Ifbranch versioning is enabled,and utilized with the service, a user can specify the verion nameto extract changes from.
return_inserts
Optional Boolean,Required if neitherreturn_updates norreturn_deletes provided. IfTrue, newly inserted features willbe returned. The default isFalse.
return_updates
Optional Boolean.Required if neitherreturn_inserts norreturn_deletes provided.IfTrue, updated features will be returned.The default isFalse.
return_deletes
Optional Boolean.Required if neitherreturn_inserts norreturn_updates provided. IfTrue, deleted features will bereturned. The default isFalse.
return_ids_only
Optional Boolean. IfTrue, the response includes a list of objectIDs only. The default isFalse.
return_extent_only
Option Boolean. IfTrue, only the extent of the changes isreturned. The default isFalse.
return_attachments
Optional Boolean. IfTrue, attachment changes are returned in theresponse. Otherwise, attachments are not included. The default isFalse. This parameter is only applicable if the feature service hasattachments.
attachments_by_url
Optional Boolean. IfTrue, a reference to a URL will be providedfor each attachment returned. Otherwise, attachments are embedded inthe response. The default isTrue.
data_format
Optional String. The format of the changes returned in the response.The default isjson. Values:
sqllite
json
change_extent_grid_cell
Optional String. To optimize localizing changes extent, the valueofmedium is an 8x8 grid that bound the changes extent.
Note
Used only whenreturn_extent_only isTrue. Default isNone.
Values:
None
large
medium
small
return_geometry_updates
Optional Boolean. IfTrue, the response includes a‘hasGeometryUpdates’ property set as true for each layer withupdates that have geometry changes. The default isFalse.
If a layer’s edits include only inserts, deletes, or updates tofields other than geometry, hasGeometryUpdates is not set or isreturned as false. When a layer has multiple rows with updates,only one needs to include a geometry changes forhasGeometryUpdates to be set as true.
fields_to_compare
Optional List. Introduced at 11.0. This parameter allows you todetermine if any list of fields has been updated. The acceptedvalues for this parameter is a list of fields you want to evaluate.The response returns a json array calledfieldUpdates (accessedas a Python list) which includes rows that contain any updates madeto the specified fields. An empty list is returned if no updatesoccurred in the specified fields.
- Returns:
A dictionary whose keys vary depending upon input arguments of method.
#Usage Example for extracting changes to specific feature layers in a hosted Feature Layer item>>>fromarcgis.gisimportGIS>>>fromarcgis.featuresimportFeatureLayerCollection>>>gis=GIS(profile="your_online_profile")# Search for the Feature Layer item>>>fl_item=gis.content.search('title:"my_feature_layer" type:"Feature Layer"')[0]# Initialize a FeatureLayerCollection object from the item>>>flc=FeatureLayerCollection.fromitem(fl_item,gis)# Extract the changes from the specific layers>>>deltas=flc.extract_changes(layers=[0,1,2],layer_servergen=[{"id":0,"serverGen":594109},{"id":1,"serverGen":594109},{"id":2,"serverGen":594109}],return_inserts=True,return_updates=True,return_deletes=True)>>>deltas{'layerServerGens':[{'id':0,'serverGen':594249},{'id':1,'serverGen':594249},{'id':2,'serverGen':594249}],'transportType':'esriTransportTypeUrl','responseType':'esriDataChangesResponseTypeEdits','edits':[{'id':0,'features':{'adds':[{'geometry':{'x':49949.824500000104,'y':90360.44769999944},'attributes':{'OBJECTID':401,'GlobalID':'8E4CD21D-C48C-4183-9AEC-3F2A2D0912CE','FID_1':401,'NAME':'Airport XTL'}},{'geometry':{'x':56948.30519999936,'y':-74861.21529999934},'attributes':{'OBJECTID':402,'GlobalID':'8C692383-3D99-4F42-9C56-10C499277E1A','FID_1':402,'NAME':'Airport SNL'}}],'updates':[],'deletes':[]}},{'id':1,'features':{'adds':[{'geometry':{'paths':[[[134899.6895,19645.5379000008],...[127425.5678,29965.8258999996],[126931.386600001,30593.6698000003]]]},'attributes':{'OBJECTID':4518,'GlobalID':'AE01C888-305C-44D9-A954-8A25D2829408','FID_1':874569,'NAME':'GTM 9 Connector ','SURFACE':'concrete mixed'}}],'updates':[],'deletes':[]}},{'id':2,'features':{'adds':[],'updates':[{'geometry':{'paths':[[[167873.3979,48154.2501999997],...[173714.5682,45801.2599999998],[173828.3726,44921.8964000009]]]},'attributes':{'OBJECTID':2,'GlobalID':'260182EA-FE8C-4D7E-8371-0BF488CDF2C2','FID_1':2,'TYPE':1,'STATUS':1}}],'deletes':[]}}]}
- classmethodfromitem(item:Item)
The
fromitem
method is used to create aFeatureLayerCollection
from aItem
class.Parameter
Description
item
A required
Item
object. The item needed to convert toaFeatureLayerCollection
object.- Returns:
A
FeatureLayerCollection
object.
- propertymanager
A helper object to manage the
FeatureLayerCollection
,for example updating its definition.- Returns:
A
FeatureLayerCollectionManager
object
- query(layer_defs_filter:LayerDefinitionFilter|None=None,geometry_filter:GeometryFilter|None=None,time_filter:TimeFilter|None=None,return_geometry:bool=True,return_ids_only:bool=False,return_count_only:bool=False,return_z:bool=False,return_m:bool=False,out_sr:int|None=None)
Queries the current
FeatureLayerCollection
based onsql
statement.Parameter
Description
time_filter
Optional list. The format is of[<startTime>, <endTime>] usingdatetime.date, datetime.datetime or timestamp in milliseconds.Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp inmilliseconds
geometry_filter
Optional from arcgis.geometry.filter. Allows for the information tobe filtered on spatial relationship with another geometry.
layer_defs_filter
Optional Layer Definition Filter.
return_geometry
Optional boolean. If true, geometry is returned with the query.Default is true.
return_ids_only
Optional boolean. Default is False. If true, the response onlyincludes an array of object IDs. Otherwise, the response is afeature set.
return_count_only
Optional boolean. If true, the response only includes the count(number of features/records) that would be returned by a query.Otherwise, the response is a feature set. The default is false. Thisoption supersedes the returnIdsOnly parameter. IfreturnCountOnly = true, the response will return both the count andthe extent.
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is False.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
out_sr
Optional Integer. The
WKID
for the spatial reference of the returnedgeometry.- Returns:
A
FeatureSet
of the queried Feature Layer Collection unlessreturn_count_only
orreturn_ids_only
is True.
- query_data_elements(layers:list)→dict
Thequery_data_elements provides access to valuable informationfor datasets exposed through a feature service such as a featurelayer, a table or a utility network layer. The response isdependent on the type of layer that is queried.
Parameter
Description
layers
Required list. Array of layerIds for which to get the data elements.
- Returns:
dict
- query_domains(layers:tuple|list[int])
Returns full domain information for the domainsreferenced by the layers in the
FeatureLayerCollection
. Thisoperation is performed on a feature layer collection. The operationtakes an array of layer IDs and returns the set of domains referencedby the layers.Note
See the
query
method for a similar function.Note
Only arcobject Feature Services support this operation. If the service supports this operation, thenthesupportsQueryDomains property in the service properties is True. If this value is False or notpresent, then the service cannot use this operation. In addition, this is only availabel for arcobject andhosted Feature Services in Enterprise, not for ArcGIS Online.
Parameter
Description
layers
Required List. An array of layers. The set of domains to return isbased on the domains referenced by these layers. Example: [1,2,3,4]
- Returns:
List of dictionaries
- query_related_records(object_ids:str,relationship_id:str,out_fields:str|list[str]='*',definition_expression:str|None=None,return_geometry:bool=True,max_allowable_offset:float|None=None,geometry_precision:int|None=None,out_wkid:int|None=None,gdb_version:str|None=None,return_z:bool=False,return_m:bool=False)
The
query_related_records
operation is performed on aFeatureLayerCollection
resource. The result of this operation are feature sets groupedby sourceFeatureLayer
/Table
object IDs.Each feature set containsFeature
objects including the values for the fieldsrequested by theUser
. For related layers, if you request geometryinformation, the geometry of each feature is also returned inthe feature set. For related tables, the feature set does notinclude geometries.Note
See the
query
method for a similar function.Parameter
Description
object_ids
Optional string. the object IDs of the table/layer to be queried.
relationship_id
Optional string. The ID of the relationship to be queried.
out_fields
Optional string.the list of fields from the related table/layerto be included in the returned feature set. This list is a commadelimited list of field names. If you specify the shape field in thelist of return fields, it is ignored. To request geometry, setreturn_geometry to true. You can also specify the wildcard “*” as thevalue of this parameter. In this case, the results will include allthe field values.
definition_expression
Optional string. The definition expression to be applied to therelated table/layer. From the list of objectIds, only those recordsthat conform to this expression are queried for related records.
return_geometry
Optional boolean. If true, the feature set includes the geometryassociated with each feature. The default is true.
max_allowable_offset
Optional float. This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation. The max_allowable_offset is in the units ofthe outSR. If outSR is not specified, then max_allowable_offset isassumed to be in the unit of the spatial reference of the map.
geometry_precision
Optional integer. This option can be used to specify the number ofdecimal places in the response geometries.
out_wkid
Optional integer. The spatial reference of the returned geometry.
gdb_version
Optional string. The geodatabase version to query. This parameterapplies only if the isDataVersioned property of the layer queried istrue.
return_z
Optional boolean. If true, Z values are included in the results ifthe features have Z values. Otherwise, Z values are not returned.The default is false.
return_m
Optional boolean. If true, M values are included in the results ifthe features have M values. Otherwise, M values are not returned.The default is false.
- Returns:
Dictionary of query results
- propertyrelationships
Gets relationship information forthe layers and tables in the
FeatureLayerCollection
object.The relationships resource includes information about relationshiprules from the back-end relationship classes, in addition to therelationship information already found in the individual
FeatureLayer
andTable
.Feature layer collections that support the relationships resourcewill have the “supportsRelationshipsResource”: true property ontheir properties.
- Returns:
List of Dictionaries
- upload(path:str|None,description:str|None=None,upload_size:int|None=None)
The
upload
method uploads a new item to the server.Note
Once the operation is completed successfully, item id of the uploaded item is returned.
Parameter
Description
path
Optional string. Filepath of the file to upload.
description
Optional string. Descriptive text for the uploaded item.
upload_size
Optional Integer. For large uploads, a user can specify the uploadsize of each part. The default is 1mb.
- Returns:
Item id of uploaded item
- propertyversions
Creates a
VersionManager
to create, update and use versions on aFeatureLayerCollection
.Note
If versioning is not enabled on the service, None is returned.
FeatureSet
- classarcgis.features.FeatureSet(features,fields=None,has_z=False,has_m=False,geometry_type=None,spatial_reference=None,display_field_name=None,object_id_field_name=None,global_id_field_name=None)
A
FeatureSet
is a set of features with information about theirfields
,fieldaliases
,geometrytype
,spatialreference
, and more.FeatureSets
are commonly used as input/output with severalGeoprocessingTools
, and can be the obtainedthrough thequery
methods of feature layers.A FeatureSet can be combined with a layer definition to compose a FeatureCollection.FeatureSet contains
Feature
objects, including the values for thefields requested by theUser
. For layers, if you request geometryinformation, the geometry of each feature is also returned in theFeatureSet. For tables, the FeatureSet does not include geometries.If a
SpatialReference
is not specified at theFeatureSet
level, theFeatureSet
will assume the SpatialReference of its first feature. IftheSpatialReference
of the first feature is also not specified, thespatial reference will be UnknownCoordinateSystem.- propertydf
Warning
deprecated in v1.5.0 please use
sdf
converts the FeatureSet to a Pandas dataframe. Requires pandas
- propertydisplay_field_name
Get/Set the
display
field for the Feature Set object.Parameter
Description
value
Required string.
- Returns:
A String
- propertyfields
Get/Set the fields in the FeatureSet
Parameter
Description
value
Required dict.
- Returns:
A dictionary
- staticfrom_arcpy(fs:arcpy.FeatureSet)→FeatureSet
Converts anarcpy FeatureSet to anarcgis FeatureSet
Parameter
Description
fs
Required arcpy.FeatureSet. The featureset object to consume.
- Returns:
A
FeatureSet
object
- staticfrom_dataframe(df)
The
from_dataframe
method creates aFeatureSet
objects from aPandas’ DataFrameParameter
Description
df
Required DataFrame.
- Returns:
A
FeatureSet
object
- staticfrom_dict(featureset_dict:dict[str,Any])
Creates a Feature Set objects from a dictionary.
Parameter
Description
featureset_dict
Required dict.Keys can include:‘fields’, ‘features’, ‘hasZ’, ‘hasM’, ‘geometryType’, ‘objectIdFieldName’,‘globalIdFieldName’, ‘displayFieldName’, ‘spatialReference’
- Returns:
- staticfrom_geojson(geojson)
Creates a Feature Set objects from a GEO JSON
FeatureCollection
objectParameter
Description
geojson
Required GEOJSON object
- Returns:
A
FeatureSet
object
- staticfrom_json(json_str:str)
Creates a Feature Set objects from a JSON string.
Parameter
Description
json_str
Required json style string.
- Returns:
A
FeatureSet
object
- propertygeometry_type
Get/Set the
Type
of the Feature Set object.Parameter
Description
value
Required string.Values: ‘Polygon’ | ‘Polyline’ | ‘Point’
- Returns:
A string representing the geometry type of the
FeatureSet
object
- propertyglobal_id_field_name
Get/Set the
globalID
field for the Feature Set object.Parameter
Description
value
Required string.
- Returns:
A string
- propertyhas_m
Get/Set the M-property of the Feature Set object.
Parameter
Description
value
Required bool.Values: True | False
- Returns:
The M-value of the
FeatureSet
object
- propertyhas_z
Get/Set the Z-property of the Feature Set object
Parameter
Description
value
Required bool.Values: True | False
- Returns:
The Z-value of the
FeatureSet
object
- propertyobject_id_field_name
Get/Set the object id field of the Feature Set object
Parameter
Description
value
Required string.
- Returns:
A string representing the object id field name
- save(save_location:str,out_name:str,encoding:str|None=None)
The
save
method saves a Feature Set object to aFeature
class on disk.Parameter
Description
save_location
Required string. Path to export the Feature Set to.
out_name
Required string. Name of the saved table.
encoding
Optional string. character encoding is used to represent arepertoire of characters by some kind of encoding system. Thedefault is None.
- Returns:
A string
# Obtain a feature from a feature layer:>>>feat_set=feature_layer.save(save_location="C:\ArcGISProjects">>>out_name="Power_Plant_Data")"C:\ArcGISProjects\Power_Plant_Data"
- propertysdf
Gets the Feature Set as a Spatially Enabled Pandas dataframe.
- Returns:
A Spatially EnabledPandas Dataframeobject
- propertyspatial_reference
Get/Set the Feature Set’s spatial reference
Parameter
Description
value
Required dict.(e.g. {“wkid” : 4326})
- Returns:
- to_dict()
Converts the Feature Set object to a Python dictionary.
- Returns:
A Python dictionary of the
FeatureSet
- propertyto_json
Gets the Feature Set object as a JSON string.
- Returns:
A JSON string of the
FeatureSet
- propertyvalue
Gets the Feature Set object as a dictionary.
- Returns:
A dictionary of the
FeatureSet
FeatureCollection
- classarcgis.features.FeatureCollection(dictdata)
FeatureCollection
is an object with a layer definition and aFeatureSet
.It is an in-memory collection of
Feature
objects with rendering information.Note
Feature Collections can be stored as
Item
objects in the GIS, added as layers to a map orscene, passed as inputs to feature analysis tools, and returned as results from feature analysis toolsif an output name for a feature layer is not specified when calling the tool.- staticfrom_featureset(fset:FeatureSet,symbol:dict[str,Any]|None=None,name:str|None=None)
Creates a
FeatureCollection
object from aFeatureSet
object.Parameter
Description
fset
Required
FeatureSet
object.symbol
Optional dict. Specify your symbol as a dictionary. Symbols for pointscan be picked from theEsri Symbol Page
If not specified, a default symbol will be created.
name
Optional String. The name of the feature collection. This is usedwhen feature collections are being persisted on a Map. If None isprovided, then a random name is generated. (New at 1.6.1)
- Returns:
A
FeatureCollection
object.
# Usage Example>>>feat_set=feature_layer.query(where="OBJECTID=1")>>>feat_collect=FeatureCollection.from_featureset(feat_set)>>>type(feat_collect)"acrgis.features.FeatureCollection"
- propertylayer
Deprecated since version 2.4.0:Removed in: 2.5.0. Use ‘properties’ instead.
Deprecated since version 2.4.0:Removed in: 2.5.0. Use ‘properties’ instead.
- propertyproperties
Returns a dictionary-like object of the current definition for theFeature Collection object. Each feature collection is comprised of a:
featureSet,
layerDefinition
popupInfo.
See thefeatureCollection Object Specificationfor full details.
Note
Theproperties andlayer property of a
FeatureCollection
return the same information.# Usage Example:>>>fromarcgis.gisimportGIS>>>gis=GIS(profile="your_online_profile")>>>fcolln_item=gis.content.search(query="*",item_type="Feature Collection")[0]>>>fcolln_obj=fcolln_item.layers[0]>>>list(fcolln_obj.properties.keys())['featureSet','layerDefinition','popupInfo']
- query()
Retrieves the data in this feature collection as a
FeatureSet
.Ex: FeatureCollection.query()Warning
Filtering by
whereclause
is not supported for feature collections.- Returns:
A
FeatureSet
object
GeoAccessor
- classarcgis.features.GeoAccessor(obj)
Adds a spatial namespace that performs spatial operations on the givenPandasDataFrame.The
GeoAccessor
class includes visualization, spatialindexing, IO and dataset level properties. TheGeoAccessor namespace is accessedas thespatial property on a Pandas Dataframe that has a geometry column.# Usage Example: Accessing the spatially enabled dataframe>>>fromarcgis.gisimportGIS>>>gis=GIS("your_organization_profile")>>>flyr_item=gis.content.get("<feature layer id>")>>>flyr=flyr_item.layers[0]>>>df=flyr.query(as_df=True)>>>df.spatial<arcgis.features.geo._accessor.GeoAccessorobjectat<mem_addr>>
Note
Setting the Geometry Engine:By default, the library used for spatial transformations (e.g., reading/writingshapefiles, file geodatabases, or spatial DataFrames) is determined by theavailable libraries in the environment. You can explicitly set the library usedfor certain spatial operations through an environment variable calledARCGIS_GEOMETRY_ENGINE. The variableMUST be set at the top of the script.The options available are:
shapefile - for thePython Shapefile Library (PyShp)A lightweight option that works well for simple shapefile operations but lacks advanced capabilitiesofgdal orarcpy.
arcpy - for the EsriArcPylibrary.Requires a license for use. Best for full compatibility with Esri’s ArcGIS ecosystem,including advanced geoprocessing tools.
gdal - for theOpen Source Geospatial Foundation gdal translatorlibrary. A good balance of performance and compatibility with multiple GIS formats. Idealfor working with large datasets and open-source workflows.
fiona - for thefiona simple feature data streaminglibrary. Can only be used to read in feature classes.
To set environment at the top of the script, add:
importosos.environ["ARCGIS_GEOMETRY_ENGINE"]="<engine of choice>"
Note
If you are using shapely in conjunction with shapefiles instead of arcpy or gdal, you will have todo all reprojections manually. Shapely does not support projections.
- propertyarea
The
area
method retrieves the total area of theGeoAccessor
dataframe.- Returns:
A float
>>>df.spatial.area143.23427
- propertybbox
The
bbox
property retrieves the total length of the dataframe- Returns:
>>>df.spatial.bbox{'rings' : [[[1,2], [2,3], [3,3],....]], 'spatialReference' {'wkid': 4326}}
- propertycentroid
The
centroid
method retrieves the centroid of the dataframe- Returns:
>>>df.spatial.centroid(-14.23427, 39)
- compare(other:GeoAccessor|DataFrame,match_field:str=None)
Compare the current spatially enabled DataFrame with another spatially enabled DataFrame and identify the differencesin terms of added, deleted, and modified rows based on a specified match field.
Parameter
Description
other
Required spatially enabled DataFrame (GeoAccessor object).
match_field
Optional string. The field to use for matching rows betweenthe DataFrames. The default will be the spatial column’s name.
- Returns:
A dictionary containing the differences between the two DataFrames:- ‘added_rows’: DataFrame representing the rows added in the other DataFrame.- ‘deleted_rows’: DataFrame representing the rows deleted from the current DataFrame.- ‘modified_rows’: DataFrame representing the rows modified between the DataFrames.
- distance_matrix(leaf_size=16,rebuild=False)
The
distance_matrix
creates a k-d tree to calculate the nearest-neighbor problem.Note
The
distance_matrix
method requires SciPy. Your environment must have either shapely or arcpy installed.Parameter
Description
leafsize
Optional Integer. The number of points at which the algorithmswitches over to brute-force. Default: 16.
rebuild
Optional Boolean. If True, the current KDTree is erased. If false,any KD-Tree that exists will be returned.
- Returns:
scipy’s KDTree class
- eq(other:GeoAccessor|DataFrame)
Check if two DataFrames are equal to each other. Equal meanssame shape and corresponding elements
- staticfrom_arrow(table:pyarrow.Table)→pd.DataFrame
Converts a Pandas DatFrame to an Arrow Table
Parameter
Description
table
Required pyarrow.Table. The Arrow Table to convert back into aspatially enabled dataframe.
- Returns:
pandas.DataFrame
- staticfrom_df(df,address_column='address',geocoder=None,sr=None,geometry_column=None)
The
from_df
creates a Spatially Enabled DataFrame from a dataframe with an address column.Parameter
Description
df
Required Pandas DataFrame. Source dataset
address_column
Optional String. The default is “address”. This is thename of a column in the specified dataframe that containsaddresses (as strings). The addresses are batch geocodedusing the GIS’s first configured geocoder and theirlocations used as the geometry of the spatial dataframe.Ignored if the ‘geometry_column’ is specified.
geocoder
Optional Geocoder. The geocoder to be used. If notspecified, the active GIS’s first geocoder is used.
sr
Optional integer. The WKID of the spatial reference.
geometry_column
Optional String. The name of the geometry column toconvert to the arcgis.Geometry Objects (new at version 1.8.1)
- Returns:
Spatially Enabled DataFrame
NOTE: Credits will be consumed for batch_geocoding, fromthe GIS to which the geocoder belongs.
- staticfrom_feather(path,spatial_column='SHAPE',columns=None,use_threads=True)
The
from-feather
method loads a feather-format object from the file path.Parameter
Description
path
String. Path object or file-like object. Any valid stringpath is acceptable. The string could be a URL. ValidURL schemes include http, ftp, s3, and file. For file URLs, a host isexpected. A local file could be:
file://localhost/path/to/table.feather
.If you want to pass in a path object, pandas accepts any
os.PathLike
.By file-like object, we refer to objects with a
read()
method,such as a file handler (e.g. via builtinopen
function)orStringIO
.spatial_column
Optional String. The default isSHAPE. Specifies the columncontaining the geo-spatial information.
columns
Sequence/List/Array. The default isNone. If notprovided, all columns are read.
use_threads
Boolean. The default isTrue. Whether to parallelizereading using multiple threads.
- Returns:
A Pandas DataFrame (pd.DataFrame)
- staticfrom_featureclass(location,**kwargs)
The
from_featureclass
creates a Spatially enabledpandas.DataFrame from aFeatures
class.Note
Null integer values will be changed to 0 when using shapely insteadof ArcPy due to shapely conventions.With ArcPy null integer values will remain null.
Note
The geometry engine used for this operation can be set with thetheARCGIS_GEOMETRY_ENGINE environment variable. Available options:
“shapefile”
“gdal”
“arcpy”
“fiona”
If not set, the first available library in the environment will be used.
Parameter
Description
location
Required string or pathlib.Path. Full path to the file.
Optional parameters when ArcPy library is available in the current environment:
Optional Argument
Description
sql_clause
sql clause to parse data down. To learn more seeArcPy Search Cursor
where_clause
where statement. To learn more seeArcPy SQL reference
fields
list of strings specifying the field names.
spatial_filter
AGeometry object that will filter the results. This requiresarcpy orgdal to work.
sr
A Spatial reference to project (or transform) output GeoDataFrameto. This requiresarcpy to work.
datum_transformation
Used in combination with ‘sr’ parameter. if the spatial reference ofoutput GeoDataFrame and input data do not share the same datum,an appropriate datum transformation should be specified.To Learn more see [Geographic datum transformations](https://pro.arcgis.com/en/pro-app/help/mapping/properties/geographic-coordinate-system-transformation.htm)This requiresarcpy to work.
Optional Parameters are not supported for URL based resources
- Returns:
A pandas.core.frame.DataFrame object
- staticfrom_geodataframe(geo_df,inplace=False,column_name='SHAPE')
The
from_geodataframe
loads a Geopandas GeoDataFrame into an ArcGIS Spatially Enabled DataFrame.Note
The
from_geodataframe
method requires geopandas library be installed in current environment.Parameter
Description
geo_df
GeoDataFrame object, created using GeoPandas library
inplace
- Optional Bool. When True, the existing GeoDataFrame is spatially
enabled and returned. When False, a new Spatially EnabledDataFrame object is returned. Default is False.
column_name
- Optional String. Sets the name of the geometry column. Default
isSHAPE.
- Returns:
A Spatially Enabled DataFrame.
- staticfrom_layer(layer)
The
from_layer
method imports aFeatureLayer
to a Spatially Enabled DataFrameNote
This operation converts a
FeatureLayer
orTable
to a Pandas’ DataFrameParameter
Description
layer
Required FeatureLayer or Table. The service to convertto a Spatially enabled DataFrame.
Usage:
>>>fromarcgis.featuresimportFeatureLayer>>>mylayer=FeatureLayer(("https://sampleserver6.arcgisonline.com/arcgis/rest" "/services/CommercialDamageAssessment/FeatureServer/0"))>>>df=from_layer(mylayer)>>>print(df.head())
- Returns:
A Pandas’DataFrame
- staticfrom_parquet(path:str,columns:list=None,**kwargs)→DataFrame
Load a Parquet object from the file path, returning a Spatially Enabled DataFrame.
You can read a subset of columns in the file using the
columns
parameter.However, the structure of the returned Spatially Enabled DataFrame will depend on whichcolumns you read:if no geometry columns are read, this will raise a
ValueError
- youshould use the pandasread_parquet method instead.if the primary geometry column saved to this file is not included incolumns, the first available geometry column will be set as the geometrycolumn of the returned Spatially Enabled DataFrame.
Requires ‘pyarrow’.
Added in version arcgis:1.9
Parameter
Description
path
Required String. path object
columns
Optional List[str]. The defaulti sNone. If not None, only thesecolumns will be read from the file. If the primary geometry columnis not included, the first secondary geometry read from the file willbe set as the geometry column of the returned Spatially EnabledDataFrame. If no geometry columns are present, a
ValueError
will be raised.kwargs
Optional dict. Any additional kwargs that can be given to thepyarrow.parquet.read_table method.
- Returns:
Spatially Enabled DataFrame
Examples
>>>df=pd.DataFrame.spatial.from_parquet("data.parquet")
Specifying columns to read:
>>>df=pd.DataFrame.spatial.from_parquet(..."data.parquet",...columns=["SHAPE","pop_est"]...)
- staticfrom_table(filename,**kwargs)
The
from_table
method allows aUser
to read from a non-spatial tableNote
The geometry engine used for this operation can be set with thetheARCGIS_GEOMETRY_ENGINE environment variable. Available options:
“shapefile”
“gdal”
“arcpy”
If not set, the first available library in the environment will be used.
Parameter
Description
filename
Required string or pathlib.Path. The path to thetable.
Keyword Arguments
Parameter
Description
fields
Optional List/Tuple. A list (or tuple) of fieldnames. For a single field, you can use a stringinstead of a list of strings.
Use an asterisk (*) instead of a list of fields ifyou want to access all fields from the input table(raster and BLOB fields are excluded). However, forfaster performance and reliable field order, it isrecommended that the list of fields be narrowed toonly those that are actually needed.
Geometry, raster, and BLOB fields are not supported.
where
Optional String. An optional expression that limitsthe records returned.
skip_nulls
Optional Boolean. This controls whether recordsusing nulls are skipped. Default is True.
null_value
Optional String/Integer/Float. Replaces null valuesfrom the input with a new value.
- Returns:
A Pandas DataFrame (pd.DataFrame)
- staticfrom_xy(df,x_column,y_column,sr=4326,z_column=None,m_column=None,**kwargs)
The
from_xy
method converts a Pandas DataFrame into a Spatially Enabled DataFrameby providing the X/Y columns.Parameter
Description
df
Required Pandas DataFrame. Source dataset
x_column
Required string. The name of the X-coordinate series
y_column
Required string. The name of the Y-coordinate series
sr
Optional int. The wkid number of the spatial reference.4326 is the default value.
z_column
Optional string. The name of the Z-coordinate series
m_column
Optional string. The name of the M-value series
kwargs
Description
oid_field
Optional string. If the value is provided the OID fieldwill not be converted from int64 to int32.
- Returns:
DataFrame
- propertyfull_extent
The
full_extent
method retrieves the extent of the DataFrame.- Returns:
A tuple
>>>df.spatial.full_extent(-118, 32, -97, 33)
- propertygeometry_type
The
geometry_type
property retrieves a list of Geometry Types for the DataFrame.- Returns:
A List
- propertyhas_m
The
has_m
property determines if the datasets haveM values- Returns:
A boolean indicatingM values (True), or not (False)
- propertyhas_z
The
has_z
property determines if the datasets haveZ values- Returns:
A boolean indicatingZ values (True), or not (False)
- insert_layer(feature_service:Item|str,gis=None,sanitize_columns:bool=False,service_name:str=None)
Creates a feature layer from the spatially enabled dataframe and adds (inserts)it to an existing feature service.
Note
Inserting table data is not supported for ArcGIS Enterprise deployments.
Note
The geometry engine used for this operation can be set with thetheARCGIS_GEOMETRY_ENGINE environment variable. Available options:
“shapefile”
“gdal”
“arcpy”
If not set, the first available library in the environment will be used.
Parameter
Description
feature_service
Required
Item
or Feature Service Id. Depictsthe feature service to which the layer will be added.gis
Optional
GIS
. The GIS object.sanitize_columns
Optional Boolean. If
True
, column names will be converted tostring, invalid characters removed and other performed. Thedefault isFalse
.service_name
Optional String. The name for the service that will be added to the
Item
The name cannot be used already or containspecial characters, spaces, or a number as the first character.- Returns:
The feature service item that was appended to.
- join(right_df,how='inner',op='intersects',left_tag='left',right_tag='right')
The
join
method joins the current DataFrame to another Spatially-Enabled DataFrame basedon spatial location based.Note
The
join
method requires the Spatially-Enabled DataFrame to be in the same coordinate systemParameter
Description
right_df
Required pd.DataFrame. Spatially enabled dataframe to join.
how
Required string. The type of join:
left - use keys from current dataframe and retains only current geometry column
right - use keys from right_df; retain only right_df geometry column
inner - use intersection of keys from both dfs and retain only current geometry column
op
Required string. The operation to use to perform the join.The default isintersects.
supported operations:intersects,within, andcontains
left_tag
Optional String. If the same column is in the left andright dataframe, this will append that string value tothe field.
right_tag
Optional String. If the same column is in the left andright dataframe, this will append that string value tothe field.
- Returns:
Spatially enabled Pandas’ DataFrame
- propertylength
The
length
method retrieves the total length of the DataFrame- Returns:
A float
>>>df.spatial.length1.23427
- overlay(sdf,op='union')
The
overlay
performs spatial operation operations on two spatially enabled dataframes.Note
The
overlay
method requires ArcPy or ShapelyParameter
Description
sdf
Required Spatially Enabled DataFrame. The geometry toperform the operation from.
op
Optional String. The spatial operation to perform. Theallowed value are: union, erase, identity, intersection.union is the default operation.
- Returns:
A Spatially enabled DataFrame (pd.DataFrame)
- plot(map_widget=None,**kwargs)
The
plot
draws the data on a map. The user can describe in simple terms how torenderer spatial data using symbol.Explicit Argument
Description
map_widget
optional
Map
object. This is the map to displaythe data on.renderer
optional renderer dataclass. This can be created from therenderers module in the arcgis.map module.
- project(spatial_reference,transformation_name=None)
The
project
method reprojects the who dataset into a newSpatialReference
.This is an inplace operation meaning that it will update the defined geometry column from theset_geometry
.Note
The
project
method requires ArcPy or pyproj v4.Parameter
Description
spatial_reference
Required
SpatialReference
. The new spatial reference.This can be a SpatialReference object or the coordinate system name.transformation_name
Optional String. The
geotransformation
name.- Returns:
A boolean indicating success (True), or failure (False)
- relationship(other,op,relation=None)
The
relationship
method allows for dataframe to dataframe comparison usingspatial relationships.Note
The return is a Pandas DataFrame (pd.DataFrame) that meet the operations’ requirements.
Parameter
Description
other
Required Spatially Enabled DataFrame. The geometry toperform the operation from.
op
Optional String. The spatial operation to perform. Theallowed value are: contains,crosses,disjoint,equals,overlaps,touches, or within.
contains - Indicates if the base geometry contains the comparison geometry.
crosses - Indicates if the two geometries intersect in a geometry of a lesser shape type.
disjoint - Indicates if the base and comparison geometries share no points in common.
equals - Indicates if the base and comparison geometries are of the same shape type and define the same set of points in the plane. This is a 2D comparison only; M and Z values are ignored.
overlaps - Indicates if the intersection of the two geometries has the same shape type as one of the input geometries and is not equivalent to either of the input geometries.
touches - Indicates if the boundaries of the geometries intersect.
within - Indicates if the base geometry contains the comparison geometry.
intersect - Indicates if the base geometry has an intersection of the other geometry.
Note - contains and within will lead to same results when performing spatial operations.
relation
Optional String. The spatial relationship type. Theallowed values are: BOUNDARY, CLEMENTINI, and PROPER.
BOUNDARY - Relationship has no restrictions for interiors or boundaries.
CLEMENTINI - Interiors of geometries must intersect. This is the default.
PROPER - Boundaries of geometries must not intersect.
This only applies to contains,
- Returns:
Spatially enabled DataFrame (pd.DataFrame)
- propertyrenderer
The
renderer
property defines the renderer for the Spatially-enabled DataFrame.Parameter
Description
value
Required dict. If none is given, then the value is reset
- Returns:
`InsensitiveDict`
: A case-insensitivedict
like object used to update and alter JSONA varients of a case-less dictionary that allows for dot and bracket notation.
- sanitize_column_names(convert_to_string=True,remove_special_char=True,inplace=False,use_snake_case=True)
The
sanitize_column_names
cleans column names by converting them to string, removing special characters,renaming columns without column names tononame
, renaming duplicates with integer suffixes and switchingspaces or Pascal or camel cases to Python’s favored snake_case style.Snake_casing gives you consistent column names, no matter what the flavor of your backend database iswhen you publish the DataFrame as a Feature Layer in your web GIS.
Parameter
Description
convert_to_string
Optional Boolean. Default is True. Converts column names to string
remove_special_char
Optional Boolean. Default is True. Removes any characters in columnnames that are not numeric or underscores. This also ensures columnnames begin with alphabets by removing numeral prefixes.
inplace
Optional Boolean. Default is False. If True, edits the DataFramein place and returns Nothing. If False, returns a new DataFrame object.
use_snake_case
Optional Boolean. Default is True. Makes column names lower case,and replaces spaces between words with underscores. If column namesare in PascalCase or camelCase, it replaces them to snake_case.
- Returns:
pd.DataFrame object if inplace=
False
. ElseNone
.
- select(other)
The
select
operation performs a dataset wideselection by geometricintersection. A geometry or another Spatially enabled DataFramecan be given andselect
will return all rows that intersect thatinput geometry. Theselect
operation uses a spatial index tocomplete the task, so if it is not built before the first run, thefunction will build a quadtree index on the fly.Note
The
select
method requires ArcPy or Shapely- Returns:
A Pandas DataFrame (pd.DataFrame, spatially enabled)
- set_geometry(col,sr=None,inplace=True)
The
set_geometry
method assigns the geometry column by name or by list.Parameter
Description
col
Required string, Pandas Series, GeoArray, list or tuple. If a string, thisis the name of the column containing the geometry. If a Pandas SeriesGeoArray, list or tuple, it is an iterable of Geometry objects.
sr
Optional integer or spatial reference of the geometries described inthe first parameter. If the geometry objects already have the spatialreference defined, this is not necessary. If the spatial reference forthe geometry objects is NOT define, it will default to WGS84 (wkid 4326).
inplace
Optional bool. Whether or not to modify the dataframe in place, or returna new dataframe. If True, nothing is returned and the dataframe is modifiedin place. If False, a new dataframe is returned with the geometry set.Defaults to True.
- Returns:
Spatially Enabled DataFrame or None
- sindex(stype='quadtree',reset=False,**kwargs)
The
sindex
creates a spatial index for the given dataset.Note
By default, the spatial index is a QuadTree spatial index.
r-tree indexes should be used for large datasets. This will allowusers to create very large out of memory indexes. To use r-tree indexes,the r-tree library must be installed. To do so, install via conda usingthe following command:conda install -c conda-forge rtree
- Returns:
A spatial index for the given dataset.
- propertysr
The
sr
property gets and sets theSpatialReference
of the dataframe.Can only be done with the ArcPy Geometry Engine.Parameter
Description
value
Spatial Reference
- to_arrow(index:bool=None)→pyarrow.Table
Converts a Pandas DatFrame to an Arrow Table
Parameter
Description
index
Optional Bool. If
True
, always include the dataframe’sindex(es) as columns in the file output.IfFalse
, the index(es) will not be written to the file.IfNone
, the index(ex) will be included as columns in the fileoutput exceptRangeIndex which is stored as metadata only.- Returns:
pyarrow.Table
- to_feature_collection(name=None,drawing_info=None,extent=None,global_id_field=None,sanitize_columns=False,**kwargs)
The
to_feature_collection
converts a spatially enabled a Pandas DataFrame to aFeatureCollection
.optional argument
Description
name
optional string. Name of the
FeatureCollection
drawing_info
Optional dictionary. This is the rendering information for aFeature Collection. Rendering information is a dictionary withthe symbology, labelling and other properties defined. See theRenderer Objectspage in the ArcGIS REST API for more information.
extent
Optional dictionary. If desired, a custom extent can beprovided to set where the map starts up when showing the data.The default is the full extent of the dataset in the SpatialDataFrame.
global_id_field
Optional string. The Global ID field of the dataset.
sanitize_columns
Optional Boolean. If True, column names will be converted to string,invalid characters removed and other checks will be performed. Thedefault is False.
- Returns:
A
FeatureCollection
object
- to_featureclass(location,overwrite=True,has_z=None,has_m=None,sanitize_columns=True)
The
to_featureclass
exports a spatially enabled dataframe to a feature class.Note
The geometry engine used for this operation can be set with thetheARCGIS_GEOMETRY_ENGINE environment variable. Available options:
“shapefile”
“gdal”
“arcpy”
If not set, the first available library in the environment will be used.
Parameter
Description
location
Required string. The output of the table.
overwrite
Optional Boolean. If True and if the feature class exists, it will bedeleted and overwritten. This is default. If False, the feature classand the feature class exists, and exception will be raised.
has_z
Optional Boolean. If True, the dataset will be forced to have Zbased geometries. If a geometry is missing a Z value when true, aRuntimeError will be raised. When False, the API will not use theZ value.
has_m
Optional Boolean. If True, the dataset will be forced to have Mbased geometries. If a geometry is missing a M value when true, aRuntimeError will be raised. When False, the API will not use theM value.
sanitize_columns
Optional Boolean. If True, column names will be converted to string,invalid characters removed and other checks will be performed. Thedefault is True.
- Returns:
A String
- to_featurelayer(title=None,gis=None,tags=None,folder=None,sanitize_columns=False,service_name=None,**kwargs)
The
to_featurelayer
method publishes a spatial dataframe to a newFeatureLayer
object.Note
Null integer values will be changed to 0 when using shapely insteadof ArcPy due to shapely conventions.With ArcPy null integer values will remain null.
Note
The geometry engine used for this operation can be set with thetheARCGIS_GEOMETRY_ENGINE environment variable. Available options:
“shapefile”
“gdal”
“arcpy”
If not set, the first available library in the environment will be used.
Parameter
Description
title
Optional string. The name of the service. If not provided, a randomstring is generated.
gis
Optional GIS. The GIS connection object
tags
Optional list of strings. A comma separated list of descriptivewords for the service.
folder
Optional string. Name of the folder where the feature layer itemand imported data would be stored.
sanitize_columns
Optional Boolean. If True, column names will be converted to string,invalid characters removed and other checks will be performed. Thedefault is False.
service_name
Optional String. The name for the service that will be added to the Item.Name cannot be used already and cannot contain special characters, spaces,or a numerical value as the first letter.
When publishing a Spatial Dataframe, additional options can be given:
Optional Arguments
Description
overwrite
Optional boolean. If True, the specified layer in theservice parameterwill be overwritten... note:
OverwritingtabledatainEnterpriseisnotcurrentlysupported.
service
Dictionary that is required ifoverwrite = True. Dictionary with twokeys: “FeatureServiceId” and “layers”.“featureServiceId” value is a string of the feature service id that the layerbelongs to.“layer” value is an integer depicting the index value of the layer tooverwrite.
Example:{“featureServiceId” : “9311d21a9a2047d19c0faaebd6f2cca6”, “layer”: 0}
- Returns:
A
FeatureLayer
object.
- to_featureset()
The
to_featureset
method converts a Spatially Enabled DataFrame object. to aFeatureSet
object.- Returns:
A
FeatureSet
object
- to_parquet(path:str,index:bool=None,compression:str='gzip',**kwargs)→str
Write a Spatially Enabled DataFrame to the Parquet format.
Any geometry columns present are serialized to WKB format in the file.
Requires ‘pyarrow’.
WARNING: this is an initial implementation of Parquet file support andassociated metadata. This is tracking version 0.4.0 of the metadataspecification at:https://github.com/geopandas/geo-arrow-spec
Added in version 2.1.0.
Parameter
Description
path
Required String. The save file path
index
Optional Bool. If
True
, always include the dataframe’sindex(es) as columns in the file output.IfFalse
, the index(es) will not be written to the file.IfNone
, the index(ex) will be included as columns in the fileoutput exceptRangeIndex which is stored as metadata only.compression
Optional string. {‘snappy’, ‘gzip’, ‘brotli’, None}, default ‘gzip’Name of the compression to use. Use
None
for no compression.**kwargs
Optional dict. Any additional kwargs that can be given to thepyarrow.parquet.write_table method.
- Returns:
string
- to_table(location,overwrite=True,**kwargs)
The
to_table
method exports a geo enabled dataframe to a file.Note
Null integer values will be changed to 0 when using shapely insteadof ArcPy due to shapely conventions.With ArcPy null integer values will remain null.
Note
The geometry engine used for this operation can be set with thetheARCGIS_GEOMETRY_ENGINE environment variable. Available options:
“gdal”
“arcpy”
If not set, the first available library in the environment will be used.
Parameter
Description
location
Required string. The output location for the table.
overwrite
Optional Boolean. If True and if the table exists, it will bedeleted and overwritten. This is default. If False, the table andthe table exists, and exception will be raised.
sanitize_columns
Optional Boolean. If True, column names will be converted tostring, invalid characters removed and other checks will beperformed. The default is True.
service_name
Optional String. The name for the service.
- Returns:
String
- propertytrue_centroid
The
true_centroid
property retrieves the true centroid of the DataFrame- Returns:
A
Geometry
object
>>>df.spatial.true_centroid(1.23427, 34)
- validate(strict=False)
The
validate
method determines if theGeoAccessor is Valid withGeometry
objects in all values- Returns:
A boolean indicating Success (True), or Failure (False)
- voronoi()
The
voronoi
method generates a voronoi diagram on the whole dataset.Note
If the
Geometry
object is not a:class:`~arcgis.geometry.Point then thecentroid is used for the geometry. The result is aPolygon
GeoArray Seriesthat matches 1:1 to the original dataset.Note
The
voronoi
method requires SciPy and either shapely or arcpy.- Returns:
A Pandas Series (pd.Series)
GeoSeriesAccessor
- classarcgis.features.GeoSeriesAccessor(obj)
- propertyJSON
The
JSON
method creates a JSON string out of theGeometry
object.- Returns:
Series of strings
- propertyWKB
The
WKB
method retrieves theGeometry
object as aWKB
- Returns:
A Series of Bytes
- angle_distance_to(second_geometry,method='GEODESIC')
The
angle_distance_to
method retrieves a tuple of angle and distance to another point using ameasurement method.Parameter
Description
second_geometry
Required Geometry. A
Geometry
object.method
Optional String.PLANAR measurements reflect the projection of geographicdata onto the 2D surface (in other words, they will not take intoaccount the curvature of the earth).GEODESIC,GREAT_ELLIPTIC, andLOXODROME measurement types may be chosen as an alternative, if desired.
- Returns:
A Series where each element is a tuple of angle and distance to another point using a measurement type.
- propertyarea
The
area
method retrieves theFeature
object’s area.- return:
A float in a series
- propertyas_arcpy
The
as_arcpy
method retrieves the features as an ArcPygeometryobject.- Returns:
An arcpy.geometry as a series
- propertyas_shapely
The
as_shapely
method retrieves the features as Shapely`Geometry <https://shapely.readthedocs.io/en/stable/manual.html#geometric-objects>`_- Returns:
shapely.Geometry objects in a series
- boundary()
The
boundary
method constructs the boundary of theGeometry
object.- Returns:
A Pandas Series of
Polyline
objects
- buffer(distance)
The
buffer
method constructs aPolygon
at a specified distance from theGeometry
object.Parameter
Description
distance
Required float. The buffer distance. The buffer distance is in thesame units as the geometry that is being buffered.A negative distance can only be specified against a polygon geometry.
- Returns:
A Pandas Series of
Polygon
objects
- clip(envelope)
The
clip
method constructs the intersection of theGeometry
object and thespecified extent.Parameter
Description
envelope
required tuple. The tuple must have (XMin, YMin, XMax, YMax) each valuerepresents the lower left bound and upper right bound of the extent.
- Returns:
A Pandas Series of
Geometry
objects
- contains(second_geometry,relation=None)
The
contains
method indicates if the baseGeometry
contains thecomparisonGeometry
.Parameter
Description
second_geometry
Required
Geometry
. A second geometryrelation
Optional string. The spatial relationship type.
BOUNDARY - Relationship has no restrictions for interiors or boundaries.
CLEMENTINI - Interiors of geometries must intersect. Specifying CLEMENTINI is equivalent to specifying None. This is the default.
PROPER - Boundaries of geometries must not intersect.
- Returns:
A Pandas Series of booleans indicating success (True), or failure (False)
- convex_hull()
The
convex_hull
method constructs theGeometry
that is the minimal boundingPolygon
such that all outer angles are convex.- Returns:
A Pandas Series of
Geometry
objects
- crosses(second_geometry)
The
crosses
method indicates if the twoGeometry
objects intersect in a geometryof a lesser shape type.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of booleans indicating success (True), or failure (False)
- cut(cutter)
The
cut
method splits thisGeometry
into a part to the left of the cuttingPolyline
and a part to the right of it.Parameter
Description
cutter
Required
Polyline
. The cutting polyline geometry- Returns:
A Pandas Series where each element is a list of two
Geometry
objects
- densify(method,distance,deviation)
The
densify
method creates a newGeometry
with added verticesParameter
Description
method
Required String. The type of densification, DISTANCE, ANGLE, or GEODESIC
distance
Required float. The maximum distance between vertices. The actualdistance between vertices will usually be less than the maximumdistance as new vertices will be evenly distributed along theoriginal segment. If using a type of DISTANCE or ANGLE, thedistance is measured in the units of the geometry’s spatialreference. If using a type of GEODESIC, the distance is measuredin meters.
deviation
Required float. Densify uses straight lines to approximate curves.You use deviation to control the accuracy of this approximation.The deviation is the maximum distance between the new segment andthe original curve. The smaller its value, the more segments willbe required to approximate the curve.
- Returns:
A Pandas Series of
Geometry
objects
- difference(second_geometry)
The
difference
method constructs theGeometry
that is composed only of theregion unique to the base geometry but not part of the other geometry.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of
Geometry
objects
- disjoint(second_geometry)
The
disjoint
method indicates if the base and comparisonGeometry
objects sharenoPoint
objects in common.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of booleans indicating success (True), or failure (False)
- distance_to(second_geometry)
The
distance_to
method retrieves the minimum distance between twoGeometry
.If the geometries intersect, the minimum distance is 0.Note
Both geometries must have the same projection.
Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of floats
- equals(second_geometry)
The
equals
method indicates if the base and comparisonGeometry
objects are ofthe same shape type and define the same set ofPoint
objects in the plane.Note
This is a 2D comparison only; M and Z values are ignored.
Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of booleans indicating success (True), or failure (False)
- propertyextent
The
extent
method retrieves the feature’s extent- Returns:
A tuple (xmin,ymin,xmax,ymax) in series
- propertyfirst_point
The
first_point
property retrieves the feature’s firstPoint
object- Returns:
A
Point
object
- generalize(max_offset)
The
generalize
method creates a new simplifiedGeometry
using a specified maximumoffset tolerance.Parameter
Description
max_offset
Required float. The maximum offset tolerance.
- Returns:
A Pandas Series of
Geometry
objects
- propertygeoextent
The
geoextent
method retrieves theGeometry
object’s extents- Returns:
A Series of Floats
- propertygeometry_type
The
geometry_type
property retrieves theGeometry
object’s type.- Returns:
A Series of strings
- get_area(method,units=None)
The
get_area
method retreives the area of the feature using a measurement type.Parameter
Description
method
Required String.PLANAR measurements reflect the projection ofgeographic data onto the 2D surface (in other words, they will nottake into account the curvature of the earth).GEODESIC,GREAT_ELLIPTIC,LOXODROME, andPRESERVE_SHAPE measurement typesmay be chosen as an alternative, if desired.
units
Optional String. Areal unit of measure keywords:` ACRES | ARES | HECTARES| SQUARECENTIMETERS | SQUAREDECIMETERS | SQUAREINCHES | SQUAREFEET| SQUAREKILOMETERS | SQUAREMETERS | SQUAREMILES |SQUAREMILLIMETERS | SQUAREYARDS`
- Returns:
A Pandas Series of floats
- get_length(method,units)
The
get_length
method retrieves the length of the feature using a measurement type.Parameter
Description
method
Required String.PLANAR measurements reflect the projection ofgeographic data onto the 2D surface (in other words, they will nottake into account the curvature of the earth).GEODESIC,GREAT_ELLIPTIC,LOXODROME, andPRESERVE_SHAPE measurement typesmay be chosen as an alternative, if desired.
units
Required String. Linear unit of measure keywords:CENTIMETERS |DECIMETERS | FEET | INCHES | KILOMETERS | METERS | MILES |MILLIMETERS | NAUTICALMILES | YARDS
- Returns:
A A Pandas Series of floats
- get_part(index=None)
The
get_part
method retrieves an array ofPoint
objects for a particular part ofGeometry
or an array containing a number of arrays, one for each part.requires arcpy
Parameter
Description
index
Required Integer. The index position of the geometry.
- Returns:
AnA Pandas Series of arcpy.Arrays
- propertyhas_m
The
has_m
method determines if theGeometry
objects has anM value- Returns:
A Series of Booleans
- propertyhas_z
The
has_z
method determines if theGeometry
object has aZ value- Returns:
A Series of Booleans
- propertyhull_rectangle
The
hull_rectangle
retrieves a space-delimited string of the coordinate pairs of the convex hull- Returns:
A Series of strings
- intersect(second_geometry,dimension=1)
The
intersect
method constructs aGeometry
that is the geometric intersection ofthe two input geometries. Different dimension values can be used to createdifferent shape types.Note
The intersection of two
Geometry
objects of thesame shape type is a geometry containing only the regions of overlapbetween the original geometries.Parameter
Description
second_geometry
Required
Geometry
. A second geometrydimension
Required Integer. The topological dimension (shape type) of theresulting geometry.
1 -A zero-dimensional geometry (point or multipoint).
2 -A one-dimensional geometry (polyline).
4 -A two-dimensional geometry (polygon).
- Returns:
A Pandas Series of
Geometry
objects
- propertyis_empty
The
is_empty
method determines if theGeometry
object is empty.- Returns:
A Series of Booleans
- propertyis_multipart
The
is_multipart
method determines if features has multiple parts.- Returns:
A Series of Booleans
- propertyis_valid
The
is_valid
method determines if the featuresGeometry
is valid- Returns:
A Series of Booleans
- propertylabel_point
The
label_point
method determines thePoint
for the optimal label location.- Returns:
A Series of
Geometry
object
- propertylast_point
The
last_point
method retrieves theGeometry
of the last point in a feature.- Returns:
A Series of
Geometry
objects
- measure_on_line(second_geometry,as_percentage=False)
The
measure_on_line
method retrieves the measure from the startPoint
of this lineto thein_point
.Parameter
Description
second_geometry
Required
Geometry
. A second geometryas_percentage
Optional Boolean. If False, the measure will be returned as adistance; if True, the measure will be returned as a percentage.
- Returns:
A Pandas Series of floats
- overlaps(second_geometry)
The
overlaps
method indicates if the intersection of the twoGeometry
objects hasthe same shape type as one of the input geometries and is not equivalent toeither of the input geometries.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of booleans indicating success (True), or failure (False)
- propertypart_count
The
part_count
method retrieves the number of parts in a feature’sGeometry
- Returns:
A Series of Integers
- propertypoint_count
The
point_count
method retrieves the number ofPoint
objects in a feature’sGeometry
.- Returns:
A Series of Integers
- point_from_angle_and_distance(angle,distance,method='GEODESCIC')
The
point_from_angle_and_distance
retrieves aPoint
at a given angle and distancein degrees and meters using the specified measurement type.Parameter
Description
angle
Required Float. The angle in degrees to the returned point.
distance
Required Float. The distance in meters to the returned point.
method
Optional String. PLANAR measurements reflect the projection of geographicdata onto the 2D surface (in other words, they will not take intoaccount the curvature of the earth). GEODESIC, GREAT_ELLIPTIC,LOXODROME, and PRESERVE_SHAPE measurement types may be chosen asan alternative, if desired.
- Returns:
A Pandas Series of
Geometry
objects
- position_along_line(value,use_percentage=False)
The
position_along_line
method retrieves aPoint
on a line at a specifieddistance from the beginning of the line.Parameter
Description
value
Required Float. The distance along the line.
use_percentage
Optional Boolean. The distance may be specified as a fixed unitof measure or a ratio of the length of the line. If True, valueis used as a percentage; if False, value is used as a distance.For percentages, the value should be expressed as a double from0.0 (0%) to 1.0 (100%).
- Returns:
A Pandas Series of
Geometry
objects.
- project_as(spatial_reference,transformation_name=None)
The
project_as
method projects aGeometry`andoptionallyappliesa``geotransformation`
.Parameter
Description
spatial_reference
Required
SpatialReference
.The new spatial reference. This can be aSpatialReference
object or the coordinate system name.transformation_name
Required String. Thegeotransformation name.
- Returns:
A Pandas Series of
Geometry
objects
- query_point_and_distance(second_geometry,use_percentage=False)
The
query_point_and_distance
finds thePoint
on thePolyline
nearest to thein_point
and thedistance between those points.Note
query_point_and_distance
also returns information about theside of the line thein_point
is on as well as the distance alongthe line where the nearest point occurs.Parameter
Description
second_geometry
Required
Geometry
. A second geometryas_percentage
Optional boolean - if False, the measure will be returned asdistance, True, measure will be a percentage
- Returns:
A Pandas Series of tuples
- segment_along_line(start_measure,end_measure,use_percentage=False)
The
segment_along_line
method retrieves aPolyline
between start and end measures.Similar topositionAlongLine
but will return a polyline segment betweentwo points on the polyline instead of a singlePoint
.Parameter
Description
start_measure
Required Float. The starting distance from the beginning of the line.
end_measure
Required Float. The ending distance from the beginning of the line.
use_percentage
Optional Boolean. The start and end measures may be specified asfixed units or as a ratio.If
True
,start_measure
andend_measure
are used as a percentage; ifFalse
,start_measure
andend_measure
are used as a distance. Forpercentages, the measures should be expressed as a double from 0.0(0 percent) to 1.0 (100 percent).- Returns:
A Pandas Series of
Geometry
objects
- snap_to_line(second_geometry)
The
snap_to_line
method creates a newPoint
based onin_point
snapped to thisGeometry
object.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of
Geometry
objects
- propertyspatial_reference
The
spatial_reference
method retrieves theSpatialReference
of theGeometry
- Returns:
A Series of
SpatialReference
objects.
- symmetric_difference(second_geometry)
The
symmetric_difference
method constructs theGeometry
that is the union of twogeometries minus the intersection of those geometries.Note
The two input
Geometry
must be the same shape type.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of
Geometry
objects
- touches(second_geometry)
The
touches
method indicates if the boundaries of theGeometry
intersect.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of booleans indicating touching (True), or not touching (False)
- propertytrue_centroid
The
true_centroid
method retrieves the true centroid of theGeometry
object.- Returns:
A Series of
Point
objects
- union(second_geometry)
The
union
method constructs theGeometry
object that is the set-theoretic unionof the input geometries.Parameter
Description
second_geometry
Required
Geometry
. A second geometry- Returns:
A Pandas Series of
Geometry
objects
- within(second_geometry,relation=None)
The
within
method indicates if the baseGeometry
is within the comparisonGeometry
.Parameter
Description
second_geometry
Required
Geometry
. A second geometryrelation
Optional String. The spatial relationship type.
BOUNDARY - Relationship has no restrictions for interiors or boundaries.
CLEMENTINI - Interiors of geometries must intersect. Specifying CLEMENTINI is equivalent to specifying None. This is the default.
PROPER - Boundaries of geometries must not intersect.
- Returns:
A Pandas Series of booleans indicating within (True), or not within (False)
GeoDaskSpatialAccessor
GeoDaskSeriesAccessor
EditFeatureJob
- classarcgis.features._async.EditFeatureJob(future,connection)
Represents a Single Editing Job. TheEditFeatureJob class allows for theasynchronous operation of the
edit_features()
method. This class is not intended for users to initialize directly, but isretuned byedit_features()
whenfuture=True.Parameter
Description
future
Future. The future request.
connection
The GIS connection object.
- result()
Return the value returned by the call. If the call hasn’t yet completedthen this method will wait.
- Returns:
object
Submodules
- arcgis.features.analysis module
- aggregate_points
- calculate_composite_index
- calculate_density
- choose_best_facilities
- connect_origins_to_destinations
- create_buffers
- create_drive_time_areas
- create_route_layers
- create_viewshed
- create_watersheds
- derive_new_locations
- dissolve_boundaries
- enrich_layer
- extract_data
- find_centroids
- find_existing_locations
- find_hot_spots
- find_nearest
- find_point_clusters
- find_similar_locations
- generate_tessellation
- interpolate_points
- join_features
- merge_layers
- overlay_layers
- plan_routes
- summarize_nearby
- summarize_center_and_dispersion
- summarize_within
- trace_downstream
- arcgis.features.analyze_patterns module
- arcgis.features.elevation module
- arcgis.features.enrich_data module
- arcgis.features.find_locations module
- arcgis.features.hydrology module
- arcgis.features.manage_data module
- arcgis.features.managers module
- AttachmentManager
- SyncManager
- FeatureLayerCollectionManager
- FeatureLayerManager
- VersionManager
- Version
- ParcelFabricManager
- TopographicProductionManager
- TopographicProductionJobManager
- TraceConfiguration
- TraceConfigurationsManager
- TraceNetworkManager
- UtilityNetworkManager
- ValidationManager
- WebHookServiceManager
- WebHook
- WebHookEvents
- WebHookScheduleInfo
- NetworkDiagramManager
- Diagram
- arcgis.features.summarize_data module
- arcgis.features.use_proximity module