arcgis.features module

The arcgis.features module contains types and functions for working with features and feature layers in the GIS .

Entities located in space with a geometrical representation (such as points, lines or polygons) and a set of properties can be represented as features. The arcgis.features module is used for working with feature data, feature layers and collections of feature layers in the GIS. It also contains the spatial analysis functions which operate against feature data.

In the GIS, entities located in space with a set of properties can be represented as features. Features are stored as feature classes, which represent a set of features located using a single spatial type (point, line, polygon) and a common set of properties. This is the geographic extension of the classic tabular or relational representation for entities - a set of entities is modelled as rows in a table. Tables represent entity classes with uniform properties. In addition to working with entities with location as features, the system can also work with non-spatial entities as rows in tables. The system can also model relationships between entities using properties which act as primary and foreign keys. A collection of feature classes and tables, with the associated relationships among the entities, is a feature layer collection. FeatureLayerCollection are one of the dataset types contained in a Datastore.

Note

Features are not simply entities in 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

class arcgis.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}}
property as_dict

Retrieves the feature layer as a dictionary.

Returns:

The feature as a dictionary

property as_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

property attributes

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"}
property fields

Retrieves the attribute field names for the feature as a list of strings

Returns:

A list of strings

classmethod from_dict(feature, sr=None)

Creates a Feature object from a dictionary.

Returns:

A Feature

classmethod from_json(json_str)

Creates a Feature object from a JSON string.

Returns:

A Feature

property geometry

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 dictionary if 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}}
property geometry_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)

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, value)

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() with feat_set in a list as the updates argument.

FeatureLayer

class arcgis.features.FeatureLayer(url, gis=None, container=None, dynamic_layer=None)

The FeatureLayer class is the primary concept for working with Feature objects in a GIS.

User objects create, import, export, analyze, edit, and visualize features, i.e. entities in space as feature layers.

Feature layers can be added to and visualized using maps. They act as inputs to and outputs from feature analysis tools.

Feature layers are created by publishing feature data to a GIS, and are exposed as a broader resource (Item) in the GIS. Feature layer objects can be obtained through the layers attribute on feature layer Items in the GIS.

append(item_id=None, upload_format='featureCollection', source_table_name=None, field_mappings=None, edits=None, source_info=None, upsert=False, skip_updates=False, use_globalids=False, update_geometry=True, append_fields=None, rollback=False, skip_inserts=None, upsert_matching_field=None, upload_id=None, layer_mappings=None, *, return_messages=None, future=False)

The append method is used to update an existing hosted FeatureLayer object. See the Append (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+

Parameter

Description

item_id

Optional string. The ID for the Portal item that contains the source file. Used in conjunction with editsUploadFormat.

upload_format

Required string. The source append data format. The default is featureCollection. Values: ‘sqlite’ | ‘shapefile’ | ‘filegdb’ | ‘featureCollection’ | ‘geojson’ | ‘csv’ | ‘excel’

Note

You can find the Feature Layer’s supported formats by checking the featureLayer.properties.supportedAppendFormats property.

source_table_name

Required string. Required even when the source data contains only one 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. Append supports all format through the upload_id or item_id.

source_info

Optional dictionary. This is only needed when appending data from excel or csv. The appendSourceInfo can be the publishing parameter returned from analyze the csv or excel file.

upsert

Optional boolean. Optional parameter specifying whether the edits needs 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 GlobalId when matching features.

update_geometry

Optional boolean. The parameter is used only when upsert is true. Skip updating the geometry and update only the attributes for existing features if they match source features by objectId or globalId.(as specified by useGlobalIds parameter).

append_fields

Optional list. The list of destination fields to append to. This is supported when upsert=true or false.

#Values:
["fieldName1", "fieldName2",....]

rollback

Optional boolean. Optional parameter specifying whether the upsert edits 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 is true. The default value is false.

upsert_matching_field

Optional string. The layer field to be used when matching features with upsert. ObjectId, GlobalId, and any other field that has a unique index can be used with upsert. This parameter overrides use_globalids; e.g., specifying upsert_matching_field will be used even if you specify use_globalids = True. Example: upsert_matching_field=”MyfieldWithUniqueIndex”

upload_id

Optional string. The itemID field from an upload() response, corresponding with the appendUploadId REST API argument. This argument should not be used along side the item_id argument.

layer_mappings

Optional list of dictionaries. This is needed if the source is featureService. It is used to map a source layer to a destination layer. Only one source can be mapped to a layer.

Syntax: layerMappings=[{“id”: <layerID>, “sourceId”: <layer id>}]

return_messages

Optional Boolean. When set to True, the messages returned from the append will be returned. If False, the response messages will not be returned. This alters the output to be a tuple consisting of a (Boolean, Dictionary).

future

Optional boolean. If True, a future object will be returned and the process will not wait for the task to complete. The default is False, which means wait for results.

Returns:

A boolean indicating success (True), or failure (False). When return_messages is True, the response messages will be return in addition to the boolean as a tuple. If future = True, then the result is a Future object. Call result() 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, calc_expression, sql_format='standard', version=None, sessionid=None, return_edit_moment=None, future=False)

The calculate operation is performed on a FeatureLayer resource. calculate updates the values of one or more fields in an existing feature service layer based on SQL expressions or scalar values. The calculate operation can only be used if the supportsCalculate property of the layer is True. Neither the Shape field nor system fields can be updated using calculate. System fields include ObjectId and GlobalId.

Inputs

Description

where

Required String. A where clause can be used to limit the updated records. Any legal SQL where clause operating on the fields in the layer is allowed.

calc_expression

Required List. The array of field/value info objects that contain the field or fields to update and their scalar values or SQL expression. Allowed types are dictionary and list. List must be a list of dictionary objects.

Calculation Format is as follows:

{“field” : “<field name>”, “value” : “<value>”}

sql_format

Optional String. The SQL format for the calc_expression. It can be either standard SQL92 (standard) or native SQL (native). The default is standard.

Values: standard, native

version

Optional String. The geodatabase version to apply the edits.

sessionid

Optional String. A parameter which is set by a client during long transaction editing on a branch version. The sessionid is a GUID value that clients establish at the beginning and use throughout the edit session. The sessonid ensures isolation during the edit session. This parameter applies only if the isDataBranchVersioned property of the layer is true.

return_edit_moment

Optional Boolean. This parameter specifies whether the response will report the time edits were applied. If true, the server will return the time edits were applied in the response’s edit moment key. This parameter applies only if the isDataBranchVersioned property of the layer is true.

future

Optional boolean. If True, a future object will be returned and the process will not wait for the task to complete. The default is False, 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 a Future object. Call result() 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"}))
property container

Get/Set the FeatureLayerCollection to which this layer belongs.

Parameter

Description

value

Required FeatureLayerCollection.

Returns:

The Feature Layer Collection where the layer is stored

property contingent_values

Returns the define contingent values for the given layer. :returns: Dict[str,Any]

delete_features(deletes=None, where=None, geometry_filter=None, gdb_version=None, rollback_on_failure=True, return_delete_results=True, future=False)

Deletes features in a FeatureLayer or Table

Parameter

Description

deletes

Optional string. A comma separated string of OIDs to remove from the service.

where

Optional string. A where clause for the query filter. Any legal SQL where 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 from arcgis.geometry.filters module to filter results by a spatial relationship with another geometry.

gdb_version

Optional string. The geodatabase version. This parameter applies only if the isDataVersioned property of the layer is true.

rollback_on_failure

Optional boolean. Optional parameter to specify if the edits should be applied only if all submitted edits succeed. If false, the server will apply the edits that succeed even if some of the submitted edits fail. If true, the server will apply the edits only if all edits succeed. The default value is true.

return_delete_results

Optional Boolean. Optional parameter that indicates whether a result is 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 process will 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 a Future object. Call result() to get the response.

# Usage Example with only a "where" sql statement

>>> from arcgis.features import FeatureLayer

>>> 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=None, updates=None, deletes=None, gdb_version=None, use_global_ids=False, rollback_on_failure=True, return_edit_moment=False, attachments=None, true_curve_client=False, session_id=None, use_previous_moment=False, datum_transformation=None, future=False)

Adds, updates, and deletes features to the associated FeatureLayer or Table in a single call.

Note

When making large number (250+ records at once) of edits, append should be used over edit_features to improve performance 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 service

use_global_ids

Optional boolean. Instead of referencing the default Object ID field, the service will look at a GUID field to track changes. This means the GUIDs will be passed instead of OIDs for delete, update or add features.

gdb_version

Optional string. The geodatabase version to apply edits. This parameter applies only if the isDataVersioned property of the layer is true.

rollback_on_failure

Optional boolean. Optional parameter to specify if the edits should be applied only if all submitted edits succeed. If false, the server will apply the edits that succeed even if some of the submitted edits fail. If true, the server will apply the edits only if all edits succeed. The default value is true.

return_edit_moment

Optional boolean. Introduced at 10.5, only applicable with ArcGIS Server services only. Specifies whether the response will report the time edits were applied. If set to true, the server will return the time in the response’s editMoment key. The default value is false.

attachments

Optional Dict. This parameter adds, updates, or deletes attachments. It applies only when the use_global_ids parameter is set to true. For adds, the globalIds of the attachments provided by the client are preserved. When useGlobalIds is true, updates and deletes are identified by each feature or attachment globalId, rather than their objectId or attachmentId. This parameter requires the layer’s supportsApplyEditsWithGlobalIds property to be true.

Attachments to be added or updated can use either pre-uploaded data or base 64 encoded data.

Inputs

Inputs

Description

adds

List of attachments to add.

updates

List of attachements to update

deletes

List of attachments to delete

See the Apply Edits to a Feature Service layer in the ArcGIS REST API for more information.

true_curve_client

Optional boolean. Introduced at 10.5. Indicates to the server whether the client is true curve capable. When set to true, this indicates to the server that true curve geometries should be downloaded and that geometries containing true curves should be consumed by the map service without densifying it. When set to false, this indicates to the server that the client is not true curves capable. The default value is false.

session_id

Optional String. Introduced at 10.6. The session_id is a GUID value that clients establish at the beginning and use throughout the edit session. The sessonID ensures isolation during the edit session. The session_id parameter is set by a client during long transaction editing on a branch version.

use_previous_moment

Optional Boolean. Introduced at 10.6. The use_previous_moment parameter is used to apply the edits with the same edit moment as the previous set of edits. This allows an editor to apply single block of edits partially, complete another task and then complete the block of edits. This parameter is set by a client during long transaction editing on a branch version.

When set to true, the edits are applied with the same edit moment as the previous set of edits. When set to false or not set (default) the edits are applied with a new edit moment.

datum_transformation

Optional Integer/Dictionary. This parameter applies a datum transformation while projecting geometries in the results when out_sr is different than the layer’s spatial reference. When specifying transformations, you need to think about which datum transformation best projects the layer (not the feature service) to the outSR and sourceSpatialReference property in the layer properties. For a list of valid datum transformation ID values ad well-known text strings, see Using spatial references. For more information on datum transformations please see the transformation parameter in the Project 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 the FeatureLayer has supportsAsyncApplyEdits set to True, then edits can be applied asynchronously. If True, a future object will be returned and the process will 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 a Future object. Call result() to get the response.

# Usage Example 1:

feature = [
{
    'attributes': {
        'ObjectId': 1,
        'UpdateDate': datetime.datetime.now(),
    }
}]
lyr.edit_features(updates=feature)
# Usage Example 2:

adds = {"geometry": {"x": 500, "y": 500, "spatialReference":
                    {"wkid": 102100, "latestWkid": 3857}},
        "attributes": {"ADMIN_NAME": "Fake Location"}
        }
lyr.edit_features(adds=[adds])
# Usage Example 3:

lyr.edit_features(deletes=[2542])
property estimates

Returns up-to-date approximations of layer information, such as row count and extent. Layers that support this property will include infoInEstimates information in the layer’s properties.

Currently available with ArcGIS Online and Enterprise 10.9.1+

Returns:

Dict[str, Any]

export_attachments(output_folder, label_field=None)

Exports attachments from the FeatureLayer in Imagenet format using the output_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

property field_groups

Returns the defined list of field groups for a given layer.

Returns:

dict[str,Any]

classmethod fromitem(item, layer_id=0)

The fromitem method creates a FeatureLayer from an Item object.

Parameter

Description

item

Required Item object. The type of item should be a Feature Service that represents a FeatureLayerCollection

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

>>> from arcgis.features import FeatureLayer

>>> 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, where=None)

Groups data using the supplied definition (classification definition) and an optional where clause. The result is a renderer object.

Note

Use baseSymbol and colorRamp to define the symbols assigned to each class. If the operation is performed on a table, the result is a renderer object containing the data classes 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. See Classification Objects for additional details.

where

Optional string. A where clause for which the data needs to be classified. Any legal SQL where clause operating on the fields in the dynamic layer/table is allowed.

Returns:

A JSON Dictionary

# Example Usage
FeatureLayer.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)

The get_html_popup method provides details about the HTML pop-up authored by the User 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, query_string='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 attributes before unique values are returned. ex. “name_2 like ‘%K%’”

Returns:

A list of unique values

# Usage Example with only a "where" sql statement

>>> from arcgis.features import FeatureLayer

>>> 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']
property manager

The manager property is a helper object to manage the FeatureLayer, such as updating its definition.

Returns:

A FeatureLayerManager

# Usage Example

>>> manager = FeatureLayer.manager
property metadata

Get the Feature Layer’s metadata.

Note

If metadata is disabled on the GIS or the layer does not support metadata, None will be returned.

Returns:

String of the metadata, if any

property properties

The properties property retrieves and set properties of this object.

query(where='1=1', out_fields='*', time_filter=None, geometry_filter=None, return_geometry=True, return_count_only=False, return_ids_only=False, return_distinct_values=False, return_extent_only=False, group_by_fields_for_statistics=None, statistic_filter=None, result_offset=None, result_record_count=None, object_ids=None, distance=None, units=None, max_allowable_offset=None, out_sr=None, geometry_precision=None, gdb_version=None, order_by_fields=None, out_statistics=None, return_z=False, return_m=False, multipatch_option=None, quantization_parameters=None, return_centroid=False, return_all_records=True, result_type=None, historic_moment=None, sql_format=None, return_true_curves=False, return_exceeded_limit_features=None, as_df=False, datum_transformation=None, time_reference_unknown_client=None, **kwargs)

The query method queries a FeatureLayer based on a sql statement.

Parameter

Description

where

Optional string. SQL-92 WHERE clause syntax on the fields in the layer is supported for most data sources. Some data sources have restrictions on what is supported. Hosted feature services in ArcGIS Enterprise running on 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 specify the wildcard “*” as the value of this parameter. In this case, the query results include all the field values.

Note

If specifying return_count_only, return_id_only, or return_extent_only as 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 data source resides in an enterprise geodatabase and more than 1,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 the distance is 100, the query geometry is a point, units is set to meters, and all points within 100 meters of the point are returned.

units

Optional string. The unit for calculating the buffer distance. If unit is not specified, the unit is derived from the geometry spatial reference. If the geometry spatial reference is not specified, the unit is derived from the feature service data spatial reference. This parameter only applies if supportsQueryWithDistance 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>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as

datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of out_sr. If out_sr is not specified, max_allowable_offset is assumed to be in the unit of the spatial reference of the layer.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

geometry_precision

Optional Integer. This option can be used to specify the number of decimal places in the response geometries returned by the query operation. This applies to X and Y values only (not m or z-values).

gdb_version

Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If this is not specified, the query will apply to the published map’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 the fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true. This parameter can be used with return_count_only to return the count of distinct values 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 only includes an array of object IDs. Otherwise, the response is a feature set. When object_ids are specified, setting this parameter to true 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. This option supersedes the returnIdsOnly parameter. If returnCountOnly = true, the response will return both the count and the extent.

return_extent_only

Optional boolean. If true, the response only includes the extent of the features that would be returned by the query. If returnCountOnly=true, the response will return both the count and the extent. The default is false. This parameter applies only if the supportsReturningQueryExtent property of the layer is true.

order_by_fields

Optional string. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

Note

If specifying return_count_only, return_id_only, or return_extent_only as 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 to be grouped for calculating the statistics. example: STATE_NAME, GENDER

out_statistics

Optional list of dictionaries. The definitions for one or more field-based statistics 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-based statistics can be added, e.g. statisticType, onStatisticField, or outStatisticFieldName.

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 if the 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 if the 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 of a multipatch feature will be returned.

result_offset

Optional integer. This option can be used for fetching query results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th). This option is ignored if return_all_records is True (i.e. by default).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s max_record_count property. This option is ignored if return_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 associated with each feature returned. If true, the result includes the geometry centroid. The default is false. Only supported on layer with polygon geometry type.

return_all_records

Optional boolean. When True, the query operation will call the service until all records that satisfy the where_clause are returned. Note: result_offset and result_record_count will be ignored if return_all_records is True. Also, if return_count_only, return_ids_only, or return_extent_only are True, this parameter will be ignored.

result_type

Optional string. The result_type parameter can be used to control the number of features returned by the query operation. Values: None | standard | tile

historic_moment

Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

sql_format

Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

return_true_curves

Optional boolean. When set to true, returns true curves in output geometries. When set to false, curves are converted to densified polylines or polygons.

return_exceeded_limit_features

Optional boolean. Optional parameter which is true by default. When set to true, features are returned even when the results include ‘exceededTransferLimit’: True.

When set to false and querying with resultType = tile features are not returned when the results include ‘exceededTransferLimit’: True. This allows a client to find the resolution in which the transfer limit is no longer exceeded without making multiple calls.

as_df

Optional boolean. If True, the results are returned as a DataFrame instead of a FeatureSet.

datum_transformation

Optional Integer/Dictionary. This parameter applies a datum transformation while projecting geometries in the results when out_sr is different than the layer’s spatial reference. When specifying transformations, you need to think about which datum transformation best projects the layer (not the feature service) to the outSR and sourceSpatialReference property in the layer properties. For a list of valid datum transformation ID values ad well-known text strings, see Coordinate systems and transformations. For more information on datum transformations, please see the transformation parameter in the Project 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 Query function. This will allow users to pass additional parameters not explicitly implemented on the function. A complete list of functions available is documented on the Query REST API.

Returns:

A FeatureSet containing the features matching the query unless another return type is specified, such as return_count_only, return_extent_only, or return_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]
<Feature 1>
# 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 containting total count
# Usage Example with "StatisticFilter" parameter

>>> from arcgis._impl.common._filters import StatisticFilter
>>> 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=None, out_fields=None, object_ids=None, distance=None, units=None, time_filter=None, geometry_filter=None, gdb_version=None, return_distinct_values=None, order_by_fields=None, group_by_fields_for_statistics=None, out_statistics=None, result_offset=None, result_record_count=None, historic_moment=None, sql_format=None, format_3d_objects=None, time_reference_unknown_client=None)

The query3D operation allows clients to query 3D object features and is based on the feature service layer query operation. The 3D object feature layer 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 layer is supported for most data sources. Some data sources have restrictions on what is supported. Hosted feature services in ArcGIS Enterprise running on 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 specify the wildcard “*” as the value of this parameter to return all fields 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 data source resides in an enterprise geodatabase and more than 1,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 the distance is 100, the query geometry is a point, units is set to meters, and all points within 100 meters of the point are returned.

units

Optional string. The unit for calculating the buffer distance. If unit is not specified, the unit is derived from the geometry spatial reference. If the geometry spatial reference is not specified, the unit is derived from the feature service data spatial reference. This parameter only applies if supportsQueryWithDistance 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>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as

datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

gdb_version

Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If this is not specified, the query will apply to the published map’s version.

return_distinct_values

Optional boolean. If true, it returns distinct values based on the fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true. This parameter can be used with return_count_only to return the count of distinct values 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 the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

Note

If specifying return_count_only, return_id_only, or return_extent_only as 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 to be grouped for calculating the statistics. example: STATE_NAME, GENDER

out_statistics

Optional list of dictionaries. The definitions for one or more field-based statistics 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 results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th). This option is ignored if return_all_records is True (i.e. by default).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s max_record_count property. This option is ignored if return_all_records is True (i.e. by default).

historic_moment

Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

sql_format

Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

format_3d_objects

Optional string. Specifies the 3D format that will be used to request a feature. If set to a valid format ID (see layer resource), the geometry of the feature response will be a 3D envelope of the 3D object and will include 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 format is not ready. Request the feature again later.

If a feature does not have the specified format, the feature will still be returned according to the query parameters (such as the where clause), but the asset 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. Setting time_reference_unknown_client as True indicates that the client is capable of working with data values that are not in UTC. If its not set to true, and the service layer’s datesInUnknownTimeZone 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 returned as-is from the database, rather than as date values in UTC. Non-hosted feature services can be set to use an unknown time zone using ArcGIS Server Manager. Setting the time zones to unknown also sets the datesInUnknownTimeZone layer property as true. Currently, hosted feature services do not support this setting. This setting does not apply to editor tracking date fields which are stored and returned in UTC even when the time zone is set to unknown.

Most clients released prior to ArcGIS Enterprise 10.9 will not be able to work with feature services that have an unknown time setting.

Returns:

A dictionary containing the feature, asset map, and asset information for the layer.

USAGE EXAMPLE: Query 3D objects

# Import the required modules
from arcgis.gis import GIS
from arcgis.features import FeatureLayer

# Connect to your GIS
gis = GIS(profile="your_enterprise_profile")

# Search for the feature layer
search_result = gis.content.search("3D Object Feature Layer", "Feature Layer")
feature_layer = search_result[0]

# Create a FeatureLayer object
layer = FeatureLayer(feature_layer.url, gis)

# Query the 3D objects
result = layer.query_3d(where="OBJECTID < 10", out_fields="*", format_3d_objects="3D_dae")
print(result)
query_analytics(out_analytics, where='1=1', out_fields='*', analytic_where=None, geometry_filter=None, out_sr=None, return_geometry=True, order_by=None, result_type=None, cache_hint=None, result_offset=None, result_record_count=None, quantization_param=None, sql_format=None, future=True, **kwargs)

The query_analytics exposes the standard SQL windows functions that compute aggregate and ranking values based on a group of rows called window partition. The window function is applied to the rows after the partitioning and ordering of the rows. query_analytics defines a window or user-specified set of rows within a query result set. query_analytics can be used to compute aggregated values such as moving averages, 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 partition or window) that are related to the current row. Unlike regular aggregate functions, use of a window function does not return single output row. The rows retain their separate identities with each calculation appended to the rows as a new field value. The window function can access more than just the 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 on a set of values and return a single value. They are used in the select list with optional HAVING clause. GROUP BY clause can also be used to calculate the aggregation on categories of rows. query_analytics can be used to calculate the aggregation on a specific range of value. Supported aggregate functions are:

  • Min

  • Max

  • Sum

  • Count

  • AVG

  • STDDEV

  • VAR

Analytic Functions

Several analytic functions available now in all SQL vendors to compute an aggregate value based on a group of rows or windows partition. Unlike aggregation functions, analytic functions can return single or multiple rows for 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. Depending on 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 over different group of rows. It is very powerful and has many potential usages. For example, you can add partition by to your window specification to look at different groups of rows individually.

partitionBy clause divides the query result set into partitions and the sql window function is applied to each partition. The ‘partitionBy’ clause normally refers to the column by which the result is partitioned. ‘partitionBy’ can also be a value expression (column expression or function) 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 analytics to be computed. This parameter is supported only on layers/tables that return true for supportsAnalytics property.

Note

If outAnalyticFieldName is empty or missing, the server assigns a 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

See Overview for 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": <double value>,// percentile value
         "partitionBy": "<field name or expression>",
         "offset": <integer>, // used by LAG/LEAD
         "windowFrame": {
            "type": "ROWS" | "RANGE",
            "extent": {
               "extentType": "PRECEDING" | "BOUNDARY",
               "PRECEDING": {
                  "type": <"UNBOUNDED" |
                          "NUMERIC_CONSTANT" |
                           "CURRENT_ROW">
                   "value": <numeric constant value>
                }
                "BOUNDARY": {
                 "start": "UNBOUNDED_PRECEDING",
                          "NUMERIC_PRECEDING",
                           "CURRENT_ROW",
                 "startValue": <numeric constant value>,
                 "end": <"UNBOUNDED_FOLLOWING" |
                         "NUMERIC_FOLLOWING" |
                         "CURRENT_ROW",
                 "endValue": <numeric constant value>
                }
              }
            }
         }
    }
  }
]
# 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 specified either 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 to the result set of applying the source where clause and all other params.

geometry_filter

Optional from arcgis.geometry.filter. Allows for the information to be filtered on spatial relationship with another geometry.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

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 the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

result_type

Optional string. The result_type parameter can be used to control the 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 results quicker. The default is False.

result_offset

Optional integer. This option can be used for fetching query results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of 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 standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

future

Optional Boolean. This determines if a Future object is returned (True) the method returns the results directly (False).

Returns:

A Pandas DataFrame (pd.DataFrame)

query_date_bins(bin_field, bin_specs, out_statistics, time_filter=None, geometry_filter=None, bin_order=None, where=None, return_centroid=False, in_sr=None, out_sr=None, spatial_rel=None, quantization_params=None, result_offset=None, result_record_count=None, return_exceeded_limit_features=False)

The query_date_bins operation is performed on a FeatureLayer. 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 or sum, and may also include the aggregate geometries (in other words, centroid) for point layers.

The parameters define the bins, the aggregate information returned, and the included features. Bins are defined using the bin parameter. The out_statistics and return_centroid parameters define the information each bin will provide. Included features can be specified by providing a time extent, where condition, and a spatial filter, similar to a query operation.

The contents of the bin_specs parameter provide flexibility for defining bin boundaries. The bin_specs parameter’s unit property defines the time width of each bin, such as one year, quarter, month, day, or hour. Fixed bins can use multiple units for these time widths. The result_offset property defines an offset within that time unit. For example, if your bin unit is day, and you want bin boundaries to go from noon to noon on the next day, the offset would be 12 hours.

Features can be manipulated with the time_filter, where, and geometry_filter parameters. By default, the result will expand to fit the feature’s earliest and latest point of time. The time_filter parameter defines a fixed starting point and ending point of the features based on the field used in binField. The where and geometry_filter parameters allow additional filters to be put on the data.

This operation is only supported on feature services using a spatiotemporal data store. As well, the service property supportsQueryDateBins must be set to true.

To use pagination with aggregated queries on hosted feature services in ArcGIS Enterprise, the supportsPaginationOnAggregatedQueries property must be true on the layer. Hosted feature services using a spatiotemporal data store do not currently support pagination on aggregated queries.

Parameter

Description

bin_field

Required String. The date field used to determine which bin each feature falls into.

bin_specs

Required Dict. A dictionary that describes the characteristics of bins, such as the size of the bin and its starting position. The size of each bin is determined by the number of time units denoted by the number and unit properties.

The starting position of the bin is the earliest moment in the specified unit. For example, each year begins at midnight of January 1. An offset inside the bin parameter can provide an offset to the starting position of the bin. This can contain a positive or negative integer value.

A bin can take two forms: either a calendar bin or a fixed bin. A calendar bin is aware of calendar-specific adjustments, such as daylight saving time and leap seconds. Fixed bins are, by contrast, always a specific unit of measurement (for example, 60 seconds in a minute, 24 hours in a day) regardless of where the date and time of the bin starts. For this reason, some calendar-specific units are only 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-based statistics 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>] using datetime.date, datetime.datetime or timestamp in milliseconds.

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

bin_order

Optional String. Either “ASC” or “DESC”. Determines whether results are returned in ascending or descending order. Default is ascending.

where

Optional String. A WHERE clause for the query filter. SQL ‘92 WHERE clause syntax on the fields in the layer is supported for most data sources.

return_centroid

Optional Boolean. Returns the geometry centroid associated with all the features in the bin. If true, the result includes the geometry centroid. The default is false. This parameter is only supported on point data.

in_sr

Optional Integer. The WKID for the spatial reference of the input geometry.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

spatial_rel

Optional String. The spatial relationship to be applied to the input geometry while performing the query. The supported spatial relationships include intersects, contains, envelop intersects, within, and so on. The default spatial relationship is intersects (esriSpatialRelIntersects). Other options are esriSpatialRelContains, esriSpatialRelCrosses, esriSpatialRelEnvelopeIntersects, esriSpatialRelIndexIntersects, esriSpatialRelOverlaps, esriSpatialRelTouches, and esriSpatialRelWithin.

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}
    }
}

See Quantization parameters JSON properties for details on format of this parameter.

Note

This parameter only applies if the layer’s supportsCoordinateQuantization property is true.

result_offset

Optional Int. This parameter fetches query results by skipping the specified number of records and starting from the next record. The default is 0.

Note:

This parameter only applies if the layer’s supportsPagination property is true.

result_record_count

Optional Int. This parameter fetches query results up to the value specified. When result_offset is specified, but this parameter is not, the map service defaults to the layer’s maxRecordCount property. The maximum value for this parameter is the value of the maxRecordCount property. The minimum value entered for this parameter cannot be below 1.

Note:

This parameter only applies if the layer’s supportsPagination property is true.

return_exceeded_limit_features

Optional Boolean. When set to True, features are returned even when the results include "exceededTransferLimit": true. This allows a client to find the resolution in which the transfer limit is no longer exceeded withou making multiple calls. The default value is False.

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
  }

The query_related_records operation is performed on a FeatureLayer resource. The result of this operation are feature sets grouped by source layer/table object IDs. Each feature set contains Feature objects including the values for the fields requested by the user. For related layers, if you request geometry information, the geometry of each feature is also returned in the feature set. For related tables, the feature set does not include 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/layer to be included in the returned feature set. This list is a comma delimited list of field names. If you specify the shape field in the list of return fields, it is ignored. To request geometry, set return_geometry to true. You can also specify the wildcard “*” as the value of this parameter. In this case, the results will include all the field values.

definition_expression

Optional string. The definition expression to be applied to the related table/layer. From the list of objectIds, only those records that conform to this expression are queried for related records.

return_geometry

Optional boolean. If true, the feature set includes the geometry associated with each feature. The default is true.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of the outSR. If out_wkid is not specified, then max_allowable_offset is 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 of decimal 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 parameter applies only if the isDataVersioned property of the layer queried is true.

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the 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 parameter applies only if the supportsQueryWithHistoricMoment property of the layers being queried is set to true. This setting is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

Syntax: historic_moment=<Epoch time in milliseconds>

return_true_curves

Optional boolean. Optional parameter that is false by default. When set to true, returns true curves in output geometries; otherwise, curves are converted to densified Polyline or Polygon 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=None, where=None, objectids=None, start_time=None, end_time=None, geometry_filter=None, out_fields='*', return_geometry=True, return_centroid=False, max_allowable_offset=None, out_sr=None, geometry_precision=None, return_ids_only=False, return_extents_only=False, order_by_field=None, return_z=False, return_m=False, result_type=None, as_df=True)

The query_top_features is performed on a FeatureLayer. This operation returns a feature set or spatially enabled dataframe based on the top features by order within a group. For example, when querying counties in the United States, you want to return the top five counties by population in each state. To do this, you can use query_top_features to group by state name, order by desc on the 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 in generating the result. The operation also has many of the same parameters (for example, where and geometry) as the layer query operation. However, unlike the layer query operation, query_top_feaures does not support parameters such as outStatistics and its related parameters or return distinct values. Consult the advancedQueryCapabilities layer property for more details.

If the feature layer collection supports the query_top_feaures 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. The top_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 in either 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 WHERE clause syntax on the fields in the layer is supported for most data sources.

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 to be 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 be added to the output.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of out_sr. If out_sr is not specified, max_allowable_offset is assumed to be in the unit of the spatial reference of the layer.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

geometry_precision

Optional Integer. This option can be used to specify the number of decimal places in the response geometries returned by the query operation. 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 only includes an array of object IDs. Otherwise, the response is a feature set.

return_extent_only

Optional boolean. If true, the response only includes the extent of the features that would be returned by the query. If returnCountOnly=true, the response will return both the count and the extent. The default is false. This parameter applies only if the supportsReturningQueryExtent property of the layer is true.

order_by_field

Optional Str. Optional string. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the 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 number of 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 a FeatureSet. If `return_count_only=True`, the return type is Integer. If `return_ids_only=True`, a list of value is returned.

property renderer

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-insensitive dict like object used to update and alter JSON A varients of a case-less dictionary that allows for dot and bracket notation.

property time_filter

The time_filter method is used to set a time filter instead of querying time-enabled map service layers or time-enabled feature service layers, a time filter can be specified. Time can be filtered as a single instant or by separating 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 single or list of start/stop date.

Returns:

A string of datetime values as milliseconds from epoch

update_metadata(file_path)

The update_metadata updates a FeatureLayer 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, sql_type='where')

The validate_sql operation validates an SQL-92 expression or WHERE clause. The validate_sql operation ensures that an SQL-92 expression, such as one written by a user through a user interface, is correct before performing another operation that uses the expression.

Note

For example, validateSQL can be used to validate information that is subsequently passed in as part of the where parameter of the calculate operation.

validate_sql also prevents SQL injection. In addition, all table and field names used in the SQL expression or WHERE clause are validated 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 user can 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 a new field or using the calculate API.

  • statement - Represents the full SQL-92 statement that can be passed directly to the database. No current ArcGIS REST API resource or operation supports using the full SQL-92 SELECT statement directly. It has been added to the validateSQL for completeness. Values: where | expression | statement

Returns:

A JSON Dictionary indicating ‘success’ or ‘error’

Oriented Imagery Layer

class arcgis.features.OrientedImageryLayer(url, gis=None, container=None, dynamic_layer=None)
append(item_id=None, upload_format='featureCollection', source_table_name=None, field_mappings=None, edits=None, source_info=None, upsert=False, skip_updates=False, use_globalids=False, update_geometry=True, append_fields=None, rollback=False, skip_inserts=None, upsert_matching_field=None, upload_id=None, layer_mappings=None, *, return_messages=None, future=False)

The append method is used to update an existing hosted FeatureLayer object. See the Append (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+

Parameter

Description

item_id

Optional string. The ID for the Portal item that contains the source file. Used in conjunction with editsUploadFormat.

upload_format

Required string. The source append data format. The default is featureCollection. Values: ‘sqlite’ | ‘shapefile’ | ‘filegdb’ | ‘featureCollection’ | ‘geojson’ | ‘csv’ | ‘excel’

Note

You can find the Feature Layer’s supported formats by checking the featureLayer.properties.supportedAppendFormats property.

source_table_name

Required string. Required even when the source data contains only one 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. Append supports all format through the upload_id or item_id.

source_info

Optional dictionary. This is only needed when appending data from excel or csv. The appendSourceInfo can be the publishing parameter returned from analyze the csv or excel file.

upsert

Optional boolean. Optional parameter specifying whether the edits needs 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 GlobalId when matching features.

update_geometry

Optional boolean. The parameter is used only when upsert is true. Skip updating the geometry and update only the attributes for existing features if they match source features by objectId or globalId.(as specified by useGlobalIds parameter).

append_fields

Optional list. The list of destination fields to append to. This is supported when upsert=true or false.

#Values:
["fieldName1", "fieldName2",....]

rollback

Optional boolean. Optional parameter specifying whether the upsert edits 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 is true. The default value is false.

upsert_matching_field

Optional string. The layer field to be used when matching features with upsert. ObjectId, GlobalId, and any other field that has a unique index can be used with upsert. This parameter overrides use_globalids; e.g., specifying upsert_matching_field will be used even if you specify use_globalids = True. Example: upsert_matching_field=”MyfieldWithUniqueIndex”

upload_id

Optional string. The itemID field from an upload() response, corresponding with the appendUploadId REST API argument. This argument should not be used along side the item_id argument.

layer_mappings

Optional list of dictionaries. This is needed if the source is featureService. It is used to map a source layer to a destination layer. Only one source can be mapped to a layer.

Syntax: layerMappings=[{“id”: <layerID>, “sourceId”: <layer id>}]

return_messages

Optional Boolean. When set to True, the messages returned from the append will be returned. If False, the response messages will not be returned. This alters the output to be a tuple consisting of a (Boolean, Dictionary).

future

Optional boolean. If True, a future object will be returned and the process will not wait for the task to complete. The default is False, which means wait for results.

Returns:

A boolean indicating success (True), or failure (False). When return_messages is True, the response messages will be return in addition to the boolean as a tuple. If future = True, then the result is a Future object. Call result() 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, calc_expression, sql_format='standard', version=None, sessionid=None, return_edit_moment=None, future=False)

The calculate operation is performed on a FeatureLayer resource. calculate updates the values of one or more fields in an existing feature service layer based on SQL expressions or scalar values. The calculate operation can only be used if the supportsCalculate property of the layer is True. Neither the Shape field nor system fields can be updated using calculate. System fields include ObjectId and GlobalId.

Inputs

Description

where

Required String. A where clause can be used to limit the updated records. Any legal SQL where clause operating on the fields in the layer is allowed.

calc_expression

Required List. The array of field/value info objects that contain the field or fields to update and their scalar values or SQL expression. Allowed types are dictionary and list. List must be a list of dictionary objects.

Calculation Format is as follows:

{“field” : “<field name>”, “value” : “<value>”}

sql_format

Optional String. The SQL format for the calc_expression. It can be either standard SQL92 (standard) or native SQL (native). The default is standard.

Values: standard, native

version

Optional String. The geodatabase version to apply the edits.

sessionid

Optional String. A parameter which is set by a client during long transaction editing on a branch version. The sessionid is a GUID value that clients establish at the beginning and use throughout the edit session. The sessonid ensures isolation during the edit session. This parameter applies only if the isDataBranchVersioned property of the layer is true.

return_edit_moment

Optional Boolean. This parameter specifies whether the response will report the time edits were applied. If true, the server will return the time edits were applied in the response’s edit moment key. This parameter applies only if the isDataBranchVersioned property of the layer is true.

future

Optional boolean. If True, a future object will be returned and the process will not wait for the task to complete. The default is False, 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 a Future object. Call result() 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"}))
property container

Get/Set the FeatureLayerCollection to which this layer belongs.

Parameter

Description

value

Required FeatureLayerCollection.

Returns:

The Feature Layer Collection where the layer is stored

property contingent_values

Returns the define contingent values for the given layer. :returns: Dict[str,Any]

delete_features(deletes=None, where=None, geometry_filter=None, gdb_version=None, rollback_on_failure=True, return_delete_results=True, future=False)

Deletes features in a FeatureLayer or Table

Parameter

Description

deletes

Optional string. A comma separated string of OIDs to remove from the service.

where

Optional string. A where clause for the query filter. Any legal SQL where 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 from arcgis.geometry.filters module to filter results by a spatial relationship with another geometry.

gdb_version

Optional string. The geodatabase version. This parameter applies only if the isDataVersioned property of the layer is true.

rollback_on_failure

Optional boolean. Optional parameter to specify if the edits should be applied only if all submitted edits succeed. If false, the server will apply the edits that succeed even if some of the submitted edits fail. If true, the server will apply the edits only if all edits succeed. The default value is true.

return_delete_results

Optional Boolean. Optional parameter that indicates whether a result is 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 process will 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 a Future object. Call result() to get the response.

# Usage Example with only a "where" sql statement

>>> from arcgis.features import FeatureLayer

>>> 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=None, updates=None, deletes=None, gdb_version=None, use_global_ids=False, rollback_on_failure=True, return_edit_moment=False, attachments=None, true_curve_client=False, session_id=None, use_previous_moment=False, datum_transformation=None, future=False)

Adds, updates, and deletes features to the associated FeatureLayer or Table in a single call.

Note

When making large number (250+ records at once) of edits, append should be used over edit_features to improve performance 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 service

use_global_ids

Optional boolean. Instead of referencing the default Object ID field, the service will look at a GUID field to track changes. This means the GUIDs will be passed instead of OIDs for delete, update or add features.

gdb_version

Optional string. The geodatabase version to apply edits. This parameter applies only if the isDataVersioned property of the layer is true.

rollback_on_failure

Optional boolean. Optional parameter to specify if the edits should be applied only if all submitted edits succeed. If false, the server will apply the edits that succeed even if some of the submitted edits fail. If true, the server will apply the edits only if all edits succeed. The default value is true.

return_edit_moment

Optional boolean. Introduced at 10.5, only applicable with ArcGIS Server services only. Specifies whether the response will report the time edits were applied. If set to true, the server will return the time in the response’s editMoment key. The default value is false.

attachments

Optional Dict. This parameter adds, updates, or deletes attachments. It applies only when the use_global_ids parameter is set to true. For adds, the globalIds of the attachments provided by the client are preserved. When useGlobalIds is true, updates and deletes are identified by each feature or attachment globalId, rather than their objectId or attachmentId. This parameter requires the layer’s supportsApplyEditsWithGlobalIds property to be true.

Attachments to be added or updated can use either pre-uploaded data or base 64 encoded data.

Inputs

Inputs

Description

adds

List of attachments to add.

updates

List of attachements to update

deletes

List of attachments to delete

See the Apply Edits to a Feature Service layer in the ArcGIS REST API for more information.

true_curve_client

Optional boolean. Introduced at 10.5. Indicates to the server whether the client is true curve capable. When set to true, this indicates to the server that true curve geometries should be downloaded and that geometries containing true curves should be consumed by the map service without densifying it. When set to false, this indicates to the server that the client is not true curves capable. The default value is false.

session_id

Optional String. Introduced at 10.6. The session_id is a GUID value that clients establish at the beginning and use throughout the edit session. The sessonID ensures isolation during the edit session. The session_id parameter is set by a client during long transaction editing on a branch version.

use_previous_moment

Optional Boolean. Introduced at 10.6. The use_previous_moment parameter is used to apply the edits with the same edit moment as the previous set of edits. This allows an editor to apply single block of edits partially, complete another task and then complete the block of edits. This parameter is set by a client during long transaction editing on a branch version.

When set to true, the edits are applied with the same edit moment as the previous set of edits. When set to false or not set (default) the edits are applied with a new edit moment.

datum_transformation

Optional Integer/Dictionary. This parameter applies a datum transformation while projecting geometries in the results when out_sr is different than the layer’s spatial reference. When specifying transformations, you need to think about which datum transformation best projects the layer (not the feature service) to the outSR and sourceSpatialReference property in the layer properties. For a list of valid datum transformation ID values ad well-known text strings, see Using spatial references. For more information on datum transformations please see the transformation parameter in the Project 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 the FeatureLayer has supportsAsyncApplyEdits set to True, then edits can be applied asynchronously. If True, a future object will be returned and the process will 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 a Future object. Call result() to get the response.

# Usage Example 1:

feature = [
{
    'attributes': {
        'ObjectId': 1,
        'UpdateDate': datetime.datetime.now(),
    }
}]
lyr.edit_features(updates=feature)
# Usage Example 2:

adds = {"geometry": {"x": 500, "y": 500, "spatialReference":
                    {"wkid": 102100, "latestWkid": 3857}},
        "attributes": {"ADMIN_NAME": "Fake Location"}
        }
lyr.edit_features(adds=[adds])
# Usage Example 3:

lyr.edit_features(deletes=[2542])
property estimates

Returns up-to-date approximations of layer information, such as row count and extent. Layers that support this property will include infoInEstimates information in the layer’s properties.

Currently available with ArcGIS Online and Enterprise 10.9.1+

Returns:

Dict[str, Any]

export_attachments(output_folder, label_field=None)

Exports attachments from the FeatureLayer in Imagenet format using the output_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

property field_groups

Returns the defined list of field groups for a given layer.

Returns:

dict[str,Any]

classmethod fromitem(item, index=0)

The fromitem method returns the layer at the specified index from a layer Item 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, where=None)

Groups data using the supplied definition (classification definition) and an optional where clause. The result is a renderer object.

Note

Use baseSymbol and colorRamp to define the symbols assigned to each class. If the operation is performed on a table, the result is a renderer object containing the data classes 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. See Classification Objects for additional details.

where

Optional string. A where clause for which the data needs to be classified. Any legal SQL where clause operating on the fields in the dynamic layer/table is allowed.

Returns:

A JSON Dictionary

# Example Usage
FeatureLayer.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)

The get_html_popup method provides details about the HTML pop-up authored by the User 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, query_string='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 attributes before unique values are returned. ex. “name_2 like ‘%K%’”

Returns:

A list of unique values

# Usage Example with only a "where" sql statement

>>> from arcgis.features import FeatureLayer

>>> 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']
property manager

The manager property is a helper object to manage the FeatureLayer, such as updating its definition.

Returns:

A FeatureLayerManager

# Usage Example

>>> manager = FeatureLayer.manager
property metadata

Get the Feature Layer’s metadata.

Note

If metadata is disabled on the GIS or the layer does not support metadata, None will be returned.

Returns:

String of the metadata, if any

property properties

The properties property retrieves and set properties of this object.

query(where='1=1', out_fields='*', time_filter=None, geometry_filter=None, return_geometry=True, return_count_only=False, return_ids_only=False, return_distinct_values=False, return_extent_only=False, group_by_fields_for_statistics=None, statistic_filter=None, result_offset=None, result_record_count=None, object_ids=None, distance=None, units=None, max_allowable_offset=None, out_sr=None, geometry_precision=None, gdb_version=None, order_by_fields=None, out_statistics=None, return_z=False, return_m=False, multipatch_option=None, quantization_parameters=None, return_centroid=False, return_all_records=True, result_type=None, historic_moment=None, sql_format=None, return_true_curves=False, return_exceeded_limit_features=None, as_df=False, datum_transformation=None, time_reference_unknown_client=None, **kwargs)

The query method queries a FeatureLayer based on a sql statement.

Parameter

Description

where

Optional string. SQL-92 WHERE clause syntax on the fields in the layer is supported for most data sources. Some data sources have restrictions on what is supported. Hosted feature services in ArcGIS Enterprise running on 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 specify the wildcard “*” as the value of this parameter. In this case, the query results include all the field values.

Note

If specifying return_count_only, return_id_only, or return_extent_only as 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 data source resides in an enterprise geodatabase and more than 1,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 the distance is 100, the query geometry is a point, units is set to meters, and all points within 100 meters of the point are returned.

units

Optional string. The unit for calculating the buffer distance. If unit is not specified, the unit is derived from the geometry spatial reference. If the geometry spatial reference is not specified, the unit is derived from the feature service data spatial reference. This parameter only applies if supportsQueryWithDistance 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>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as

datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of out_sr. If out_sr is not specified, max_allowable_offset is assumed to be in the unit of the spatial reference of the layer.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

geometry_precision

Optional Integer. This option can be used to specify the number of decimal places in the response geometries returned by the query operation. This applies to X and Y values only (not m or z-values).

gdb_version

Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If this is not specified, the query will apply to the published map’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 the fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true. This parameter can be used with return_count_only to return the count of distinct values 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 only includes an array of object IDs. Otherwise, the response is a feature set. When object_ids are specified, setting this parameter to true 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. This option supersedes the returnIdsOnly parameter. If returnCountOnly = true, the response will return both the count and the extent.

return_extent_only

Optional boolean. If true, the response only includes the extent of the features that would be returned by the query. If returnCountOnly=true, the response will return both the count and the extent. The default is false. This parameter applies only if the supportsReturningQueryExtent property of the layer is true.

order_by_fields

Optional string. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

Note

If specifying return_count_only, return_id_only, or return_extent_only as 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 to be grouped for calculating the statistics. example: STATE_NAME, GENDER

out_statistics

Optional list of dictionaries. The definitions for one or more field-based statistics 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-based statistics can be added, e.g. statisticType, onStatisticField, or outStatisticFieldName.

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 if the 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 if the 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 of a multipatch feature will be returned.

result_offset

Optional integer. This option can be used for fetching query results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th). This option is ignored if return_all_records is True (i.e. by default).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s max_record_count property. This option is ignored if return_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 associated with each feature returned. If true, the result includes the geometry centroid. The default is false. Only supported on layer with polygon geometry type.

return_all_records

Optional boolean. When True, the query operation will call the service until all records that satisfy the where_clause are returned. Note: result_offset and result_record_count will be ignored if return_all_records is True. Also, if return_count_only, return_ids_only, or return_extent_only are True, this parameter will be ignored.

result_type

Optional string. The result_type parameter can be used to control the number of features returned by the query operation. Values: None | standard | tile

historic_moment

Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

sql_format

Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

return_true_curves

Optional boolean. When set to true, returns true curves in output geometries. When set to false, curves are converted to densified polylines or polygons.

return_exceeded_limit_features

Optional boolean. Optional parameter which is true by default. When set to true, features are returned even when the results include ‘exceededTransferLimit’: True.

When set to false and querying with resultType = tile features are not returned when the results include ‘exceededTransferLimit’: True. This allows a client to find the resolution in which the transfer limit is no longer exceeded without making multiple calls.

as_df

Optional boolean. If True, the results are returned as a DataFrame instead of a FeatureSet.

datum_transformation

Optional Integer/Dictionary. This parameter applies a datum transformation while projecting geometries in the results when out_sr is different than the layer’s spatial reference. When specifying transformations, you need to think about which datum transformation best projects the layer (not the feature service) to the outSR and sourceSpatialReference property in the layer properties. For a list of valid datum transformation ID values ad well-known text strings, see Coordinate systems and transformations. For more information on datum transformations, please see the transformation parameter in the Project 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 Query function. This will allow users to pass additional parameters not explicitly implemented on the function. A complete list of functions available is documented on the Query REST API.

Returns:

A FeatureSet containing the features matching the query unless another return type is specified, such as return_count_only, return_extent_only, or return_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]
<Feature 1>
# 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 containting total count
# Usage Example with "StatisticFilter" parameter

>>> from arcgis._impl.common._filters import StatisticFilter
>>> 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=None, out_fields=None, object_ids=None, distance=None, units=None, time_filter=None, geometry_filter=None, gdb_version=None, return_distinct_values=None, order_by_fields=None, group_by_fields_for_statistics=None, out_statistics=None, result_offset=None, result_record_count=None, historic_moment=None, sql_format=None, format_3d_objects=None, time_reference_unknown_client=None)

The query3D operation allows clients to query 3D object features and is based on the feature service layer query operation. The 3D object feature layer 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 layer is supported for most data sources. Some data sources have restrictions on what is supported. Hosted feature services in ArcGIS Enterprise running on 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 specify the wildcard “*” as the value of this parameter to return all fields 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 data source resides in an enterprise geodatabase and more than 1,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 the distance is 100, the query geometry is a point, units is set to meters, and all points within 100 meters of the point are returned.

units

Optional string. The unit for calculating the buffer distance. If unit is not specified, the unit is derived from the geometry spatial reference. If the geometry spatial reference is not specified, the unit is derived from the feature service data spatial reference. This parameter only applies if supportsQueryWithDistance 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>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as

datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

gdb_version

Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If this is not specified, the query will apply to the published map’s version.

return_distinct_values

Optional boolean. If true, it returns distinct values based on the fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true. This parameter can be used with return_count_only to return the count of distinct values 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 the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

Note

If specifying return_count_only, return_id_only, or return_extent_only as 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 to be grouped for calculating the statistics. example: STATE_NAME, GENDER

out_statistics

Optional list of dictionaries. The definitions for one or more field-based statistics 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 results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th). This option is ignored if return_all_records is True (i.e. by default).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s max_record_count property. This option is ignored if return_all_records is True (i.e. by default).

historic_moment

Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

sql_format

Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

format_3d_objects

Optional string. Specifies the 3D format that will be used to request a feature. If set to a valid format ID (see layer resource), the geometry of the feature response will be a 3D envelope of the 3D object and will include 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 format is not ready. Request the feature again later.

If a feature does not have the specified format, the feature will still be returned according to the query parameters (such as the where clause), but the asset 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. Setting time_reference_unknown_client as True indicates that the client is capable of working with data values that are not in UTC. If its not set to true, and the service layer’s datesInUnknownTimeZone 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 returned as-is from the database, rather than as date values in UTC. Non-hosted feature services can be set to use an unknown time zone using ArcGIS Server Manager. Setting the time zones to unknown also sets the datesInUnknownTimeZone layer property as true. Currently, hosted feature services do not support this setting. This setting does not apply to editor tracking date fields which are stored and returned in UTC even when the time zone is set to unknown.

Most clients released prior to ArcGIS Enterprise 10.9 will not be able to work with feature services that have an unknown time setting.

Returns:

A dictionary containing the feature, asset map, and asset information for the layer.

USAGE EXAMPLE: Query 3D objects

# Import the required modules
from arcgis.gis import GIS
from arcgis.features import FeatureLayer

# Connect to your GIS
gis = GIS(profile="your_enterprise_profile")

# Search for the feature layer
search_result = gis.content.search("3D Object Feature Layer", "Feature Layer")
feature_layer = search_result[0]

# Create a FeatureLayer object
layer = FeatureLayer(feature_layer.url, gis)

# Query the 3D objects
result = layer.query_3d(where="OBJECTID < 10", out_fields="*", format_3d_objects="3D_dae")
print(result)
query_analytics(out_analytics, where='1=1', out_fields='*', analytic_where=None, geometry_filter=None, out_sr=None, return_geometry=True, order_by=None, result_type=None, cache_hint=None, result_offset=None, result_record_count=None, quantization_param=None, sql_format=None, future=True, **kwargs)

The query_analytics exposes the standard SQL windows functions that compute aggregate and ranking values based on a group of rows called window partition. The window function is applied to the rows after the partitioning and ordering of the rows. query_analytics defines a window or user-specified set of rows within a query result set. query_analytics can be used to compute aggregated values such as moving averages, 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 partition or window) that are related to the current row. Unlike regular aggregate functions, use of a window function does not return single output row. The rows retain their separate identities with each calculation appended to the rows as a new field value. The window function can access more than just the 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 on a set of values and return a single value. They are used in the select list with optional HAVING clause. GROUP BY clause can also be used to calculate the aggregation on categories of rows. query_analytics can be used to calculate the aggregation on a specific range of value. Supported aggregate functions are:

  • Min

  • Max

  • Sum

  • Count

  • AVG

  • STDDEV

  • VAR

Analytic Functions

Several analytic functions available now in all SQL vendors to compute an aggregate value based on a group of rows or windows partition. Unlike aggregation functions, analytic functions can return single or multiple rows for 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. Depending on 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 over different group of rows. It is very powerful and has many potential usages. For example, you can add partition by to your window specification to look at different groups of rows individually.

partitionBy clause divides the query result set into partitions and the sql window function is applied to each partition. The ‘partitionBy’ clause normally refers to the column by which the result is partitioned. ‘partitionBy’ can also be a value expression (column expression or function) 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 analytics to be computed. This parameter is supported only on layers/tables that return true for supportsAnalytics property.

Note

If outAnalyticFieldName is empty or missing, the server assigns a 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

See Overview for 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": <double value>,// percentile value
         "partitionBy": "<field name or expression>",
         "offset": <integer>, // used by LAG/LEAD
         "windowFrame": {
            "type": "ROWS" | "RANGE",
            "extent": {
               "extentType": "PRECEDING" | "BOUNDARY",
               "PRECEDING": {
                  "type": <"UNBOUNDED" |
                          "NUMERIC_CONSTANT" |
                           "CURRENT_ROW">
                   "value": <numeric constant value>
                }
                "BOUNDARY": {
                 "start": "UNBOUNDED_PRECEDING",
                          "NUMERIC_PRECEDING",
                           "CURRENT_ROW",
                 "startValue": <numeric constant value>,
                 "end": <"UNBOUNDED_FOLLOWING" |
                         "NUMERIC_FOLLOWING" |
                         "CURRENT_ROW",
                 "endValue": <numeric constant value>
                }
              }
            }
         }
    }
  }
]
# 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 specified either 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 to the result set of applying the source where clause and all other params.

geometry_filter

Optional from arcgis.geometry.filter. Allows for the information to be filtered on spatial relationship with another geometry.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

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 the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

result_type

Optional string. The result_type parameter can be used to control the 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 results quicker. The default is False.

result_offset

Optional integer. This option can be used for fetching query results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of 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 standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

future

Optional Boolean. This determines if a Future object is returned (True) the method returns the results directly (False).

Returns:

A Pandas DataFrame (pd.DataFrame)

query_date_bins(bin_field, bin_specs, out_statistics, time_filter=None, geometry_filter=None, bin_order=None, where=None, return_centroid=False, in_sr=None, out_sr=None, spatial_rel=None, quantization_params=None, result_offset=None, result_record_count=None, return_exceeded_limit_features=False)

The query_date_bins operation is performed on a FeatureLayer. 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 or sum, and may also include the aggregate geometries (in other words, centroid) for point layers.

The parameters define the bins, the aggregate information returned, and the included features. Bins are defined using the bin parameter. The out_statistics and return_centroid parameters define the information each bin will provide. Included features can be specified by providing a time extent, where condition, and a spatial filter, similar to a query operation.

The contents of the bin_specs parameter provide flexibility for defining bin boundaries. The bin_specs parameter’s unit property defines the time width of each bin, such as one year, quarter, month, day, or hour. Fixed bins can use multiple units for these time widths. The result_offset property defines an offset within that time unit. For example, if your bin unit is day, and you want bin boundaries to go from noon to noon on the next day, the offset would be 12 hours.

Features can be manipulated with the time_filter, where, and geometry_filter parameters. By default, the result will expand to fit the feature’s earliest and latest point of time. The time_filter parameter defines a fixed starting point and ending point of the features based on the field used in binField. The where and geometry_filter parameters allow additional filters to be put on the data.

This operation is only supported on feature services using a spatiotemporal data store. As well, the service property supportsQueryDateBins must be set to true.

To use pagination with aggregated queries on hosted feature services in ArcGIS Enterprise, the supportsPaginationOnAggregatedQueries property must be true on the layer. Hosted feature services using a spatiotemporal data store do not currently support pagination on aggregated queries.

Parameter

Description

bin_field

Required String. The date field used to determine which bin each feature falls into.

bin_specs

Required Dict. A dictionary that describes the characteristics of bins, such as the size of the bin and its starting position. The size of each bin is determined by the number of time units denoted by the number and unit properties.

The starting position of the bin is the earliest moment in the specified unit. For example, each year begins at midnight of January 1. An offset inside the bin parameter can provide an offset to the starting position of the bin. This can contain a positive or negative integer value.

A bin can take two forms: either a calendar bin or a fixed bin. A calendar bin is aware of calendar-specific adjustments, such as daylight saving time and leap seconds. Fixed bins are, by contrast, always a specific unit of measurement (for example, 60 seconds in a minute, 24 hours in a day) regardless of where the date and time of the bin starts. For this reason, some calendar-specific units are only 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-based statistics 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>] using datetime.date, datetime.datetime or timestamp in milliseconds.

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

bin_order

Optional String. Either “ASC” or “DESC”. Determines whether results are returned in ascending or descending order. Default is ascending.

where

Optional String. A WHERE clause for the query filter. SQL ‘92 WHERE clause syntax on the fields in the layer is supported for most data sources.

return_centroid

Optional Boolean. Returns the geometry centroid associated with all the features in the bin. If true, the result includes the geometry centroid. The default is false. This parameter is only supported on point data.

in_sr

Optional Integer. The WKID for the spatial reference of the input geometry.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

spatial_rel

Optional String. The spatial relationship to be applied to the input geometry while performing the query. The supported spatial relationships include intersects, contains, envelop intersects, within, and so on. The default spatial relationship is intersects (esriSpatialRelIntersects). Other options are esriSpatialRelContains, esriSpatialRelCrosses, esriSpatialRelEnvelopeIntersects, esriSpatialRelIndexIntersects, esriSpatialRelOverlaps, esriSpatialRelTouches, and esriSpatialRelWithin.

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}
    }
}

See Quantization parameters JSON properties for details on format of this parameter.

Note

This parameter only applies if the layer’s supportsCoordinateQuantization property is true.

result_offset

Optional Int. This parameter fetches query results by skipping the specified number of records and starting from the next record. The default is 0.

Note:

This parameter only applies if the layer’s supportsPagination property is true.

result_record_count

Optional Int. This parameter fetches query results up to the value specified. When result_offset is specified, but this parameter is not, the map service defaults to the layer’s maxRecordCount property. The maximum value for this parameter is the value of the maxRecordCount property. The minimum value entered for this parameter cannot be below 1.

Note:

This parameter only applies if the layer’s supportsPagination property is true.

return_exceeded_limit_features

Optional Boolean. When set to True, features are returned even when the results include "exceededTransferLimit": true. This allows a client to find the resolution in which the transfer limit is no longer exceeded withou making multiple calls. The default value is False.

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
  }

The query_related_records operation is performed on a FeatureLayer resource. The result of this operation are feature sets grouped by source layer/table object IDs. Each feature set contains Feature objects including the values for the fields requested by the user. For related layers, if you request geometry information, the geometry of each feature is also returned in the feature set. For related tables, the feature set does not include 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/layer to be included in the returned feature set. This list is a comma delimited list of field names. If you specify the shape field in the list of return fields, it is ignored. To request geometry, set return_geometry to true. You can also specify the wildcard “*” as the value of this parameter. In this case, the results will include all the field values.

definition_expression

Optional string. The definition expression to be applied to the related table/layer. From the list of objectIds, only those records that conform to this expression are queried for related records.

return_geometry

Optional boolean. If true, the feature set includes the geometry associated with each feature. The default is true.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of the outSR. If out_wkid is not specified, then max_allowable_offset is 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 of decimal 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 parameter applies only if the isDataVersioned property of the layer queried is true.

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the 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 parameter applies only if the supportsQueryWithHistoricMoment property of the layers being queried is set to true. This setting is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

Syntax: historic_moment=<Epoch time in milliseconds>

return_true_curves

Optional boolean. Optional parameter that is false by default. When set to true, returns true curves in output geometries; otherwise, curves are converted to densified Polyline or Polygon 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=None, where=None, objectids=None, start_time=None, end_time=None, geometry_filter=None, out_fields='*', return_geometry=True, return_centroid=False, max_allowable_offset=None, out_sr=None, geometry_precision=None, return_ids_only=False, return_extents_only=False, order_by_field=None, return_z=False, return_m=False, result_type=None, as_df=True)

The query_top_features is performed on a FeatureLayer. This operation returns a feature set or spatially enabled dataframe based on the top features by order within a group. For example, when querying counties in the United States, you want to return the top five counties by population in each state. To do this, you can use query_top_features to group by state name, order by desc on the 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 in generating the result. The operation also has many of the same parameters (for example, where and geometry) as the layer query operation. However, unlike the layer query operation, query_top_feaures does not support parameters such as outStatistics and its related parameters or return distinct values. Consult the advancedQueryCapabilities layer property for more details.

If the feature layer collection supports the query_top_feaures 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. The top_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 in either 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 WHERE clause syntax on the fields in the layer is supported for most data sources.

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 to be 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 be added to the output.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of out_sr. If out_sr is not specified, max_allowable_offset is assumed to be in the unit of the spatial reference of the layer.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

geometry_precision

Optional Integer. This option can be used to specify the number of decimal places in the response geometries returned by the query operation. 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 only includes an array of object IDs. Otherwise, the response is a feature set.

return_extent_only

Optional boolean. If true, the response only includes the extent of the features that would be returned by the query. If returnCountOnly=true, the response will return both the count and the extent. The default is false. This parameter applies only if the supportsReturningQueryExtent property of the layer is true.

order_by_field

Optional Str. Optional string. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the 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 number of 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 a FeatureSet. If `return_count_only=True`, the return type is Integer. If `return_ids_only=True`, a list of value is returned.

property renderer

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-insensitive dict like object used to update and alter JSON A varients of a case-less dictionary that allows for dot and bracket notation.

property time_filter

The time_filter method is used to set a time filter instead of querying time-enabled map service layers or time-enabled feature service layers, a time filter can be specified. Time can be filtered as a single instant or by separating 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 single or list of start/stop date.

Returns:

A string of datetime values as milliseconds from epoch

update_metadata(file_path)

The update_metadata updates a FeatureLayer 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, sql_type='where')

The validate_sql operation validates an SQL-92 expression or WHERE clause. The validate_sql operation ensures that an SQL-92 expression, such as one written by a user through a user interface, is correct before performing another operation that uses the expression.

Note

For example, validateSQL can be used to validate information that is subsequently passed in as part of the where parameter of the calculate operation.

validate_sql also prevents SQL injection. In addition, all table and field names used in the SQL expression or WHERE clause are validated 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 user can 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 a new field or using the calculate API.

  • statement - Represents the full SQL-92 statement that can be passed directly to the database. No current ArcGIS REST API resource or operation supports using the full SQL-92 SELECT statement directly. It has been added to the validateSQL for completeness. Values: where | expression | statement

Returns:

A JSON Dictionary indicating ‘success’ or ‘error’

Table

class arcgis.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” as Feature objects, the GIS can also work with non-spatial entities as rows in tables.

Note

Working with tables is similar to working with :class:`~arcgis.features.FeatureLayer`objects, except that the rows (Features) in a table do not have a geometry, and tables ignore any geometry related operation.

append(item_id=None, upload_format='featureCollection', source_table_name=None, field_mappings=None, edits=None, source_info=None, upsert=False, skip_updates=False, use_globalids=False, update_geometry=True, append_fields=None, rollback=False, skip_inserts=None, upsert_matching_field=None, upload_id=None, layer_mappings=None, *, return_messages=None, future=False)

The append method is used to update an existing hosted FeatureLayer object. See the Append (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+

Parameter

Description

item_id

Optional string. The ID for the Portal item that contains the source file. Used in conjunction with editsUploadFormat.

upload_format

Required string. The source append data format. The default is featureCollection. Values: ‘sqlite’ | ‘shapefile’ | ‘filegdb’ | ‘featureCollection’ | ‘geojson’ | ‘csv’ | ‘excel’

Note

You can find the Feature Layer’s supported formats by checking the featureLayer.properties.supportedAppendFormats property.

source_table_name

Required string. Required even when the source data contains only one 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. Append supports all format through the upload_id or item_id.

source_info

Optional dictionary. This is only needed when appending data from excel or csv. The appendSourceInfo can be the publishing parameter returned from analyze the csv or excel file.

upsert

Optional boolean. Optional parameter specifying whether the edits needs 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 GlobalId when matching features.

update_geometry

Optional boolean. The parameter is used only when upsert is true. Skip updating the geometry and update only the attributes for existing features if they match source features by objectId or globalId.(as specified by useGlobalIds parameter).

append_fields

Optional list. The list of destination fields to append to. This is supported when upsert=true or false.

#Values:
["fieldName1", "fieldName2",....]

rollback

Optional boolean. Optional parameter specifying whether the upsert edits 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 is true. The default value is false.

upsert_matching_field

Optional string. The layer field to be used when matching features with upsert. ObjectId, GlobalId, and any other field that has a unique index can be used with upsert. This parameter overrides use_globalids; e.g., specifying upsert_matching_field will be used even if you specify use_globalids = True. Example: upsert_matching_field=”MyfieldWithUniqueIndex”

upload_id

Optional string. The itemID field from an upload() response, corresponding with the appendUploadId REST API argument. This argument should not be used along side the item_id argument.

layer_mappings

Optional list of dictionaries. This is needed if the source is featureService. It is used to map a source layer to a destination layer. Only one source can be mapped to a layer.

Syntax: layerMappings=[{“id”: <layerID>, “sourceId”: <layer id>}]

return_messages

Optional Boolean. When set to True, the messages returned from the append will be returned. If False, the response messages will not be returned. This alters the output to be a tuple consisting of a (Boolean, Dictionary).

future

Optional boolean. If True, a future object will be returned and the process will not wait for the task to complete. The default is False, which means wait for results.

Returns:

A boolean indicating success (True), or failure (False). When return_messages is True, the response messages will be return in addition to the boolean as a tuple. If future = True, then the result is a Future object. Call result() 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, calc_expression, sql_format='standard', version=None, sessionid=None, return_edit_moment=None, future=False)

The calculate operation is performed on a FeatureLayer resource. calculate updates the values of one or more fields in an existing feature service layer based on SQL expressions or scalar values. The calculate operation can only be used if the supportsCalculate property of the layer is True. Neither the Shape field nor system fields can be updated using calculate. System fields include ObjectId and GlobalId.

Inputs

Description

where

Required String. A where clause can be used to limit the updated records. Any legal SQL where clause operating on the fields in the layer is allowed.

calc_expression

Required List. The array of field/value info objects that contain the field or fields to update and their scalar values or SQL expression. Allowed types are dictionary and list. List must be a list of dictionary objects.

Calculation Format is as follows:

{“field” : “<field name>”, “value” : “<value>”}

sql_format

Optional String. The SQL format for the calc_expression. It can be either standard SQL92 (standard) or native SQL (native). The default is standard.

Values: standard, native

version

Optional String. The geodatabase version to apply the edits.

sessionid

Optional String. A parameter which is set by a client during long transaction editing on a branch version. The sessionid is a GUID value that clients establish at the beginning and use throughout the edit session. The sessonid ensures isolation during the edit session. This parameter applies only if the isDataBranchVersioned property of the layer is true.

return_edit_moment

Optional Boolean. This parameter specifies whether the response will report the time edits were applied. If true, the server will return the time edits were applied in the response’s edit moment key. This parameter applies only if the isDataBranchVersioned property of the layer is true.

future

Optional boolean. If True, a future object will be returned and the process will not wait for the task to complete. The default is False, 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 a Future object. Call result() 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"}))
property container

Get/Set the FeatureLayerCollection to which this layer belongs.

Parameter

Description

value

Required FeatureLayerCollection.

Returns:

The Feature Layer Collection where the layer is stored

property contingent_values

Returns the define contingent values for the given layer. :returns: Dict[str,Any]

delete_features(deletes=None, where=None, geometry_filter=None, gdb_version=None, rollback_on_failure=True, return_delete_results=True, future=False)

Deletes features in a FeatureLayer or Table

Parameter

Description

deletes

Optional string. A comma separated string of OIDs to remove from the service.

where

Optional string. A where clause for the query filter. Any legal SQL where 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 from arcgis.geometry.filters module to filter results by a spatial relationship with another geometry.

gdb_version

Optional string. The geodatabase version. This parameter applies only if the isDataVersioned property of the layer is true.

rollback_on_failure

Optional boolean. Optional parameter to specify if the edits should be applied only if all submitted edits succeed. If false, the server will apply the edits that succeed even if some of the submitted edits fail. If true, the server will apply the edits only if all edits succeed. The default value is true.

return_delete_results

Optional Boolean. Optional parameter that indicates whether a result is 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 process will 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 a Future object. Call result() to get the response.

# Usage Example with only a "where" sql statement

>>> from arcgis.features import FeatureLayer

>>> 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=None, updates=None, deletes=None, gdb_version=None, use_global_ids=False, rollback_on_failure=True, return_edit_moment=False, attachments=None, true_curve_client=False, session_id=None, use_previous_moment=False, datum_transformation=None, future=False)

Adds, updates, and deletes features to the associated FeatureLayer or Table in a single call.

Note

When making large number (250+ records at once) of edits, append should be used over edit_features to improve performance 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 service

use_global_ids

Optional boolean. Instead of referencing the default Object ID field, the service will look at a GUID field to track changes. This means the GUIDs will be passed instead of OIDs for delete, update or add features.

gdb_version

Optional string. The geodatabase version to apply edits. This parameter applies only if the isDataVersioned property of the layer is true.

rollback_on_failure

Optional boolean. Optional parameter to specify if the edits should be applied only if all submitted edits succeed. If false, the server will apply the edits that succeed even if some of the submitted edits fail. If true, the server will apply the edits only if all edits succeed. The default value is true.

return_edit_moment

Optional boolean. Introduced at 10.5, only applicable with ArcGIS Server services only. Specifies whether the response will report the time edits were applied. If set to true, the server will return the time in the response’s editMoment key. The default value is false.

attachments

Optional Dict. This parameter adds, updates, or deletes attachments. It applies only when the use_global_ids parameter is set to true. For adds, the globalIds of the attachments provided by the client are preserved. When useGlobalIds is true, updates and deletes are identified by each feature or attachment globalId, rather than their objectId or attachmentId. This parameter requires the layer’s supportsApplyEditsWithGlobalIds property to be true.

Attachments to be added or updated can use either pre-uploaded data or base 64 encoded data.

Inputs

Inputs

Description

adds

List of attachments to add.

updates

List of attachements to update

deletes

List of attachments to delete

See the Apply Edits to a Feature Service layer in the ArcGIS REST API for more information.

true_curve_client

Optional boolean. Introduced at 10.5. Indicates to the server whether the client is true curve capable. When set to true, this indicates to the server that true curve geometries should be downloaded and that geometries containing true curves should be consumed by the map service without densifying it. When set to false, this indicates to the server that the client is not true curves capable. The default value is false.

session_id

Optional String. Introduced at 10.6. The session_id is a GUID value that clients establish at the beginning and use throughout the edit session. The sessonID ensures isolation during the edit session. The session_id parameter is set by a client during long transaction editing on a branch version.

use_previous_moment

Optional Boolean. Introduced at 10.6. The use_previous_moment parameter is used to apply the edits with the same edit moment as the previous set of edits. This allows an editor to apply single block of edits partially, complete another task and then complete the block of edits. This parameter is set by a client during long transaction editing on a branch version.

When set to true, the edits are applied with the same edit moment as the previous set of edits. When set to false or not set (default) the edits are applied with a new edit moment.

datum_transformation

Optional Integer/Dictionary. This parameter applies a datum transformation while projecting geometries in the results when out_sr is different than the layer’s spatial reference. When specifying transformations, you need to think about which datum transformation best projects the layer (not the feature service) to the outSR and sourceSpatialReference property in the layer properties. For a list of valid datum transformation ID values ad well-known text strings, see Using spatial references. For more information on datum transformations please see the transformation parameter in the Project 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 the FeatureLayer has supportsAsyncApplyEdits set to True, then edits can be applied asynchronously. If True, a future object will be returned and the process will 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 a Future object. Call result() to get the response.

# Usage Example 1:

feature = [
{
    'attributes': {
        'ObjectId': 1,
        'UpdateDate': datetime.datetime.now(),
    }
}]
lyr.edit_features(updates=feature)
# Usage Example 2:

adds = {"geometry": {"x": 500, "y": 500, "spatialReference":
                    {"wkid": 102100, "latestWkid": 3857}},
        "attributes": {"ADMIN_NAME": "Fake Location"}
        }
lyr.edit_features(adds=[adds])
# Usage Example 3:

lyr.edit_features(deletes=[2542])
property estimates

Returns up-to-date approximations of layer information, such as row count and extent. Layers that support this property will include infoInEstimates information in the layer’s properties.

Currently available with ArcGIS Online and Enterprise 10.9.1+

Returns:

Dict[str, Any]

export_attachments(output_folder, label_field=None)

Exports attachments from the FeatureLayer in Imagenet format using the output_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

property field_groups

Returns the defined list of field groups for a given layer.

Returns:

dict[str,Any]

classmethod fromitem(item, table_id=0)

The fromitem method creates a Table from a Item object. The table_id is the id of the table in FeatureLayerCollection (feature service).

Parameter

Description

item

Required Item object. The type of item should be a Feature Service that represents a FeatureLayerCollection

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, where=None)

Groups data using the supplied definition (classification definition) and an optional where clause. The result is a renderer object.

Note

Use baseSymbol and colorRamp to define the symbols assigned to each class. If the operation is performed on a table, the result is a renderer object containing the data classes 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. See Classification Objects for additional details.

where

Optional string. A where clause for which the data needs to be classified. Any legal SQL where clause operating on the fields in the dynamic layer/table is allowed.

Returns:

A JSON Dictionary

# Example Usage
FeatureLayer.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)

The get_html_popup method provides details about the HTML pop-up authored by the User 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, query_string='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 attributes before unique values are returned. ex. “name_2 like ‘%K%’”

Returns:

A list of unique values

# Usage Example with only a "where" sql statement

>>> from arcgis.features import FeatureLayer

>>> 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']
property manager

The manager property is a helper object to manage the FeatureLayer, such as updating its definition.

Returns:

A FeatureLayerManager

# Usage Example

>>> manager = FeatureLayer.manager
property metadata

Get the Feature Layer’s metadata.

Note

If metadata is disabled on the GIS or the layer does not support metadata, None will be returned.

Returns:

String of the metadata, if any

property properties

The properties property retrieves and set properties of this object.

query(where='1=1', out_fields='*', time_filter=None, return_count_only=False, return_ids_only=False, return_distinct_values=False, group_by_fields_for_statistics=None, statistic_filter=None, result_offset=None, result_record_count=None, object_ids=None, gdb_version=None, order_by_fields=None, out_statistics=None, return_all_records=True, historic_moment=None, sql_format=None, return_exceeded_limit_features=None, as_df=False, having=None, time_reference_unknown_client=None, **kwargs)

The query method queries a Table 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 specified either 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>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as

datetime.date, datetime.datetime or timestamp in milliseconds

gdb_version

Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If this is not specified, the query will apply to the published map’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 the fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true.

return_ids_only

Optional boolean. Default is False. If true, the response only includes an array of object IDs. Otherwise, the response is a feature 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. This option supersedes the returnIdsOnly parameter. If returnCountOnly = true, the response will return both the count and the extent.

order_by_fields

Optional string. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

group_by_fields_for_statistics

Optional string. One or more field names on which the values need to be grouped for calculating the statistics. example: STATE_NAME, GENDER

out_statistics

Optional string. The definitions for one or more field-based statistics 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 results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th). This option is ignored if return_all_records is True (i.e. by default).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s max_record_count property. This option is ignored if return_all_records is True (i.e. by default).

return_all_records

Optional boolean. When True, the query operation will call the service until all records that satisfy the where_clause are returned. Note: result_offset and result_record_count will be ignored if return_all_records is True. Also, if return_count_only, return_ids_only, or return_extent_only are True, this parameter will be ignored.

historic_moment

Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

sql_format

Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

return_exceeded_limit_features

Optional boolean. Optional parameter which is true by default. When set to true, features are returned even when the results include ‘exceededTransferLimit’: True.

When set to false and querying with resultType = tile features are not returned when the results include ‘exceededTransferLimit’: True. This allows a client to find the resolution in which the transfer limit is no longer exceeded without making multiple calls.

as_df

Optional boolean. If True, the results are returned as a DataFrame instead of a FeatureSet.

kwargs

Optional dict. Optional parameters that can be passed to the Query function. This will allow users to pass additional parameters not explicitly implemented on the function. A complete list of functions available is documented on the Query REST API.

Returns:

A FeatureSet object or, if `as_df=True`, a Panda’s DataFrame containing the features matching the query unless another return type is specified, such as return_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]
<Feature 1>
# 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=None, out_fields=None, object_ids=None, distance=None, units=None, time_filter=None, geometry_filter=None, gdb_version=None, return_distinct_values=None, order_by_fields=None, group_by_fields_for_statistics=None, out_statistics=None, result_offset=None, result_record_count=None, historic_moment=None, sql_format=None, format_3d_objects=None, time_reference_unknown_client=None)

The query3D operation allows clients to query 3D object features and is based on the feature service layer query operation. The 3D object feature layer 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 layer is supported for most data sources. Some data sources have restrictions on what is supported. Hosted feature services in ArcGIS Enterprise running on 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 specify the wildcard “*” as the value of this parameter to return all fields 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 data source resides in an enterprise geodatabase and more than 1,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 the distance is 100, the query geometry is a point, units is set to meters, and all points within 100 meters of the point are returned.

units

Optional string. The unit for calculating the buffer distance. If unit is not specified, the unit is derived from the geometry spatial reference. If the geometry spatial reference is not specified, the unit is derived from the feature service data spatial reference. This parameter only applies if supportsQueryWithDistance 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>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as

datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

gdb_version

Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If this is not specified, the query will apply to the published map’s version.

return_distinct_values

Optional boolean. If true, it returns distinct values based on the fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true. This parameter can be used with return_count_only to return the count of distinct values 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 the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

Note

If specifying return_count_only, return_id_only, or return_extent_only as 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 to be grouped for calculating the statistics. example: STATE_NAME, GENDER

out_statistics

Optional list of dictionaries. The definitions for one or more field-based statistics 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 results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th). This option is ignored if return_all_records is True (i.e. by default).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s max_record_count property. This option is ignored if return_all_records is True (i.e. by default).

historic_moment

Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

sql_format

Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

format_3d_objects

Optional string. Specifies the 3D format that will be used to request a feature. If set to a valid format ID (see layer resource), the geometry of the feature response will be a 3D envelope of the 3D object and will include 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 format is not ready. Request the feature again later.

If a feature does not have the specified format, the feature will still be returned according to the query parameters (such as the where clause), but the asset 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. Setting time_reference_unknown_client as True indicates that the client is capable of working with data values that are not in UTC. If its not set to true, and the service layer’s datesInUnknownTimeZone 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 returned as-is from the database, rather than as date values in UTC. Non-hosted feature services can be set to use an unknown time zone using ArcGIS Server Manager. Setting the time zones to unknown also sets the datesInUnknownTimeZone layer property as true. Currently, hosted feature services do not support this setting. This setting does not apply to editor tracking date fields which are stored and returned in UTC even when the time zone is set to unknown.

Most clients released prior to ArcGIS Enterprise 10.9 will not be able to work with feature services that have an unknown time setting.

Returns:

A dictionary containing the feature, asset map, and asset information for the layer.

USAGE EXAMPLE: Query 3D objects

# Import the required modules
from arcgis.gis import GIS
from arcgis.features import FeatureLayer

# Connect to your GIS
gis = GIS(profile="your_enterprise_profile")

# Search for the feature layer
search_result = gis.content.search("3D Object Feature Layer", "Feature Layer")
feature_layer = search_result[0]

# Create a FeatureLayer object
layer = FeatureLayer(feature_layer.url, gis)

# Query the 3D objects
result = layer.query_3d(where="OBJECTID < 10", out_fields="*", format_3d_objects="3D_dae")
print(result)
query_analytics(out_analytics, where='1=1', out_fields='*', analytic_where=None, geometry_filter=None, out_sr=None, return_geometry=True, order_by=None, result_type=None, cache_hint=None, result_offset=None, result_record_count=None, quantization_param=None, sql_format=None, future=True, **kwargs)

The query_analytics exposes the standard SQL windows functions that compute aggregate and ranking values based on a group of rows called window partition. The window function is applied to the rows after the partitioning and ordering of the rows. query_analytics defines a window or user-specified set of rows within a query result set. query_analytics can be used to compute aggregated values such as moving averages, 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 partition or window) that are related to the current row. Unlike regular aggregate functions, use of a window function does not return single output row. The rows retain their separate identities with each calculation appended to the rows as a new field value. The window function can access more than just the 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 on a set of values and return a single value. They are used in the select list with optional HAVING clause. GROUP BY clause can also be used to calculate the aggregation on categories of rows. query_analytics can be used to calculate the aggregation on a specific range of value. Supported aggregate functions are:

  • Min

  • Max

  • Sum

  • Count

  • AVG

  • STDDEV

  • VAR

Analytic Functions

Several analytic functions available now in all SQL vendors to compute an aggregate value based on a group of rows or windows partition. Unlike aggregation functions, analytic functions can return single or multiple rows for 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. Depending on 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 over different group of rows. It is very powerful and has many potential usages. For example, you can add partition by to your window specification to look at different groups of rows individually.

partitionBy clause divides the query result set into partitions and the sql window function is applied to each partition. The ‘partitionBy’ clause normally refers to the column by which the result is partitioned. ‘partitionBy’ can also be a value expression (column expression or function) 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 analytics to be computed. This parameter is supported only on layers/tables that return true for supportsAnalytics property.

Note

If outAnalyticFieldName is empty or missing, the server assigns a 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

See Overview for 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": <double value>,// percentile value
         "partitionBy": "<field name or expression>",
         "offset": <integer>, // used by LAG/LEAD
         "windowFrame": {
            "type": "ROWS" | "RANGE",
            "extent": {
               "extentType": "PRECEDING" | "BOUNDARY",
               "PRECEDING": {
                  "type": <"UNBOUNDED" |
                          "NUMERIC_CONSTANT" |
                           "CURRENT_ROW">
                   "value": <numeric constant value>
                }
                "BOUNDARY": {
                 "start": "UNBOUNDED_PRECEDING",
                          "NUMERIC_PRECEDING",
                           "CURRENT_ROW",
                 "startValue": <numeric constant value>,
                 "end": <"UNBOUNDED_FOLLOWING" |
                         "NUMERIC_FOLLOWING" |
                         "CURRENT_ROW",
                 "endValue": <numeric constant value>
                }
              }
            }
         }
    }
  }
]
# 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 specified either 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 to the result set of applying the source where clause and all other params.

geometry_filter

Optional from arcgis.geometry.filter. Allows for the information to be filtered on spatial relationship with another geometry.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

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 the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

result_type

Optional string. The result_type parameter can be used to control the 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 results quicker. The default is False.

result_offset

Optional integer. This option can be used for fetching query results by skipping the specified number of records and starting from the next record (that is, resultOffset + 1th).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of 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 standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native

future

Optional Boolean. This determines if a Future object is returned (True) the method returns the results directly (False).

Returns:

A Pandas DataFrame (pd.DataFrame)

query_date_bins(bin_field, bin_specs, out_statistics, time_filter=None, geometry_filter=None, bin_order=None, where=None, return_centroid=False, in_sr=None, out_sr=None, spatial_rel=None, quantization_params=None, result_offset=None, result_record_count=None, return_exceeded_limit_features=False)

The query_date_bins operation is performed on a FeatureLayer. 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 or sum, and may also include the aggregate geometries (in other words, centroid) for point layers.

The parameters define the bins, the aggregate information returned, and the included features. Bins are defined using the bin parameter. The out_statistics and return_centroid parameters define the information each bin will provide. Included features can be specified by providing a time extent, where condition, and a spatial filter, similar to a query operation.

The contents of the bin_specs parameter provide flexibility for defining bin boundaries. The bin_specs parameter’s unit property defines the time width of each bin, such as one year, quarter, month, day, or hour. Fixed bins can use multiple units for these time widths. The result_offset property defines an offset within that time unit. For example, if your bin unit is day, and you want bin boundaries to go from noon to noon on the next day, the offset would be 12 hours.

Features can be manipulated with the time_filter, where, and geometry_filter parameters. By default, the result will expand to fit the feature’s earliest and latest point of time. The time_filter parameter defines a fixed starting point and ending point of the features based on the field used in binField. The where and geometry_filter parameters allow additional filters to be put on the data.

This operation is only supported on feature services using a spatiotemporal data store. As well, the service property supportsQueryDateBins must be set to true.

To use pagination with aggregated queries on hosted feature services in ArcGIS Enterprise, the supportsPaginationOnAggregatedQueries property must be true on the layer. Hosted feature services using a spatiotemporal data store do not currently support pagination on aggregated queries.

Parameter

Description

bin_field

Required String. The date field used to determine which bin each feature falls into.

bin_specs

Required Dict. A dictionary that describes the characteristics of bins, such as the size of the bin and its starting position. The size of each bin is determined by the number of time units denoted by the number and unit properties.

The starting position of the bin is the earliest moment in the specified unit. For example, each year begins at midnight of January 1. An offset inside the bin parameter can provide an offset to the starting position of the bin. This can contain a positive or negative integer value.

A bin can take two forms: either a calendar bin or a fixed bin. A calendar bin is aware of calendar-specific adjustments, such as daylight saving time and leap seconds. Fixed bins are, by contrast, always a specific unit of measurement (for example, 60 seconds in a minute, 24 hours in a day) regardless of where the date and time of the bin starts. For this reason, some calendar-specific units are only 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-based statistics 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>] using datetime.date, datetime.datetime or timestamp in milliseconds.

geometry_filter

Optional from filters. Allows for the information to be filtered on spatial relationship with another geometry.

bin_order

Optional String. Either “ASC” or “DESC”. Determines whether results are returned in ascending or descending order. Default is ascending.

where

Optional String. A WHERE clause for the query filter. SQL ‘92 WHERE clause syntax on the fields in the layer is supported for most data sources.

return_centroid

Optional Boolean. Returns the geometry centroid associated with all the features in the bin. If true, the result includes the geometry centroid. The default is false. This parameter is only supported on point data.

in_sr

Optional Integer. The WKID for the spatial reference of the input geometry.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

spatial_rel

Optional String. The spatial relationship to be applied to the input geometry while performing the query. The supported spatial relationships include intersects, contains, envelop intersects, within, and so on. The default spatial relationship is intersects (esriSpatialRelIntersects). Other options are esriSpatialRelContains, esriSpatialRelCrosses, esriSpatialRelEnvelopeIntersects, esriSpatialRelIndexIntersects, esriSpatialRelOverlaps, esriSpatialRelTouches, and esriSpatialRelWithin.

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}
    }
}

See Quantization parameters JSON properties for details on format of this parameter.

Note

This parameter only applies if the layer’s supportsCoordinateQuantization property is true.

result_offset

Optional Int. This parameter fetches query results by skipping the specified number of records and starting from the next record. The default is 0.

Note:

This parameter only applies if the layer’s supportsPagination property is true.

result_record_count

Optional Int. This parameter fetches query results up to the value specified. When result_offset is specified, but this parameter is not, the map service defaults to the layer’s maxRecordCount property. The maximum value for this parameter is the value of the maxRecordCount property. The minimum value entered for this parameter cannot be below 1.

Note:

This parameter only applies if the layer’s supportsPagination property is true.

return_exceeded_limit_features

Optional Boolean. When set to True, features are returned even when the results include "exceededTransferLimit": true. This allows a client to find the resolution in which the transfer limit is no longer exceeded withou making multiple calls. The default value is False.

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
  }

The query_related_records operation is performed on a FeatureLayer resource. The result of this operation are feature sets grouped by source layer/table object IDs. Each feature set contains Feature objects including the values for the fields requested by the user. For related layers, if you request geometry information, the geometry of each feature is also returned in the feature set. For related tables, the feature set does not include 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/layer to be included in the returned feature set. This list is a comma delimited list of field names. If you specify the shape field in the list of return fields, it is ignored. To request geometry, set return_geometry to true. You can also specify the wildcard “*” as the value of this parameter. In this case, the results will include all the field values.

definition_expression

Optional string. The definition expression to be applied to the related table/layer. From the list of objectIds, only those records that conform to this expression are queried for related records.

return_geometry

Optional boolean. If true, the feature set includes the geometry associated with each feature. The default is true.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of the outSR. If out_wkid is not specified, then max_allowable_offset is 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 of decimal 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 parameter applies only if the isDataVersioned property of the layer queried is true.

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the 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 parameter applies only if the supportsQueryWithHistoricMoment property of the layers being queried is set to true. This setting is provided in the layer resource.

If historic_moment is not specified, the query will apply to the current features.

Syntax: historic_moment=<Epoch time in milliseconds>

return_true_curves

Optional boolean. Optional parameter that is false by default. When set to true, returns true curves in output geometries; otherwise, curves are converted to densified Polyline or Polygon 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=None, where=None, objectids=None, start_time=None, end_time=None, geometry_filter=None, out_fields='*', return_geometry=True, return_centroid=False, max_allowable_offset=None, out_sr=None, geometry_precision=None, return_ids_only=False, return_extents_only=False, order_by_field=None, return_z=False, return_m=False, result_type=None, as_df=True)

The query_top_features is performed on a FeatureLayer. This operation returns a feature set or spatially enabled dataframe based on the top features by order within a group. For example, when querying counties in the United States, you want to return the top five counties by population in each state. To do this, you can use query_top_features to group by state name, order by desc on the 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 in generating the result. The operation also has many of the same parameters (for example, where and geometry) as the layer query operation. However, unlike the layer query operation, query_top_feaures does not support parameters such as outStatistics and its related parameters or return distinct values. Consult the advancedQueryCapabilities layer property for more details.

If the feature layer collection supports the query_top_feaures 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. The top_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 in either 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 WHERE clause syntax on the fields in the layer is supported for most data sources.

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 to be 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 be added to the output.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of out_sr. If out_sr is not specified, max_allowable_offset is assumed to be in the unit of the spatial reference of the layer.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

geometry_precision

Optional Integer. This option can be used to specify the number of decimal places in the response geometries returned by the query operation. 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 only includes an array of object IDs. Otherwise, the response is a feature set.

return_extent_only

Optional boolean. If true, the response only includes the extent of the features that would be returned by the query. If returnCountOnly=true, the response will return both the count and the extent. The default is false. This parameter applies only if the supportsReturningQueryExtent property of the layer is true.

order_by_field

Optional Str. Optional string. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the 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 number of 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 a FeatureSet. If `return_count_only=True`, the return type is Integer. If `return_ids_only=True`, a list of value is returned.

property renderer

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-insensitive dict like object used to update and alter JSON A varients of a case-less dictionary that allows for dot and bracket notation.

property time_filter

The time_filter method is used to set a time filter instead of querying time-enabled map service layers or time-enabled feature service layers, a time filter can be specified. Time can be filtered as a single instant or by separating 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 single or list of start/stop date.

Returns:

A string of datetime values as milliseconds from epoch

update_metadata(file_path)

The update_metadata updates a FeatureLayer 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, sql_type='where')

The validate_sql operation validates an SQL-92 expression or WHERE clause. The validate_sql operation ensures that an SQL-92 expression, such as one written by a user through a user interface, is correct before performing another operation that uses the expression.

Note

For example, validateSQL can be used to validate information that is subsequently passed in as part of the where parameter of the calculate operation.

validate_sql also prevents SQL injection. In addition, all table and field names used in the SQL expression or WHERE clause are validated 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 user can 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 a new field or using the calculate API.

  • statement - Represents the full SQL-92 statement that can be passed directly to the database. No current ArcGIS REST API resource or operation supports using the full SQL-92 SELECT statement directly. It has been added to the validateSQL for completeness. Values: where | expression | statement

Returns:

A JSON Dictionary indicating ‘success’ or ‘error’

FeatureLayerCollection

class arcgis.features.FeatureLayerCollection(url, gis=None)

A FeatureLayerCollection is the Python API representation of a Feature Service. Namely it is a collection of feature layers and tables with the associated relationships among the records.

Instances of a FeatureLayerCollection can be obtained

  • from Feature Layer items using the container property

  • using the fromitem() method

  • by initializing an object using the feature service url

# Using the container property
>>> from arcgis.gis import GIS
>>> gis = GIS(profile="your_organization_profile")

>>> flyr_item = gis.content.search("storm damage", "Feature Layer)[0]
>>> flc = flyr_item.layers[0].container
>>> flc

<FeatureLayerCollection url:"https://services8.arcgis.com/<org_id>/arcgis/rest/services/<service_name>/FeatureServer">

# Using the fromitem method
>>> from arcgis.features import FeatureLayerCollection

 >>> flyr_item = gis.content.search("storm damage", "Feature Layer)[0]
 >>> flc = FeatureLayerCollection.fromitem(flyr_item)

 <FeatureLayerCollection url:"https://services8.arcgis.com/<org_id>/arcgis/rest/services/<service_name>/FeatureServer">

# Initializing from a service url
>>> from arcgis.gis import GIS
>>> from arcgis.features import FeatureLayerCollection

>>> 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)

<FeatureLayerCollection https://services7.arcgis.com/<org_id>/arcgis/rest/services/<service_name>/FeatureServer>

The manager property accesses the FeatureLayerCollectionManager object which can be used to configure and manage the service.

If the feature service is configured for synchronization, the replicas property will be available to return a SyncManager object to manage that functionality.

Note

You can use the layers and tables property to get to the individual layers and tables in this feature layer collection.

extract_changes(layers, servergen=None, layer_servergen=None, queries=None, geometry=None, geometry_type=None, in_sr=None, version=None, return_inserts=False, return_updates=False, return_deletes=False, return_ids_only=False, return_extent_only=False, return_attachments=False, attachments_by_url=False, data_format='json', change_extent_grid_cell=None, return_geometry_updates=None, fields_to_compare=None, out_sr=None)

A method to query for changes that have been made to the layers and tables in a feature service.

To verify whether a feature service is configured to send responses about the features that have changed within its layers, query the service for the ChangeTracking capability:

# Get the capabilities a feature service is configured with
>>> from arcgis.gis import GIS
>>> 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 services as well as enterprise-geodatabase based ArcGIS Enterprise services.

Note

For Enterprise geodatabase based feature services published from ArcGIS Pro 2.2 or higher, the ChangeTracking capability requires all layers and tables to be either archive enabled or branch versioned and have globalid columns.

Parameter

Description

layers

Required List. The list of layers (by index value) and tables to include in the output.

# Get layer index values
>>> from arcgis.gis import FeatureLayerCollection

>>> flyr_item = gis.content.get("<>flyr_item_id>")
>>> flc = FeatureLayerCollection(flyr_item, gis)

>>> for flyr_obj in flc.layers:
>>>     print(f"{flyr_obj.properties.id<3}{lfyr_obj.properties.name}")

0  Airports
1  Roads
2  Railroads

servergen

Required integer (when layer_servergen argument not present). Introduced at 11.0, this argument provides the server generation numbers to apply to all layers included in the layers parameter from which to return changes.

Either a single generation value, or a pair of generation values can be provided.

  • If a single value is provided, all changes that have happened since that generation are returned.

  • If a pair of values are provided, the changes that have happened between the first generation (the minimum value) and up to and including the second generation (the maximum value) value are returned. The first value in the pair is expected to be the smaller value.

Query the FeatureLayerCollection properties to verify whether the feature service supports this capability. If the supportServerGens property in the extractChangesCapabilities property group is set to true, the capability is present.

# Determine whether parameter is supported
>>> from arcgis.gis import GIS
>>> 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 the servergen or layer_servergen argument must be provided with this method.

You can get the latest generation numbers from the changeTrackingInfo property 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 (if servergen argument not provided) of generation numbers for each layer to return changes. Use the changeTrackingInfo information 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 server data changes.

  • serverGen - It is the current server generation number of the changes. Every changed feature has a version or a generation number that 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 the layers and geometry parameters, the queries parameter can be used to further define what changes to return. This parameter allows you to set query properties on a per-layer or per-table basis. If a layer’s ID is present in the layers argument and missing from queries, the layer’s changed features that intersect with the geometry argument are returned.

The key-value options for the dictinary are:

  • where - Defines an attribute query for a layer or table. The default is no where clause.

  • useGeometry - Determines whether or not to apply the geometry for the layer. The default is True. If set to False, features from the layer that intersect the geometry are not added.

  • includeRelated - Determines whether or not to add related rows. The default is True and honored only when queryOption=None. This is only applicable if your data has relationship classes. Relationships are only processed in a forward direction from origin to destination.

  • queryOption - Defines whether or how filters will be applied to a layer. The queryOption was added in 10.2. See the Compatibility notes topic for more information.

    Valid values are:

Note

Info on queryOption key values:

  • If the value is None and the layer participates in a relationship:

    • If includeRelated is False, no related features are returned.

    • If includeRelated is True, features in this layer (that are related to the features in other layers) are returned.

  • If value is useFilter, features that satisfy filtering based on geometry and where 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 or Envelope object to apply as the spatial filter for the changes. All the changed features intersecting this geometry will be returned.

Note

For envelope and point geometries, you can specify the geometry with a simple comma-separated syntax instead of a json object.

geometry_type

Optional String. The type of geometry specified by the geometry parameter. The geometry type can be an envelope, point, line or polygon. The default geometry type is an envelope.

Values:

  • esriGeometryPoint

  • esriGeometryMultipoint

  • esriGeometryPolyline

  • esriGeometryPolygon

  • esriGeometryEnvelope

in_sr

Optional Integer. The wkid value of the input geometry spatial reference. See Coordinate systems PDFs for complete list of available values.

out_sr

Optional Integer. The wkid for the the spatial reference of the geometries in the returned changes. See Coordinate systems PDFs for complete list of available values.

version

Optional String. If branch versioning is enabled, and utilized with the service, a user can specify the verion name to extract changes from.

return_inserts

Optional Boolean, Required if neither return_updates nor return_deletes provided. If True, newly inserted features will be returned. The default is False.

return_updates

Optional Boolean. Required if neither return_inserts nor return_deletes provided.If True, updated features will be returned. The default is False.

return_deletes

Optional Boolean. Required if neither return_inserts nor return_updates provided. If True, deleted features will be returned. The default is False.

return_ids_only

Optional Boolean. If True, the response includes a list of object IDs only. The default is False.

return_extent_only

Option Boolean. If True, only the extent of the changes is returned. The default is False.

return_attachments

Optional Boolean. If True, attachment changes are returned in the response. Otherwise, attachments are not included. The default is False. This parameter is only applicable if the feature service has attachments.

attachments_by_url

Optional Boolean. If True, a reference to a URL will be provided for each attachment returned. Otherwise, attachments are embedded in the response. The default is True.

data_format

Optional String. The format of the changes returned in the response. The default is json. Values:

  • sqllite

  • json

change_extent_grid_cell

Optional String. To optimize localizing changes extent, the value of medium is an 8x8 grid that bound the changes extent.

Note

Used only when return_extent_only is True. Default is None.

Values:

  • None

  • large

  • medium

  • small

return_geometry_updates

Optional Boolean. If True, the response includes a ‘hasGeometryUpdates’ property set as true for each layer with updates that have geometry changes. The default is False.

If a layer’s edits include only inserts, deletes, or updates to fields other than geometry, hasGeometryUpdates is not set or is returned as false. When a layer has multiple rows with updates, only one needs to include a geometry changes for hasGeometryUpdates to be set as true.

fields_to_compare

Optional List. Introduced at 11.0. This parameter allows you to determine if any list of fields has been updated. The accepted values for this parameter is a list of fields you want to evaluate. The response returns a json array called fieldUpdates (accessed as a Python list) which includes rows that contain any updates made to the specified fields. An empty list is returned if no updates occurred 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

>>> from arcgis.gis import GIS
>>> from arcgis.features import FeatureLayerCollection

>>> 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': []}}]}
classmethod fromitem(item)

The fromitem method is used to create a FeatureLayerCollection from a Item class.

Parameter

Description

item

A required Item object. The item needed to convert to a FeatureLayerCollection object.

Returns:

A FeatureLayerCollection object.

property manager

A helper object to manage the FeatureLayerCollection, for example updating its definition.

Returns:

A FeatureLayerCollectionManager object

property properties

The properties property retrieves and set properties of this object.

query(layer_defs_filter=None, geometry_filter=None, time_filter=None, return_geometry=True, return_ids_only=False, return_count_only=False, return_z=False, return_m=False, out_sr=None)

Queries the current FeatureLayerCollection based on sql statement.

Parameter

Description

time_filter

Optional list. The format is of [<startTime>, <endTime>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as

datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter

Optional from arcgis.geometry.filter. Allows for the information to be 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 only includes an array of object IDs. Otherwise, the response is a feature 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. This option supersedes the returnIdsOnly parameter. If returnCountOnly = true, the response will return both the count and the extent.

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the 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 returned geometry.

Returns:

A FeatureSet of the queried Feature Layer Collection unless return_count_only or return_ids_only is True.

query_data_elements(layers)

The query_data_elements provides access to valuable information for datasets exposed through a feature service such as a feature layer, a table or a utility network layer. The response is dependent 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)

Returns full domain information for the domains referenced by the layers in the FeatureLayerCollection. This operation is performed on a feature layer collection. The operation takes an array of layer IDs and returns the set of domains referenced by 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, then the supportsQueryDomains property in the service properties is True. If this value is False or not present, then the service cannot use this operation. In addition, this is only availabel for arcobject and hosted Feature Services in Enterprise, not for ArcGIS Online.

Parameter

Description

layers

Required List. An array of layers. The set of domains to return is based on the domains referenced by these layers. Example: [1,2,3,4]

Returns:

List of dictionaries

The query_related_records operation is performed on a FeatureLayerCollection resource. The result of this operation are feature sets grouped by source FeatureLayer/Table object IDs. Each feature set contains Feature objects including the values for the fields requested by the User. For related layers, if you request geometry information, the geometry of each feature is also returned in the feature set. For related tables, the feature set does not include 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/layer to be included in the returned feature set. This list is a comma delimited list of field names. If you specify the shape field in the list of return fields, it is ignored. To request geometry, set return_geometry to true. You can also specify the wildcard “*” as the value of this parameter. In this case, the results will include all the field values.

definition_expression

Optional string. The definition expression to be applied to the related table/layer. From the list of objectIds, only those records that conform to this expression are queried for related records.

return_geometry

Optional boolean. If true, the feature set includes the geometry associated with each feature. The default is true.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of the outSR. If outSR is not specified, then max_allowable_offset is 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 of decimal 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 parameter applies only if the isDataVersioned property of the layer queried is true.

return_z

Optional boolean. If true, Z values are included in the results if the 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 if the features have M values. Otherwise, M values are not returned. The default is false.

Returns:

Dictionary of query results

property relationships

Gets relationship information for the layers and tables in the FeatureLayerCollection object.

The relationships resource includes information about relationship rules from the back-end relationship classes, in addition to the relationship information already found in the individual FeatureLayer and Table.

Feature layer collections that support the relationships resource will have the “supportsRelationshipsResource”: true property on their properties.

Returns:

List of Dictionaries

upload(path, description=None, upload_size=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 upload size of each part. The default is 1mb.

Returns:

Item id of uploaded item

property versions

Creates a VersionManager to create, update and use versions on a FeatureLayerCollection.

Note

If versioning is not enabled on the service, None is returned.

FeatureSet

class arcgis.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 their fields, field aliases, geometry type, spatial reference, and more.

FeatureSets are commonly used as input/output with several Geoprocessing Tools, and can be the obtained through the query 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 the fields requested by the User . For layers, if you request geometry information, the geometry of each feature is also returned in the FeatureSet. For tables, the FeatureSet does not include geometries.

If a Spatial Reference is not specified at the FeatureSet level, the FeatureSet will assume the SpatialReference of its first feature. If the Spatial Reference of the first feature is also not specified, the spatial reference will be UnknownCoordinateSystem.

property df

Warning

deprecated in v1.5.0 please use sdf

converts the FeatureSet to a Pandas dataframe. Requires pandas

property display_field_name

Get/Set the display field for the Feature Set object.

Parameter

Description

value

Required string.

Returns:

A String

property features

Gets the Feature objects in the FeatureSet object.

Returns:

A list of Feature objects

property fields

Get/Set the fields in the FeatureSet

Parameter

Description

value

Required dict.

Returns:

A dictionary

static from_arcpy(fs)

Converts an arcpy FeatureSet to an arcgis FeatureSet

Parameter

Description

fs

Required arcpy.FeatureSet. The featureset objec to consume.

Returns:

A FeatureSet object

static from_dataframe(df)

The from_dataframe method creates a FeatureSet objects from a Pandas’ DataFrame

Parameter

Description

df

Required DataFrame.

Returns:

A FeatureSet object

static from_dict(featureset_dict)

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:

A FeatureSet

static from_geojson(geojson)

Creates a Feature Set objects from a GEO JSON FeatureCollection object

Parameter

Description

geojson

Required GEOJSON object

Returns:

A FeatureSet object

static from_json(json_str)

Creates a Feature Set objects from a JSON string.

Parameter

Description

json_str

Required json style string.

Returns:

A FeatureSet object

property geometry_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

property global_id_field_name

Get/Set the global ID field for the Feature Set object.

Parameter

Description

value

Required string.

Returns:

A string

property has_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

property has_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

property object_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, out_name, encoding=None)

The save method saves a Feature Set object to a Feature 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 a repertoire of characters by some kind of encoding system. The default 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"
property sdf

Gets the Feature Set as a Spatially Enabled Pandas dataframe.

Returns:

A Spatially Enabled Pandas Dataframe object

property spatial_reference

Get/Set the Feature Set’s spatial reference

Parameter

Description

value

Required dict. (e.g. {“wkid” : 4326})

Returns:

A SpatialReference

to_dict()

Converts the Feature Set object to a Python dictionary.

Returns:

A Python dictionary of the FeatureSet

property to_geojson

Gets the Feature Set object as a GeoJSON.

Returns:

A GeoJSON object.

property to_json

Gets the Feature Set object as a JSON string.

Returns:

A JSON string of the FeatureSet

property value

Gets the Feature Set object as a dictionary.

Returns:

A dictionary of the FeatureSet

FeatureCollection

class arcgis.features.FeatureCollection(dictdata)

FeatureCollection is an object with a layer definition and a FeatureSet.

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 or scene, passed as inputs to feature analysis tools, and returned as results from feature analysis tools if an output name for a feature layer is not specified when calling the tool.

static from_featureset(fset, symbol=None, name=None)

Creates a FeatureCollection object from a FeatureSet object.

Parameter

Description

fset

Required FeatureSet object.

symbol

Optional dict. Specify your symbol as a dictionary. Symbols for points can be picked from the Esri Symbol Page

If not specified, a default symbol will be created.

name

Optional String. The name of the feature collection. This is used when feature collections are being persisted on a Map. If None is provided, 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"
property layer

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.

property properties

Returns a dictionary-like object of the current definition for the Feature Collection object. Each feature collection is comprised of a:

  • featureSet,

  • layerDefinition

  • popupInfo.

See the featureCollection Object Specification for full details.

Note

The properties and layer property of a FeatureCollection return the same information.

# Usage Example:
>>> from arcgis.gis import GIS
>>> 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 where clause is not supported for feature collections.

Returns:

A FeatureSet object

GeoAccessor

class arcgis.features.GeoAccessor(obj)

The GeoAccessor class adds a spatial namespace that performs spatial operations on the given Pandas DataFrame. The GeoAccessor class includes visualization, spatial indexing, IO and dataset level properties.

property area

The area method retrieves the total area of the GeoAccessor dataframe.

Returns:

A float

>>> df.spatial.area
143.23427
property bbox

The bbox property retrieves the total length of the dataframe

Returns:

Polygon

>>> df.spatial.bbox
{'rings' : [[[1,2], [2,3], [3,3],....]], 'spatialReference' {'wkid': 4326}}
property centroid

The centroid method retrieves the centroid of the dataframe

Returns:

Geometry

>>> df.spatial.centroid
(-14.23427, 39)
compare(other, match_field=None)

Compare the current spatially enabled DataFrame with another spatially enabled DataFrame and identify the differences in 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 between the 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

Parameter

Description

leafsize

Optional Integer. The number of points at which the algorithm switches 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)

Check if two DataFrames are equal to each other. Equal means same shape and corresponding elements

static from_arrow(table)

Converts a Pandas DatFrame to an Arrow Table

Parameter

Description

table

Required pyarrow.Table. The Arrow Table to convert back into a spatially enabled dataframe.

Returns:

pandas.DataFrame

static from_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 the name of a column in the specified dataframe that contains addresses (as strings). The addresses are batch geocoded using the GIS’s first configured geocoder and their locations used as the geometry of the spatial dataframe. Ignored if the ‘geometry_column’ is specified.

geocoder

Optional Geocoder. The geocoder to be used. If not specified, 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 to convert to the arcgis.Geometry Objects (new at version 1.8.1)

Returns:

Spatially Enabled DataFrame

NOTE: Credits will be consumed for batch_geocoding, from the GIS to which the geocoder belongs.

static from_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 string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. 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 builtin open function) or StringIO.

spatial_column

Optional String. The default is SHAPE. Specifies the column containing the geo-spatial information.

columns

Sequence/List/Array. The default is None. If not provided, all columns are read.

use_threads

Boolean. The default is True. Whether to parallelize reading using multiple threads.

Returns:

A Pandas DataFrame (pd.DataFrame)

static from_featureclass(location, **kwargs)

The from_featureclass creates a Spatially enabled pandas.DataFrame from a Features class.

Note

Null integer values will be changed to 0 when using shapely instead of ArcPy due to shapely conventions. With ArcPy null integer values will remain null.

Parameter

Description

location

Required string or pathlib.Path. Full path to the feature class or URL (shapefile only).

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 see ArcPy Search Cursor

where_clause

where statement. To learn more see ArcPy SQL reference

fields

list of strings specifying the field names.

spatial_filter

A Geometry object that will filter the results. This requires arcpy to work.

sr

A Spatial reference to project (or transform) output GeoDataFrame to. This requires arcpy to work.

datum_transformation

Used in combination with ‘sr’ parameter. if the spatial reference of output 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 requires arcpy to work.

Optional Parameters are not supported for URL based resources

Returns:

A pandas.core.frame.DataFrame object

static from_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 Enabled DataFrame object is returned. Default is False.

column_name

Optional String. Sets the name of the geometry column. Default

is SHAPE.

Returns:

A Spatially Enabled DataFrame.

static from_layer(layer)

The from_layer method imports a FeatureLayer to a Spatially Enabled DataFrame

Note

This operation converts a FeatureLayer or Table to a Pandas’ DataFrame

Parameter

Description

layer

Required FeatureLayer or TableLayer. The service to convert to a Spatially enabled DataFrame.

Usage:

>>> from arcgis.features import FeatureLayer
>>> mylayer = FeatureLayer(("https://sampleserver6.arcgisonline.com/arcgis/rest"
                    "/services/CommercialDamageAssessment/FeatureServer/0"))
>>> df = from_layer(mylayer)
>>> print(df.head())
Returns:

A Pandas’ DataFrame

static from_parquet(path, columns=None, **kwargs)

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 which columns you read:

  • if no geometry columns are read, this will raise a ValueError - you should use the pandas read_parquet method instead.

  • if the primary geometry column saved to this file is not included in columns, the first available geometry column will be set as the geometry column 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 s None. If not None, only these columns will be read from the file. If the primary geometry column is not included, the first secondary geometry read from the file will be set as the geometry column of the returned Spatially Enabled DataFrame. If no geometry columns are present, a ValueError will be raised.

kwargs

Optional dict. Any additional kwargs that can be given to the pyarrow.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"]
... )  
static from_table(filename, **kwargs)

The from_table method allows a User to read from a non-spatial table

Note

The from_table method requires ArcPy

Parameter

Description

filename

Required string or pathlib.Path. The path to the table.

Keyword Arguments

Parameter

Description

fields

Optional List/Tuple. A list (or tuple) of field names. For a single field, you can use a string instead of a list of strings.

Use an asterisk (*) instead of a list of fields if you want to access all fields from the input table (raster and BLOB fields are excluded). However, for faster performance and reliable field order, it is recommended that the list of fields be narrowed to only those that are actually needed.

Geometry, raster, and BLOB fields are not supported.

where

Optional String. An optional expression that limits the records returned.

skip_nulls

Optional Boolean. This controls whether records using nulls are skipped. Default is True.

null_value

Optional String/Integer/Float. Replaces null values from the input with a new value.

Returns:

A Pandas DataFrame (pd.DataFrame)

static from_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 DataFrame by 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 field will not be converted from int64 to int32.

Returns:

DataFrame

property full_extent

The full_extent method retrieves the extent of the DataFrame.

Returns:

A tuple

>>> df.spatial.full_extent
(-118, 32, -97, 33)
property geometry_type

The geometry_type property retrieves a list of Geometry Types for the DataFrame.

Returns:

A List

property has_m

The has_m property determines if the datasets have M values

Returns:

A boolean indicating M values (True), or not (False)

property has_z

The has_z property determines if the datasets have Z values

Returns:

A boolean indicating Z values (True), or not (False)

insert_layer(feature_service, gis=None, sanitize_columns=False, service_name=None)

This method creates a feature layer from the spatially enabled dataframe and adds (inserts) it to an existing feature service.

Note

Inserting table data in Enterprise is not currently supported.

Parameter

Description

feature_service

Required Item or Feature Service Id. Depicts the 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 to string, invalid characters removed and other performed. The default is False.

service_name

Optional String. The name for the service that will be added to the Item The name cannot be used already or contain special 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 based on spatial location based.

Note

The join method requires the Spatially-Enabled DataFrame to be in the same coordinate system

Parameter

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 is intersects.

supported perations: intersects, within, and contains

left_tag

Optional String. If the same column is in the left and right dataframe, this will append that string value to the field.

right_tag

Optional String. If the same column is in the left and right dataframe, this will append that string value to the field.

Returns:

Spatially enabled Pandas’ DataFrame

property length

The length method retrieves the total length of the DataFrame

Returns:

A float

>>> df.spatial.length
1.23427
property name

The name method retrieves the name of the geometry column.

Returns:

A string

overlay(sdf, op='union')

The overlay performs spatial operation operations on two spatially enabled dataframes.

Note

The overlay method requires ArcPy or Shapely

Parameter

Description

sdf

Required Spatially Enabled DataFrame. The geometry to perform the operation from.

op

Optional String. The spatial operation to perform. The allowed 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 to renderer spatial data using symbol.

Explicit Argument

Description

map_widget

optional Map object. This is the map to display the data on.

renderer

optional renderer dataclass. This can be created from the renderers module in the arcgis.map module.

project(spatial_reference, transformation_name=None)

The project method reprojects the who dataset into a new SpatialReference. This is an inplace operation meaning that it will update the defined geometry column from the set_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 using spatial relationships.

Note

The return is a Pandas DataFrame (pd.DataFrame) that meet the operations’ requirements.

Parameter

Description

other

Required Spatially Enabled DataFrame. The geometry to perform the operation from.

op

Optional String. The spatial operation to perform. The allowed 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. The allowed 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)

property renderer

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-insensitive dict like object used to update and alter JSON A 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 to noname, renaming duplicates with integer suffixes and switching spaces 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 is when 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 column names that are not numeric or underscores. This also ensures column names begin with alphabets by removing numeral prefixes.

inplace

Optional Boolean. Default is False. If True, edits the DataFrame in 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 names are in PascalCase or camelCase, it replaces them to snake_case.

Returns:

pd.DataFrame object if inplace= False . Else None .

select(other)

The select operation performs a dataset wide selection by geometric intersection. A geometry or another Spatially enabled DataFrame can be given and select will return all rows that intersect that input geometry. The select operation uses a spatial index to complete the task, so if it is not built before the first run, the function 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, this is the name of the column containing the geometry. If a Pandas Series GeoArray, list or tuple, it is an iterable of Geometry objects.

sr

Optional integer or spatial reference of the geometries described in the first parameter. If the geometry objects already have the spatial reference defined, this is not necessary. If the spatial reference for the 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 return a new dataframe. If True, nothing is returned and the dataframe is modified in 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 allow users 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 using the following command: conda install -c conda-forge rtree

Returns:

A spatial index for the given dataset.

property sr

The sr property gets and sets the SpatialReference of the dataframe

Parameter

Description

value

Spatial Reference

to_arrow(index=None)

Converts a Pandas DatFrame to an Arrow Table

Parameter

Description

index

Optional Bool. If True, always include the dataframe’s index(es) as columns in the file output. If False, the index(es) will not be written to the file. If None, the index(ex) will be included as columns in the file output except RangeIndex 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)

The to_feature_collection converts a spatially enabled a Pandas DataFrame to a FeatureCollection .

optional argument

Description

name

optional string. Name of the FeatureCollection

drawing_info

Optional dictionary. This is the rendering information for a Feature Collection. Rendering information is a dictionary with the symbology, labelling and other properties defined. See the Renderer Objects page in the ArcGIS REST API for more information.

extent

Optional dictionary. If desired, a custom extent can be provided to set where the map starts up when showing the data. The default is the full extent of the dataset in the Spatial DataFrame.

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. The default 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.

Parameter

Description

location

Required string. The output of the table.

overwrite

Optional Boolean. If True and if the feature class exists, it will be deleted and overwritten. This is default. If False, the feature class and the feature class exists, and exception will be raised.

has_z

Optional Boolean. If True, the dataset will be forced to have Z based geometries. If a geometry is missing a Z value when true, a RuntimeError will be raised. When False, the API will not use the Z value.

has_m

Optional Boolean. If True, the dataset will be forced to have M based geometries. If a geometry is missing a M value when true, a RuntimeError will be raised. When False, the API will not use the M value.

sanitize_columns

Optional Boolean. If True, column names will be converted to string, invalid characters removed and other checks will be performed. The default 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 new FeatureLayer object.

Note

Null integer values will be changed to 0 when using shapely instead of ArcPy due to shapely conventions. With ArcPy null integer values will remain null.

Parameter

Description

title

Optional string. The name of the service. If not provided, a random string is generated.

gis

Optional GIS. The GIS connection object

tags

Optional list of strings. A comma seperated list of descriptive words for the service.

folder

Optional string. Name of the folder where the featurelayer item and 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. The default 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 the service parameter will be overwritten. .. note:

Overwriting table data in Enterprise is not currently supported.

service

Dictionary that is required if overwrite = True. Dictionary with two keys: “FeatureServiceId” and “layers”. “featureServiceId” value is a string of the feature service id that the layer belongs to. “layer” value is an integer depicting the index value of the layer to overwrite.

Example: {“featureServiceId” : “9311d21a9a2047d19c0faaebd6f2cca6”, “layer”: 0}

Returns:

A FeatureLayer object.

to_featureset()

The to_featureset method converts a Spatially Enabled DataFrame object. to a FeatureSet object.

Returns:

A FeatureSet object

to_parquet(path, index=None, compression='gzip', **kwargs)

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 and associated metadata. This is tracking version 0.4.0 of the metadata specification 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’s index(es) as columns in the file output. If False, the index(es) will not be written to the file. If None, the index(ex) will be included as columns in the file output except RangeIndex 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 the pyarrow.parquet.write_table method.

Returns:

string

to_table(location, overwrite=True, **kwargs)

The to_table method exports a geo enabled dataframe to a Table object.

Note

Null integer values will be changed to 0 when using shapely instead of ArcPy due to shapely conventions. With ArcPy null integer values will remain null.

Parameter

Description

location

Required string. The output of the table.

overwrite

Optional Boolean. If True and if the table exists, it will be deleted and overwritten. This is default. If False, the table and the table exists, and exception will be raised.

sanitize_columns

Optional Boolean. If True, column names will be converted to string, invalid characters removed and other checks will be performed. The default is True.

Returns:

String

property true_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 the GeoAccessor is Valid with Geometry 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 the centroid is used for the geometry. The result is a Polygon GeoArray Series that matches 1:1 to the original dataset.

Note

The voronoi method requires SciPy

Returns:

A Pandas Series (pd.Series)

GeoSeriesAccessor

class arcgis.features.GeoSeriesAccessor(obj)
property JSON

The JSON method creates a JSON string out of the Geometry object.

Returns:

Series of strings

property WKB

The WKB method retrieves the Geometry object as a WKB

Returns:

A Series of Bytes

property WKT

The WKT method retrieves the Geometry object’s WKT

Returns:

Series of String

angle_distance_to(second_geometry, method='GEODESIC')

The angle_distance_to method retrieves a tuple of angle and distance to another point using a measurement method.

Parameter

Description

second_geometry

Required Geometry. A Geometry object.

method

Optional String. PLANAR measurements reflect the projection of geographic data onto the 2D surface (in other words, they will not take into account the curvature of the earth). GEODESIC, GREAT_ELLIPTIC, and LOXODROME 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.

property area

The area method retrieves the Feature object’s area.

return:

A float in a series

property as_arcpy

The as_arcpy method retrieves the features as an ArcPy geometry object.

Returns:

An arcpy.geometry as a series

property as_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 the Geometry object.

Returns:

A Pandas Series of Polyline objects

buffer(distance)

The buffer method constructs a Polygon at a specified distance from the Geometry object.

Parameter

Description

distance

Required float. The buffer distance. The buffer distance is in the same 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

property centroid

Returns the feature’s centroid

Returns:

tuple (x,y) in series

clip(envelope)

The clip method constructs the intersection of the Geometry object and the specified extent.

Parameter

Description

envelope

required tuple. The tuple must have (XMin, YMin, XMax, YMax) each value represents 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 base Geometry contains the comparison Geometry.

Parameter

Description

second_geometry

Required Geometry. A second geometry

relation

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 the Geometry that is the minimal bounding Polygon such that all outer angles are convex.

Returns:

A Pandas Series of Geometry objects

crosses(second_geometry)

The crosses method indicates if the two Geometry objects intersect in a geometry of 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 this Geometry into a part to the left of the cutting Polyline 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 new Geometry with added vertices

Parameter

Description

method

Required String. The type of densification, DISTANCE, ANGLE, or GEODESIC

distance

Required float. The maximum distance between vertices. The actual distance between vertices will usually be less than the maximum distance as new vertices will be evenly distributed along the original segment. If using a type of DISTANCE or ANGLE, the distance is measured in the units of the geometry’s spatial reference. If using a type of GEODESIC, the distance is measured in 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 and the original curve. The smaller its value, the more segments will be required to approximate the curve.

Returns:

A Pandas Series of Geometry objects

difference(second_geometry)

The difference method constructs the Geometry that is composed only of the region 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 comparison Geometry objects share no Point 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 two Geometry. 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 comparison Geometry objects are of the same shape type and define the same set of Point 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)

property extent

The extent method retrieves the feature’s extent

Returns:

A tuple (xmin,ymin,xmax,ymax) in series

property first_point

The first_point property retrieves the feature’s first Point object

Returns:

A Point object

generalize(max_offset)

The generalize method creates a new simplified Geometry using a specified maximum offset tolerance.

Note

This only works on Polyline and Polygon objects.

Parameter

Description

max_offset

Required float. The maximum offset tolerance.

Returns:

A Pandas Series of Geometry objects

property geoextent

The geoextent method retrieves the Geometry object’s extents

Returns:

A Series of Floats

property geometry_type

The geometry_type property retrieves the Geometry 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 of geographic data onto the 2D surface (in other words, they will not take into account the curvature of the earth). GEODESIC, GREAT_ELLIPTIC, LOXODROME, and PRESERVE_SHAPE measurement types may 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 of geographic data onto the 2D surface (in other words, they will not take into account the curvature of the earth). GEODESIC, GREAT_ELLIPTIC, LOXODROME, and PRESERVE_SHAPE measurement types may 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 of Point objects for a particular part of Geometry 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

property has_m

The has_m method determines if the Geometry objects has an M value

Returns:

A Series of Booleans

property has_z

The has_z method determines if the Geometry object has a Z value

Returns:

A Series of Booleans

property hull_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 a Geometry that is the geometric intersection of the two input geometries. Different dimension values can be used to create different shape types.

Note

The intersection of two Geometry objects of the same shape type is a geometry containing only the regions of overlap between the original geometries.

Parameter

Description

second_geometry

Required Geometry. A second geometry

dimension

Required Integer. The topological dimension (shape type) of the resulting 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

property is_empty

The is_empty method determines if the Geometry object is empty.

Returns:

A Series of Booleans

property is_multipart

The is_multipart method determines if features has multiple parts.

Returns:

A Series of Booleans

property is_valid

The is_valid method determines if the features Geometry is valid

Returns:

A Series of Booleans

property label_point

The label_point method determines the Point for the optimal label location.

Returns:

A Series of Geometry object

property last_point

The last_point method retrieves the Geometry of the last point in a feature.

Returns:

A Series of Geometry objects

property length

The length method retrieves the length of the features.

Returns:

A Series of floats

property length3D

The length3D method retrieves the length of the features

Returns:

A Series of floats

measure_on_line(second_geometry, as_percentage=False)

The measure_on_line method retrieves the measure from the start Point of this line to the in_point.

Parameter

Description

second_geometry

Required Geometry. A second geometry

as_percentage

Optional Boolean. If False, the measure will be returned as a distance; 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 two Geometry objects has the same shape type as one of the input geometries and is not equivalent to either 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)

property part_count

The part_count method retrieves the number of parts in a feature’s Geometry

Returns:

A Series of Integers

property point_count

The point_count method retrieves the number of Point objects in a feature’s Geometry.

Returns:

A Series of Integers

point_from_angle_and_distance(angle, distance, method='GEODESCIC')

The point_from_angle_and_distance retrieves a Point at a given angle and distance in 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 geographic data onto the 2D surface (in other words, they will not take into account the curvature of the earth). GEODESIC, GREAT_ELLIPTIC, LOXODROME, and PRESERVE_SHAPE measurement types may be chosen as an alternative, if desired.

Returns:

A Pandas Series of Geometry objects

position_along_line(value, use_percentage=False)

The position_along_line method retrieves a Point on a line at a specified distance 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 unit of measure or a ratio of the length of the line. If True, value is used as a percentage; if False, value is used as a distance. For percentages, the value should be expressed as a double from 0.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 a Geometry`and optionally applies a ``geotransformation`.

Parameter

Description

spatial_reference

Required SpatialReference. The new spatial reference. This can be a SpatialReference object or the coordinate system name.

transformation_name

Required String. The geotransformation name.

Returns:

A Pandas Series of Geometry objects

query_point_and_distance(second_geometry, use_percentage=False)

The query_point_and_distance finds the Point on the Polyline nearest to the in_point and the distance between those points.

Note

query_point_and_distance also returns information about the side of the line the in_point is on as well as the distance along the line where the nearest point occurs.

Parameter

Description

second_geometry

Required Geometry. A second geometry

as_percentage

Optional boolean - if False, the measure will be returned as distance, 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 a Polyline between start and end measures. Similar to positionAlongLine but will return a polyline segment between two points on the polyline instead of a single Point.

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 as fixed units or as a ratio. If True, start_measure and end_measure are used as a percentage; if False, start_measure and end_measure are used as a distance. For percentages, 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 new Point based on in_point snapped to this Geometry object.

Parameter

Description

second_geometry

Required Geometry. A second geometry

Returns:

A Pandas Series of Geometry objects

property spatial_reference

The spatial_reference method retrieves the SpatialReference of the Geometry

Returns:

A Series of SpatialReference objects.

symmetric_difference(second_geometry)

The symmetric_difference method constructs the Geometry that is the union of two geometries 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 the Geometry intersect.

Parameter

Description

second_geometry

Required Geometry. A second geometry

Returns:

A Pandas Series of booleans indicating touching (True), or not touching (False)

property true_centroid

The true_centroid method retrieves the true centroid of the Geometry object.

Returns:

A Series of Point objects

union(second_geometry)

The union method constructs the Geometry object that is the set-theoretic union of 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 base Geometry is within the comparison Geometry.

Parameter

Description

second_geometry

Required Geometry. A second geometry

relation

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

class arcgis.features._async.EditFeatureJob(future, connection)

Represents a Single Editing Job. The EditFeatureJob class allows for the asynchronous operation of the edit_features() method. This class is not intended for users to initialize directly, but is retuned by edit_features() when future=True.

Parameter

Description

future

Future. The future request.

connection

The GIS connection object.

cancelled()

Return True if the call was successfully cancelled.

Returns:

boolean

done()

Return True if the call was successfully cancelled or finished running.

Returns:

boolean

property messages

returns the GP messages

Returns:

List

result()

Return the value returned by the call. If the call hasn’t yet completed then this method will wait.

Returns:

object

running()

Return True if the call is currently being executed and cannot be cancelled.

Returns:

boolean

property status

returns the Job status

Returns:

bool - True means running, False means finished

property task

Returns the task name. :return: string

Submodules

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.